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));
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]
PHP
echo '<data><![CDATA[ [{"x":0,"y":0,"src":"images/image.jpg"}] ]]></data>';
JS
$.post( 'getData.php', {}, _onResult );
_onResult = function( result)
{
console.log(result);
}
The above console.log outputs:
( on localhost, using WAMP ):
<data><![CDATA[ [{"x":0,"y":0,"src":"images/image.jpg/"}] ]]></data>
( on web hosting, using LINUX ):
<data><![CDATA[ [{"/x/":0,/"y/":0,/"src/":/"images/image.jpg/"}] ]]></data>
How can I get the same output in the second case?
or
Can I somehow convert the second output to be able to parse it with $.parseJSON ?
No problem with your script..
var xml = "<data>\
<![CDATA[ [{\"x\":0,\"y\":0,\"src\":\"images/image.jpg\"}] ]]>\
</data>";
var dataXML = $.parseXML(xml);
var json = $(dataXML).find('data').text();
console.log(json); // outputs [{"x":0,"y":0,"src":"images/image.jpg"}]
No error in this line too
var json = JSON.parse(json);
The problem could be about the browser, or the HTTP server reading the XML data and not automatically parsing it to be a JSON object due to the security reasons. Whatever the reason, this line is (by assuming automatic conversion) fails:
var json = $(dataXML).find('data').text();
Instead, change it with this:
var json = $.parseJSON($(dataXML).find('data').text()); // i think you can use $.parse() too.
This problem have occured to me a few times in various occasions on both platforms before, and I don't think a stable thing. Howeever, since there is no way that the browser (or JS interpreter) can "detect" that it's actually a JSON object (inside that XML), you must explicitly define it to be so, if you want to establish type safety of your stuff (which is a good programming method).
PS: "localhost" is very flexible about security, so I'd recommend not to rely on it very much :)
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>"
)
Example:
javascript:
var mycourses=new Array();
mycourses[0]="History";
mycourses[1]="Math";
mycourses[1][0]="Introduction to math";
mycourses[1][1]="Math 2";
mycourses[1][2]="Math 3";
PHP will then run these values through functions (please note values are mostly not strings as in the example above but rather numbers), the functions will return some text which will than be displayed in a form
How should I go about doing this?
p.s.: I found some similar stuff, but nothing quite like this... as far as I see I will have to use JSON (is there a way to code it from JS automatically - saw this for strings) and AJAX
Yes, you may use JSON and PHP's json_encode() and json_decode() functions for that.
There are libraries in JavaScript... that will automatically convert your Array to JSON, and in php there are function to convert from JSON to a PHP Array... you process encode again in PHP and decode in JS...
JSON is an standard for JS.. try to use it since most languages already offer support for it, and it would make your life easier
Client-side, you need to send the data to the server and get back the result. This is a sample code with jquery, but you can do similar things with another lib or pure js:
$.post( "compute_courses.php", mycourses )
.done(function( data ) {
// Handle result
})
.fail(function( jqXHR, textStatus, errorThrown ) {
// Handle error here
});
This will send mycourses array to compute_courses.php, and handle the result.
Server-side, it depends which framework/lib you are using, but you will need to read the json, apply treatment, and return a result (most likely with json_encode). If you are planning to write that part yourself (with no third-party framework/lib), you can try something like :
$input = file_get_contents("php://input");
$mycourses = json_decode($input, true);
// Treatment...
$json_result = json_encode($mycourses);
exit($json_result);
If you are looking for a PHP framework that helps to do that kind of stuff, I suggest you to use Silex or Slim.
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