In a simple ajax post example:
$.post('ajax/test.php', function(data) {
$('.result').html(data);
});
Is there any way to separate the result data to do two different things? ie:
$.post('ajax/test.php', function(data) {
$('.result').html(data.partone);
$('.other-result').html(data.parttwo);
});
I run an ajax request when the page is loaded and I'm trying to get everything I need in one POST. If this is possible, how do you define the different data parts on the PHP side? (ie: data.partone and data.parttwo)
You can return the data as JSON encoded string, using json_encode() on an associative array, for example: echo json_encode(array("partone" => "data1", "parttwo" => "data2"));
That way you could access it as data.partone and data.parttwo. Also worth mentioning, you should define the dataType in the $.post() to be read as JSON. For that, you need to add another parameter to it, specifying the type of data you are returning - JSON.
For example: $.post('ajax/test.php', function(data) { ... }, "JSON");
Also worth mentioning, that you should return ONLY this json_encode() output back from the ajax script, else jQuery won't be able to parse it right.
An AJAX call only returns one response, which is stored in that data variable. However, what your server-side code returns as that response is up to you, and what you do with it in your Javascript is also up to you.
Assuming you're returning some HTML that you want to make the contents of some elements on your page, what you could do is separate the two parts in a way you can distinguish with Javascript. Perhaps something along the lines of:
/* part one here */|parttwo|/* part two here */
Then you just need to split data on the '|parttwo|' string, and use the elements of the resulting array to set the contents of your different elements.
Related
In my website I will have a "browse catalogue" button, which, onclick will change several elements of the page to display the catalogue element. I dont want a full page reload because several elements such as the nav bars and news feed will stay the same.
My question is how can i change several different divs with ajax onclick?
Essentially im not sure how to do place several different components in different divs across a page.
And i know there's a limit on simultaneous ajax calls, so im sure the proper way to do it wouldnt be to make a unique ajax call for each of my divs.
A little guidance would be great.
Using jQuery, you can get an json array of elements for each block that needs to be updated:
In your html page:
$.get("page.php?id=42",
function(result){
$('#title').text(result['title']);
$('#description').text(result['description']);
$('#price').text(result['price']);
}, "json");
In page.php:
$result = array('title' => 'foo', 'description' => 'bar', 'price' => 3);
echo json_encode($result);
header('Content-Type: application/json');
die();
I'm not sure if the right decision will be to send several ajax requests. Just create a request with unique attribute value, in so shape that server will know which blocks you need. On server side all required blocks concatenate in json object, and return it to client. After just parse object on blocks that should be. For example
$.ajax({
url : 'http://your.server.doment',
data : 'block[]=1&block[]=7&block[]=15',
type : 'post',
dataType : 'json',
success : function (object){
for( el in object) { $('#block_'+el).html(object[el]); }
}
});
you can use json
example
php request ajax
$div1="<table><tr><td>x</td></tr></table>";
$div2="<table><tr><td>x</td></tr></table>";
$div3="<table><tr><td>x</td></tr></table>";
$json = '{"div1":"'.$div1.'","div2":"'.$div2.'","div3":"'.$div3.'"}';
return $json;
uses jquery
$.ajax({url: 'ajax/test.php',
success: function(data) {
var obj = JSON.parse(data);
$("mydiv1").html(obj.div1);
$("mydiv2").html(obj.div2);
$("mydiv3").html(obj.div3);
}});
if you have a error in the parce function
replace spaces
example
$arr =array("\n","\t");
$div1= str_replace($arr,"",$div1);
Practically, ten or more elements updated in parallel on the page (each by a separate ajax) will not make such a big difference (unless you can test it with your website deployed into productive environment and prove I am wrong).
Nonetheless, if you wish to compact all the data exchange to one single request/response ajax call - it is very well possible but does require certain flexibility on the server side (see http://php.net/manual/en/function.json-encode.php).
I.e. one of the possible solutions is to produce json response on the server side, that generates a key-value pairs (JSON - javascript {} object) with keys being id of your elements and values being (new) html.
There are tons of ajax JS frameworks as jQuery, prototype, dojo, etc. (I will pick jQuery for this one).
Ajax request
$.ajax({
...
})
See http://api.jquery.com/jQuery.ajax/
Server response
// Assume we got
// var data = {key1:'html1',key2: 'html2'};
// Ajax handle can look like
success(data) {
$.each(data, function(key, val){
//console.log(key, val);
// Do some checks here.. But key should indicate #id of html elements
$(key).empty().append(html);
});
}
This is a basic outline but should keep you going into the right direction.
In an earlier post today the answer has led me down the route of using a JSON feed to populate elements in my page.
Something new to learn!!
the JSON data is created from a PHP script which retrieves the data from a Mysql database. The php script retrieves a specific record which I need to pass to the php script with the getJson call.
I've had success with creating the url with the parameters added as a GET method but I can't find an example of a POST method - the parameters should go as an optional parameter. here's what I have so far...
function loadData(index) {
alert(index);//debug
$.getJSON('loadJSONholeData.php' ,
{hole: index} ,
function(data) {
I've found examples for a twitter feed which shows a parameter like option: "cat", but can't find an option where the value is in a variable.
I don't understand how to use the parameters - where am I going wrong. Appreciate this is probably a fundamental issue but I'm learning.
Thanks
Update:
I've revised the code per the responses below and used both suggestions to pass the POST parameter, but the receiving PHP code is not reading the POST parameter and just returns the default query values.
I even used as static value of 1 both as a value and as a string but no joy.
Here's my receiving PHP code which accesses the POST values:
$hole = 3;
if (isset($_POST['hole'])) {
$hole = $_POST['hole'];
}
I'm missing something basic here. The value in 'index' definitely exists as it shows in the debug and JSON data is being returned )(but the default). I can go back to my GET method but want to see this work!!
Thanks
Update: Success!!
I played around further with the revised code. I removed the content type parameter from the code and it all works now, the PHP is returning the correct query.
I assume then that by specifying the JSON type in contentType it passes the POST parameter in a different way to PHP which expects it in anpther way?
Onwards and upwards - thanks
The $.getJSON() method does an HTTP GET and not POST. Try something like this -
$.ajax({
url: 'loadJSONholeData.php',
data: JSON.stringify({hole: index }),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
//(result.d) has your data.
}
});
Each key/value pair in the arguments object will represent a parameter in the HTTP POST. You can use variables as values, but I believe they will be converted to strings, so it's better to do the conversion yourself (so you can make sure they have the correct format). A simple example:
var dynamicValue = foo();
$.post('my/url', { var1:"static value", var2:dynamicValue }, function(data) {
// Your callback; the format of "data" will depend on the 4th parameter to post...
}, "json"); // ...in this case, json
Now, in case your server is expecting a json encoded object/list, you can pass it by using JSON.stringify:
function foo() {
return JSON.stringify({ my:"object" });
}
JSON should be available in most modern browsers, in case it's not, you can get it here (json2.js, under "JavaScript").
So I'm building a web application and I have an ajax request that pings a database (or database cache) and echos back a big thing of json. I'm totally new to json, and when the php pulls from the database I echo json_encode($databaseResults), then it shows up in my html page as a long string. My question is, how do I convert it and pull out the pieces I need into a nice format?
Thanks!
The Json result that was in the page looks like:
"[{\"currentcall\":\"1\",\"timecalled\":\"15:30\",\"etaTime\":\"15:35\",\"departmentID\":\"1\",\"memberID\":\"1\",\"callinnum\":\"1\",\"location\":\"Fire House\",\"billed\":\"N\",\"date\":\"2\\/12\\/11\",\"firstName\":\"Phil\",\"lastName\":\"asdf\",\"email\":\"pasdf#gmail.com\",\"homephone\":\"+19111111111\",\"cellphone\":\"+11234567891\",\"cellphone2\":null,\"workphone\":null,\"phonenumber5\":null,\"phonenumber6\":null,\"streetAddress\":\"10 asdfnt Dr\",\"city\":\"\",\"username\":\"pgsdfg\",\"password\":\"0623ab6b6b7dsasd3834799fbf2a08529d\",\"admin\":\"Y\",\"qualifications\":\"Interior\",\"rank\":null,\"cpr\":null,\"emt\":null,\"training\":null,\"datejoined\":null,\"dateactive\":null,\"state\":\"DE\",\"zip\":\"51264\",\"pending\":\"NO\",\"defaultETA\":\"7\",\"apparatus\":\"asdKE-286\"}]"
There can be multiple results... this is only one result
EDIT:
Basically, I'm trying to pass a bunch of rows in an array into an html file, and take out only the data I need and format it. I don't know if json is the best way to do this or not, just one solution I came up with. So if anyone has a better solution that would be awesome.
Edit2:
This is the jquery I have that makes the request, the php just has echo json_encode ($DBResults);
function getResponder(){
var responders = $.ajax({
type : "POST",
url: "/index.php/callresponse/get_responders",
success: function(html){
$("#ajaxDiv").html(html);
}
});
setTimeout("getResponder()", 10000);
}
As you flagged this as jquery I assume that you're using jQuery. If you're only going to get the one string you can skip the json part and use jQuery .load() like this $('#result').load('ajax/test.php'); that will load the contents from ajax/test.php into #result
However if you want to use json you can take a look over at getJSON on the jQuery documentation. You can also use the jQuery parseJSON function which will return the json an javascript object containing the jsonData.
Here's an example how you can use parseJSON
var object = $.praseJSON(jsonString); //jsonString is the string containing your actual json data
alert(object.location) //Will alert "Fire House" with the given json string
Here's an example of how you can use getJSON in the same way
$.getJSON('ajax/test.php', function(object) {
alert(object.location); //Will alert "Fire House" with the given json string
});
If you want to pass parameters as well you can do it like this
$.getJSON('ajax/test.php',
{
Param1 : "Value1",
Param2 : "value2"
},
function(object) {
alert(object.location); //Will alert "Fire House" with the given json string
}
);
If you are trying to send json from javascript to php you can use
$jsonArray = jsonDecode($_GET['key']);
Of course if you're using post you'll write $_POST instead.
You have to parse the data into a JSON object, then you can use properties of the object as you wish.
Without seeing the specifics, I can tell you that you'll need to use the JSON object to parse the text. See more here: http://www.json.org
var obj = JSON.parse(ajaxResponseText);
You should use php function json_decode which will give you an object or array with all the properties.
Then you should iterate recursively through this object and add the content of the properties to a string, which should be your final HTML.
Normally to display JSON response in an html element after jquery(for example) by web request, try this:
$("#box-content-selector").append(
"<pre>"+
JSON.stringify(JSON.parse(data), null, 4)+
"</pre>"
)
I've a php file which processes a query and returns an array.
How do i get these and array and parse them and display them using ajax.
I call the file using ajax. Its used to display the matching products while typing a text box with the price...
responseText doesn't return anything...
Your data needs to be encoded in a format that JavaScript can understand, like JSON. You want to serialize the PHP array and return that as the HTTP Response, more information on how to JSON serialize data can be found here. Once the data is serialized, you can parse it in the ResponseText as though it were a JavaScript object (i.e. you can pull data like this: ResponseText[0].some_key)
I should note that jQuery makes this very, VERY easy. Like... this easy:
var url = '/json-data.php?id=2';
$.getJSON(url, function(data) {
$("#target").text(data.some_key);
}
I want to send an array constructed in javascript with the selected values of a multiple select. Is there a way to send this array to a php script using ajax?
You might do that with $.post method of jQuery (for example) :
var myJavascriptArray = new Array('jj', 'kk', 'oo');
$.post('urltocallinajax', {'myphpvariable[]': myJavascriptArray }, function(data){
// do something with received data!
});
Php will receive an array which will be name myphpvariable and it will contain the myJavascriptArray values.
Is it that ?
You can post back to your server with XML or JSON. Your javascript will have to construct the post, which in the case of XML would require you to create it in javascript. JSON is not only lighterweight but easier to make in javascript. Check out JSON-PHP for parsing JSON.
You might want to take a look at Creating JSON Data in PHP
IIRC, if PHP sees a query string that looks like http://blah.com/test.php?var[]=foo&var[]=bar&var[]=baz, it will automatically make an array called $var that contains foo, bar and baz. I think you can even specify the array index in the square brackets of the query string and it will stick the value in that index. You may need to URL encode the brackets... The usual way this feature is used is in creating an HTML input field with the name "var[]", so just do whatever the browser normally does there. There's a section in the PHP documentation on array variables through the request.
You may be looking for a way to Serialize (jQuery version) the data.
jQuery 1.4 was updated to use the PHP syntax for sending arrays. You can switch it into the old style by using:
here is the synatax:
jQuery.ajaxSetting.traditional = true;
here is the example
$.ajax({
traditional: true,
type: "post",
url: myURL,
dataType: "text",
data: dataToSend, //this will be an array eg.
success: function(request) {
$('#results').html(request);
} // End success
}); // End ajax method
You can create an array and send it, as Meador recommended:
(following code is Mootooled, but similar in other libraries / plain old JS)
myArray.each(function(item, index) myObject.set('arrayItems['+index+']', item);
myAjax.send(myObject.toQueryString());
That will send to php an array called arrayItems, which can be accessed through $_POST['arrayItems']
echo $_POST['arrayItems'] ;
will echo something like: array=>{[0]=>'first thing', [1]=> second thing}