tags:

views:

104

answers:

2

i use $.get to run php file. how can i send key-value pair (eg. variables) from the php-file to jquery? and when sent, how can i retrieve them with jquery? i want to validate eg. if(key == value) in jquery.

and what is the difference between $.getJSON and $.get? if i want to run php i cannot use $.getJSON?

i tried in the php file use:

     echo '{"url": 1}';

i also tried:

    $json['url'] = 2;
    echo json_encode($json);

and in jquery file i use:

     alert(data.url);

but it didnt work. it displayed "undefined".

what is wrong

+3  A: 

You can use $.getJSON() with PHP. Javascript:

$(function() {
  $.getJSON("/some/script.php", function(data) {
    alert(data.url);
  });
});

On the PHP side use json_encode():

<?php
header("Content-Type: application/json");
$array = array('url' => 'http://www.google.com');
echo json_encode($array);
?>
cletus
if i dont want to use json_encode..how can i send them?
never_had_a_name
Why wouldn't you want to use json_encode()?
cletus
it doesnt work:s
never_had_a_name
A: 

Cletus's response answers your question, though I just wanted to point out the difference between $.get and $.getJSON.

It's very simple really:

// $.get is a shortcut for this:
$.ajax({
    method: "get"
});

// $.getJSON is just a shortcut for this:
$.ajax({
    method: "get",
    dataType : "json"
})

They're both just convenience-methods which pre-fill some of the parameters for you.

nickf
Yes, all the jQuery ajax methods are just shortcuts for $.ajax().
cletus
but what is the difference then between ajax with no dataType row and the other one with it? i mean, if i send back json key-value-pairs with json, will it work with the first method?
never_had_a_name