jQuery AJAX返回变量+值可能吗?

jQuery AJAX返回变量+值可能吗?

问题描述:

I'm submitting a form via jQuery.ajax()

Now my PHP script is checking if a specific input field is empty, example:

$is_error = $user->is_error;

if($is_error !=0)
 { 
    echo $is_error;
 }

Back to my jQuery.ajax() , I'd like to check if the value of $error was true or not, within the sucess: part of the jQuery.ajax() call.

   jQuery.ajax({
           type: "POST",
           url: "edit.php", 
           data: jQuery("#idForm").serialize(),
           success: function(data)
       {   

        // show response from the php script if there is an error message
        // like:
        //         if(is_error) {show specific error message}
        //         else {show everything positive message}

       }
    });

Is it possible to check the PHP variable's value in there? Like if/else ?

Best regards!

if($_POST['name'] == "") 
  {
    $error = 1;
  }
else 
  {
    $error = 0;
  }
echo $error;

This code will echo the value.

 jQuery.ajax({
           type: "POST",
           url: "edit.php", 
           data: jQuery("#idForm").serialize(),
           success: function(data)
       {   

        // show response from the php script if $error == 0 or $error == 1.
        if(data==1)
....
       }
    });

Then you check what is the returned value.

With your variable data, you can return values from PHP. And after in your scope success you can check.

You have to echo the error so that it can be returned as data.. The ajax only returns what has been created in html..

In instances like this I would use the following:

if($_POST['name'] == "") 
  {
    $error = 1;
  }
else 
  {
    $error = 0;
  }

echo $error;

jQuery.ajax({ type: "POST", url: "edit.php", data: jQuery("#idForm").serialize(), success: function(response) {

    if(response == 1){
        alert('Error');
    }else{
        alert('No error');
    }

   }
});

i think you should try the following in php script

echo $error;

and then in jquery.ajax() do

success: function(data){
 //data is $error
}