Processing Json Data in PHP - php

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]

Related

Sending back a PHP object to an ajax call

I'm learning PHP OOP, and getting used to all of these objects. I can't find the answer of a little question (maybe it's obvious, but I m new to objects...) :
When I create an object in a PHP file called via an $.ajax function, I want to deliver the answer back.
But how am I supposed to send back the object to my ajax call ? Before OOP, I was putting everything into an array, then json_encode() the array, and everything worked perfectly. How to adapt this using OOP ?
Thanks a lot for your answers
Romain
Example :
On the client side
$.ajax(
{
url:"test.php",
type:"POST",
dataType:"json",
success(function(json))
{
// json into template
}
});
On the server side : test.php
require_once("bdd.php");
function loadClass($class)
{
require $class.".class.php";
}
spl_autoload_register('loadClass');
$PersonneM = new PersonneManager($db);
$perso = $PersonneM->get("123456");
$perso = serialize($perso); // ????????????
header('Content-type: application/json');
echo json_encode(array("result",$perso));
#lahud: Generally we use XML and JSON formats to send data from server side to client side. PHP Objects are used only at its server end (at php level). You can result to client in a standard data format like xml and json.
If you want to store php object, you can use serialize function to store object as string. Hope its clear to you.
#Pankaj
Yes of course I often send JSON results to my client and write it down with a template like Mustache. But what is the correct way to convert the $object into JSON ?
Maybe :
$array = (array)$object;
header('Content-type: application/json');
echo json_encode(array("response" => $array));

easy jQuery - php communication

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'];

parse ajax response text

I want to update the web page based on ajax response received from a php script.
code inside php page :
// based on the logic either of the following three will be returned using ajax repsonse.
echo "<div align='center>Yahoo</div>";
echo "<div align='center>Rediff</div>";
echo "<div align='center>Google</div>";
The page which calls the ajax and receive the repsonse needs to perform some actions based on the returned response text.
Like , when the reponse includes "Yahoo" i need to execute some javascript functions....
when the reponse includes "Rediff" i need to perform some other javascript functions....
Currently i am using the javascript .indexOf function to search for "Yahoo" or "Rediff" in the ajax response and based on the return status of .indexOf() i am calling the functions i wish to execute.....
I feel i am not doing it in the right way ..... so thats why this question !!!
Can JSON be used in this case ??? [ just a tech thought :-) ]
i use json quite a lot for ajax apps, you could simply have a response such as
{
"response":"rediff",
}
then eval that, and get the .response value. works perfectly for me
the response from the php script would be the same as above, then (the way i interpret json) use
var resp = eval("("+req.responseText+")");
resp = resp.response;
resp will now return "rediff"

how to send json to php file to save on server

Im developing a javascript/php/ajax application and have stumbled across some problems.
Im confident at javascript and ajax but my php is a little rusty.
My aim is to get a json file from the server, modify it using javascript, and then save this modified json back to the server.
After some research it was obvious that the modified json file must be sent to a php file, this php file will then do the saving.
HOW do i send a json string from javascript to php? OR how do I get the php file to pick up the json variable from the javascript?
im assuming the php will be something like:
<?php
$json = $_POST["something"];
?>
but how do i send or "post" the javascript variable to the php file?
I was thinking about creating a hidden html form, setting a hidden textbox to the json string, then posting the html form
But surely there must be a way without including the html middle man?
Im looking for answer WITHOUT jQuery. Seeing as this is an application i would like a relieve the dependancy of jQuery.
The only, as far as I know, proper way to do this is sending data to a file through Ajax, then attaching some POST or GET data.
Example:
You could send the data in the url as GET:
http://example.com/foo.php?myvalue=cake
And then in the php you'd say:
<?php
$yourvalue = $_GET['myvalue'];
// Some code to save it to the database/server
?>
You would need to create a XMLHttp-Request like this:
xmlhttp.open( "POST", url, false );
xmlhttp.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded; charset=UTF-8'
);
xmlhttp.send("data=yaystuff!")
So you can send it. In PHP just get the $_POST['data'] variable and do some json_decode() on it, if you send JSON :)

JSON response from PHP script being enclosed in <head></head><body> ... <body>

I am trying to debug a simple PHP/JSON/jQuery problem.
The following PHP script:
header('Content-type: text/javascript');
echo json_encode(array('type'=>'error','message'=>'arg'));
is being consumed by jQuery but when the line:
var results = jQuery.parseJSON(responseText);
is executed, the jQuery JSON parser gives the following:
uncaught exception: Invalid JSON: <head></head><body><pre>{"type":"error","message":"oops!"}</pre></body>
Obviously the head/body/pre are not supposed to be returned.
I cannot see any hidden characters nor anything out of order in my PHP code..
Any ideas?
This one has had me stumped for the last two days. I'm using the jQuery Form plugin's ajaxSubmit function to submit a form via AJAX without reloading the page. I finally stumbled across the answer after this question showed me a parameter I hadn't noticed previously: dataType.
Behind the scenes, an iframe is being created and is actually making the call back to the server. The response from the server is being pulled from the iframe, which is bringing along with it the tags.
The jQuery Form plugin handles the situation by allowing you to specify the type of response to expect from the server. If I specify 'json' as the response type, the following few lines of code are executed to get the JSON from within the tags:
// account for browsers injecting pre around json response
var pre = doc.getElementsByTagName('pre')[0];
if (pre) {
xhr.responseText = pre.innerHTML;
}
(doc is a reference to the iframe's document and xhr is the XmlHttpResponse object that ultimately gets returned from the plugin's function.)
I don't know exactly how you're making your AJAX call, but I'm guessing a similar construct (perhaps using a document fragment) will allow you to extract the necessary JSON from the response.
Try not to send header('Content-type: text/javascript');
json for php find "function send_as_json($obj)"
headers types
Set the header to application/json.

Categories