-2

i try to update a list with jquery but for some reason the POST function returns wierd objects. any ideas how to retrieve the data from the POST answer?

 var ans = jQuery.post("mysite.com", {name: "John"})
 var cont = jQuery( ans ).find( "#content" );
 alert(cont);

and the page:

<?php
   echo "<div id='content'>";
   echo $_POST['name'];
   echo '</div>';
?>

it alerts [object], when i try to read all the field of the object with:

answ = '';
for( var key in ans ) {
   answ = answ + 'key: ' + key + '\n' + 'value: ' + ans[key];
}
jQuery('#somediv').html( answ );

any ideas how to get what i echoed on the other page?

EDIT: i tried the following as you all suggested:

var ans = jQuery.post("mysite.com", {name: "John"});
jQuery.when(ans).then(function(answ){
var cont = jQuery( answ ).find( "#content" );
alert(cont);
});

and also:

var ans = jQuery.post("mysite.com", {name: "John"}, function(answ){
var cont = jQuery( answ ).find( "#content" ).html(); 
alert(cont);
});

but it still doesnt work. the alert simply doesnt show which means there is something wrong before it.

antonpuz
  • 3,256
  • 4
  • 25
  • 48

3 Answers3

1

jQuery.post returns a deffered, not the result of the request, because this is an asynchronous function and the script goes on while the request is handled.

One of the typical use of post is to pass a callback which will be called when the request is complete :

 jQuery.post("mysite.com", {name: "John"}, function(ans){
    var cont = jQuery( ans ).find( "#content" );
    // use cont
 });

But, as your URL is "mysite.com", you might also encounter a Same Origin Policy problem. To fix that you must set the relevant CORS headers on your server.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
0

Instead of the below code:

var cont = jQuery( ans ).find( "#content" );

Use the following code:

var cont = jQuery( ans ).find( "#content" ).html(); 
 //to get the content use the .html() or .text()
Code Lღver
  • 15,573
  • 16
  • 56
  • 75
0

@dystroy is right. you could also use the deffered:

var defer = jQuery.post("mysite.com", {name: "John"});
$.when(defer).then(function(ans){
    var cont = jQuery( ans ).find( "#content" );
    // use cont
});
R. Oosterholt
  • 7,720
  • 2
  • 53
  • 77