user1969371
user1969371

Reputation: 1

How to get data through $.ajax()

$.ajax({
    type: "GET",
    url: "wordtyping_sql.php",
    data: "id=" + id + "&formname=" + formname,
    success: function(msg){
        alert( "Data Saved: " + msg);
    }
});

msg that contains three lines from wordtyping_sql.php which are:

echo "one"; 
echo "two"; 
echo "three";

How do I get this data separately?

Upvotes: 0

Views: 136

Answers (2)

Jason Dean
Jason Dean

Reputation: 9615

Return the data as a JSON string. jQuery will parse it and turn it into an object you can work with.

$.ajax({
    type: "GET",
    url: "wordtyping_sql.php",
    data: "id=" + id + "&formname=" + formname,
    dataType: "json",
    success: function(msg){
        alert( "Data Saved: " + msg);
    }
});

wordtyping_sql.php

echo '["one","two","three"]'; 

Then inside of your successhandler you can access the data as msg[0], msg[1]. etc.

Upvotes: 0

Lix
Lix

Reputation: 47956

What you'll want to do is have your PHP code echo out some JSON data. Then you'll be able to access any one of the variables you wish.

In wordtyping_sql.php -

$data = array(
  'one' => 1,
  'two' => 2,
  'three' => 3
);
echo json_encode($data);

Now in your jQuery, you'll want to specify that your AJAX call is expecting a JSON in return -

$.ajax({
    type: "GET",
    url: "wordtyping_sql.php",
    data: "id=" + id + "&formname=" + formname,
    dataType : 'json', // <------------------ this line was added
    success: function(response){
        alert( response.one );
        alert( response.two );
        alert( response.three );
    }
});

Check out the relevant documentation pages for jQuery's AJAX method. Specifically the dataType parameter -

dataType - The type of data that you're expecting back from the server...

Upvotes: 5

Related Questions