fiktionvt
fiktionvt

Reputation:

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 a a 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

Upvotes: 0

Views: 1753

Answers (5)

fiktionvt
fiktionvt

Reputation:

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.

Upvotes: 0

Rory
Rory

Reputation: 1

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>

Upvotes: 0

Brad G
Brad G

Reputation: 2583

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 );
   }
 });

Upvotes: 4

rasx
rasx

Reputation: 5338

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)

Upvotes: 1

SLaks
SLaks

Reputation: 887225

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(); ?>

Upvotes: 0

Related Questions