$(document.ready(){
var lookup = {
"shared_items":
[{"entity_id":"253","position":1}, {"entity_id":"823","position":2}]
}
$.ajax({
type: "GET",
cache:false,
contentType: 'application/json',
dataType: "json",
data: '{"name":"jonas"}',
success: function(data) {$("#result").html(data.name) },
}
});
});
I am new to ajax this is my first example towards can any one help me out.I want to pass json data {"name":"jonas"}
and display it .
Ajax
is a group of programming techniques that make asynchronous calls to other pages
without interfering with the display and the behavior of the existing page (from Wikipedia, Ajax Programming)
Data can be sent via GET
or POST
methods and retrieved as jqXHR
a superset of browser XHR
object. You can therefore use methods like getResponseHeader()
.
If you want to pass to ajaxexample.php
this array {"name":"Jonas"}
your JavaScript code will be
$.ajax({
type: GET //The method, either POST or GET
url: 'ajaxexample.php', //The page you call
data: {name:"Jonas"}, //Array automatically converted in string with jQuery.param(). You can also use directly the string 'name=Jonas'
})
.done(function( data ) {
//Do something with result data
});
If your page returns a json
object you can use instead
$.getJSON({ "ajaxexample.php?name=Jonas", //Passed parameters appended to URL
function (data) {
var message = data.message //Call to a json array element through its name (here 'message')
}
});
A trivial version of ajaxexample.php code written in PHP can be (if you want to return json encoded data)
$msg = "Hello " . $_GET["name"]; //Retrieves sent data
$resArray = array("message" => $msg); //Creates an array with return values
json_encode($resArray); //Passes it with valid json sintax