简体   繁体   中英

Getting data returned from a jquery ajax call

I am trying to get the data return from a function called by a jquery ajax call. My function is located in aa php file and it looks liket his

valid_user() {

    $id = $_POST('id');

    if($id == 'hello'){
        return true;
    }
    else{
        return false;
    }
}

and here is my ajax call

$.ajax({
    type: "POST",
    url: path + "valid_user",
    sucess: function(msg) {
         alert("Data returned: " + msg );
     }
 });

I have tested everthing and the function is wokring ( has been changed for this example) but I can not the return value of the function valid_id(). How do I get this? the variable msg keeps coming back empty. Thanks

From my understanding, there are several issues.

1) the method valid_user() is not been called.
2) The url doesn't look like it is correct either.
3) The "success" keyword is spelt "sucess".
4) You aren't passing any "data".

Here is an example ajax call tailored to what you may want.

 $.ajax({
   type: "POST",
   url: "validateUser.php",
   data: "id=49",
   success: function(msg){
     alert( "true or false: " + msg );
   }
 });

It looks like you misspelled sucess ----but this may not be in your running code. You should check the second parameter of success :

success:function(data, textStatus)

You need to write PHP server-side code that calls the function and writes its return value to the output stream. For example:

<?php echo valid_user(); ?>

This should work - you might want to put better sanitizing on the POST value just in case.

In the PHP file:

$id = isset($_POST['id']) ? trim($_POST['id']) : '';
$return = 'false';

if($id!=''){
   valid_user($id);
}

echo $return;

valid_user($id) {
    if($id == 'hello'){
        $return = 'true';
    }
}

jQuery Call:

<script>
id = 'hello';    
$.ajax({
   type: "POST",
   url: "validateUser.php?id="+id,
   success: function(msg) {
      alert("Data returned: " + msg );
   }
});
</script>

Thank you for your help, I figured out the issue, the reason why it was not working was becuase my function valid_id() was returning true or false, and I needed to return echo "true"; and echo "false"; once I did this the msg variable contained the data true or false.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM