views:

80

answers:

3

i dont understand one thing.

if i want to get JSON data (key-value-pairs) from php to jquery using ajax...which of these following ones should i use?

  • $.get
  • $.post
  • $.getJSON

do i need to use getJSON if i want to use json_encode in php file? but what if i want to send with post? (there is no postJSON)?

and one more thing:

in php file i wrote:

<?php
  if($_GET['value'] == "value")
  {
  $array['firstname'] = 'Johnny'; 

  $jsonstring=json_encode($array); 

  return $jsonstring; 
  }
?>

in jquery file

  $.getJSON("php.php", {value: "value"}, function(data){
   alert(data.firstname);
  });

why doesnt this work??:S

+3  A: 

The problem lies with the line in PHP:

return $jsonstring;

You should echo it instead:

echo $jsonstring;

As for which jQuery method to use, I suggest $.getJSON() if you can return a pure json string. It really depends on how you use it.

When using $.getJSON(), your server file should return a JSON string. Thus echoing the string returned by json_encode() would be appropriate for the $.getJSON() method to take in the response.

thephpdeveloper
but in tutorials i have seen they are using return. and it seemed to work..?
never_had_a_name
no it won't. At times you can't trust tutorials.
thephpdeveloper
what if i send multiple json_encode() values with echo in a php? the last one will be the one jquery retrieves?
never_had_a_name
That would depend on the browser. It might use that last one, or the first one, or just error out and use nothing. Better to wrap it all into a `json_encode` if you need to do that: `json_encode(array(json_encode($data1), json_encode($data2)));`
Atli
the best way is still to consolidate all data into one single array, parse it through json_encode, and echo it.
thephpdeveloper
just to remind you that using GET in AJAX is much efficient. try googling on this. I read one article which touches on this.
thephpdeveloper
A: 

You can use .ajax, this allows you to do both get and post.

Ngu Soon Hui
You could also just use `$.get` or `$.post` ;-]
Atli
A: 

I always use $.ajax.

$.ajax({
     url: "script.php",
     type: "POST",
     data: { name : "John Doe" },
     dataType: 'json',
     success: function(msg){
        alert(msg);
     }
});

in PHP:

$name = $_POST['name']
echo $name

this will alert "John Doe"

also, if it's not working, use firebug to see values being passed around.

lyrae
is post much better than get? because i send password values to the php, so post is better for security reason?
never_had_a_name
and why dont they do a $.postJSON?
never_had_a_name
You could just as well use `$.post(url, data, callback, 'json')`. No reason to type out all that when they have wrapped it into a nice shortcut function for you. Not unless you plan to do something out of the ordinary.
Atli
@ fayer - POST or GET is up to you. I don't know why they don't have $.postJSON@ Atli: $.POST doesn't have a 'success', 'error' and 'complete' callback.
lyrae