i'm working on an php-application, and now i have to build an interface to communicate between jquery and php. i already have a working controller/action. what is the best way to communicate with jQuery, if i need to send an array to php in the request.
example:
data that is needed to fulfill the request:
$request_data = array
(
'key1' => 'value1',
'list1' => array
(
'listkey1' => 'listvalue1',
)
)
should i send this in different as "normal" post-request, or is it easier to send one post-var with the array encoded in json? ($post_json="{key: value....})
the focus is on easy integration in jquery
edit: it is not about passing the data to the client, it is about passing the array from the client to the php-script
use phps json_encode() to generate the response, and read it with jquery on client?
$.getJSON('youpage.php', function(data) {
$.each(data, function(key, value) {
alert(key + '=>' + value);
});
}
http://php.net/manual/en/function.json-encode.php
UPDATE
in regards to communication the other way, from the client to php. It all depends on the task at hand really. If the data in the drop down purely depend on the entries on the form, and they are otherwise stateless. Then,the best route will depends on your backend code, you could do a ajax post, with the individual variables, or concatenate them into one variable before sending, and then splitting them up on the backend. Or, as you say, you could create a json string and then use json_decode on the backend.
Which route is fit for purpose depends on many factors, and I dont think there is a right or wrong error.
Personally, I would generate a AJAX post request (im not a php coder though) to the backend, and then process the request object directly. You still would need to process a data structure, so why add the overhead/extra-step of deserializing json from the request.
You can use jquery post
$.post('url', data, function(data) {
console.log(data);
});
YOu can access the data in php
echo $_POST['key1'];
echo $_POST['key2'];
Related
I´m having problems to process Json Data in PHP via an Ajax call. I´m reading Json data from a Web Service.
I receive the data via JQuery getJSON method and if I stringify the data I have the following data structure:
[{"id":"788","name":"Tunisia","name_es":"Túnez","iso2":"TN","prefix":"216","zones":[{"id":"3805","name":"Beja","code":"31"},{"id":"3806","name":"Ben Arous","code":"13"},{"id":"3807","name":"Bizerte","code":"23"},{"id":"3808","name":"Gabes","code":"81"},{"id":"3809","name":"Gafsa","code":"71"},{"id":"3810","name":"Jendouba","code":"32"},{"id":"3811","name":"Kairouan","code":"41"},{"id":"3812","name":"Kasserine","code":"42"},{"id":"3813","name":"Kebili","code":"73"},{"id":"3815","name":"L'Ariana","code":"12"},{"id":"3814","name":"La Manouba","code":"14"},{"id":"3816","name":"Le Kef","code":"33"},{"id":"3817","name":"Mahdia","code":"53"},{"id":"3818","name":"Medenine","code":"82"},{"id":"3819","name":"Monastir","code":"52"},{"id":"3820","name":"Nabeul","code":"21"},{"id":"3821","name":"Sfax","code":"61"},{"id":"3822","name":"Sidi Bouzid","code":"43"},{"id":"3823","name":"Siliana","code":"34"},{"id":"3824","name":"Sousse","code":"51"},{"id":"3825","name":"Tataouine","code":"83"},{"id":"3826","name":"Tozeur","code":"72"},{"id":"3827","name":"Tunis","code":"11"},{"id":"3828","name":"Zaghouan","code":"22"}]}]
As you can see there are keys and values:
"id":"788",
"name":"Tunisia",
"name_es":"Túnez",
"iso2":"TN",
"prefix":"216"
And an optional array called zones with different keys and values:
"zones":[{"id":"3805","name":"Beja","code":"31"},
{"id":"3806","name":"Ben Arous","code":"13"},
...
I have two methods to pass different data to two PHP processing files:
countryData(data2[0].name, data2[0].prefix, data2[0].iso2), this function will write to the countries table via Ajax
zoneData(data2[0].zones, data2[0].iso2), this function will write to the zones table via Ajax
Both methods work simultaneously.
I´m having difficulties working with the data2[0].zones array in the PHP file (I don´t manage to check the structure and access the fields). The main problem I´m having is that I can´t var_dum() or echo() in the php file because if i do so it will not print because the data i need to check is coming from the ajax calls.
Is there something I must do to organize the data before sending it via Ajax which will make things easier in the backend side?
Or perhaps is there a way of printing the data in the server side to check what´s happening? Or perhaps a method that organizes the received data in way which is easy a methodically easy to work with?
Any ideas are more than welcome.
I live some samples of the code incase it helps:
function addZones(data){
$.getJSON("http:.." + data.codIso, function(data2){
var myJSON = JSON.stringify(data2);
console.log("DATA 2: " + myJSON);
countryData( data2[0].name, data2[0].prefix, data2[0].iso2 )
zonesData( data2[0].zones, data2[0].iso2 );
});
}
CORRECTION:
Before I send via Ajax has the following format using stringify:
Zones stringify: [{"id":"3924","name":"Abim","code":"UG-317"},{"id":"3925","name":"Adjumani","code":"UG-301"},{"id":"3926","name":"Amolatar","code":"UG-314"},
....
In the backend I have the following:
$zones = $_POST['zones'];
$zonesArray = json_decode($zones);
$jsondata["success"] = true;
$jsondata["data"] = array(
'message' => (string)$zonesArray[0]['name']
);
header('Content-type: application/json; charset=utf-8');
echo json_encode($jsondata, JSON_FORCE_OBJECT);
In the Ajax response I get the following error:
SyntaxError: Unexpected token < in JSON at position 0parsererror[object Object]
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.
I have a form which sent the entered values using ajax:
var form_data = {
board_id : $("#board-tabs").tabs('option', 'selected'),
name : $('#board_name').val(),
csrf_test_name : $("input[name=csrf_test_name]").val()
};
In that case form_data will be sent.
The server will return some JSON content.
Server side i'm using PHP and I'm wondering if there is some advantage sending form_data as a JSON object (considering that it must be decoded).
When you pass form data as a json object to jQuery ajax method it serializes into a string escaping all the required characters safe enough to transfer over http. It also depends on the type(GET/POST etc) you set in the ajax options.
The advantage is simplicity and simple to create json object instead of building a string of key/value pair.
I'm not sure about performance over other solutions, but decoding the json will result in an object or array without needing to create it yourself (organization).
Also, even though it's not in your example, replying to a javascript request with json provides for an easier parsing system. As jQuery already provides a way to decode json data.
It's a good medium supported by both languages.
$('myBtn').on("click",function(){
var parent= $(this).parent();// will give you the Parent Object of the button, that has been clicked
});
I need to send var parent to php so it knows where to display the html data (in the correct are div/class, how would i do this.
The short answer is that "You can't".
Communication between the browser (where your JS is running) and the server (where the PHP is running) is handled via HTTP. If you want to send a JavaScript object then you have to serialise it to a string and deserialise it at the other end. There is no sane way to represent an HTMLElementNode (or a jQuery object that wraps on) in that process (not least because PHP doesn't usually represent HTML in a DOM and when it does it won't be the same DOM instance as the browser is using).
Usually in this type of situation, you would request some data from PHP (possibly using one of jQuery's ajax methods) and then use JavaScript to turn it into DOM elements and insert it into the document.
Try JSON and Ajax (XMLHttpRequest) as the "client to server" mechanism
JavaScript is evaluated on client-side, when PHP is server side. You don't have trivial way to do it.
If the html data is not already generated, you would have to make a new request to the server, preferrably by the jQuery $.get function, then pass the output (again via jQuery) to the parent element.
Please use Jquery and use $.ajax for this purpose
$.ajax({
type: "POST",
url: "yourPHPPage.php",
data: "parentvar="+parent,
//parent is a javascript variable
success: function(msg){
//Message received from server,
// if you would write some code in echo there, like echo "hello";
// you would get that in msg.
}
});
to access this variable on php, use $_POST["parentvar"];
You can also send multiple values by concatinating them with & operator.
Like data:"parentVar="+parent+"&name=atif&age=23"; etc
Please let me know if further help needed.
Further help on
http://api.jquery.com/jQuery.ajax/
As far as I know, you can't pass a DOM object directly to the server -- there's too much information stored for it to be practical. You could send the HTML of the object though.
Here's an example that sends the HTML to the server. You would process it, but we just echo it back.
http://jsfiddle.net/hLD4F/
Try clicking on any of the buttons, and it will send a request. In PHP you could access this information via $_POST['html'].
I have an interactive web application powered by jQuery where users can manipulate visual objects on the screen. When done, the "state" of JavaScript objects should be sent to PHP to store into database. I'd prefer to use GET for this, but solution that uses POST to submit the data is also viable.
I'm currently thinking to serialize all JS objects using something like base64 encoding and just use something like:
var str = encode_objects();
document.location = 'result.php?result='+str;
However, something tells me there has to be some, more elegant, way than writing my own base64 encoding function in JavaScript. Isn't there something already built into JavaScript that can do the job?
Update: decoding in PHP is not the problem. I know how to decode base64, JSON, whatever in PHP. The problem is how to encode data on JavaScript side.
AJAX is out of the question. It has to be a clean GET or POST with page reload.
json_decode() should serve you well here.
If you simply append a string containing the JSON representation of your javascript object to your HTTP request, you can json_decode() it in PHP and have a PHP object ready to go.
Edit: I should mention that this page has a link to a Javascript JSON stringifier, which will convert your JS objects into the necessary JSON.
first of all, if you're updating the objects state, it should be a POST. try to keep all your GET idempotent.
second, even if you don't want to do any AJAX, JSON is still your friend. the easiest way would be to serialize your objects into JSON and send the resulting string in the POST dataload. there are many ways to decode JSON in PHP, and you're all set.
You can use this serialize function, and then unserialize it on the PHP end.
GET or POST will probably depend on the size of your data : there is a limit on the amout of data you can pass through GET (something like 2000 bytes ; more, depending on the browser).
There is also an other thing to take into account : if you are modifying data, you should use POST ; not GET, which is used to... get... data.
About the format, I would really not go for anything like a custom function doing any kind of stuff like base64 : I would definitly go for JSON, which is a native Javascript notation.
You can for instance have a look at :
wikipedia
http://www.json.org/
There are many JS libraries that can generate JSON (probably every JS Framework can ; and there are standlone libraries like this one) ; and since PHP 5.2 there are functions in PHP to encode/decode it (see json_encode and json_decode)
If it's just a simple flat array you don't need to do anything fancy, as PHP has a built in feature to parse array syntax from GET/POST variable names. Rough example below.
Javascript side:
// Do the parameter-building however you want, I picked the short/messy way
var arrayvalues = [1, 2, 'a'];
var querystring = "var[]=" + arrayvalues.join("&var[]=");
querystring += "&var[something]=abcdef";
// querystring is now "var[]=1&var[]=2&var[]=a&var[something]=abcdef"
PHP side:
var_dump($_POST);
// Remember to validate the data properly!
if ( is_array($_POST['var']) ) {
count($_POST['var']);
echo $_POST['var']['something'];
array_map('do_something_interesting', $_POST['var']);
}
I've used Jquery/JSON.
var jsonArray = $.toJSON(jsArray);
Then sent it via JQuery/Ajax