jQuery not recognizing Symfony JSON? - php
I'm trying to get my JSON data from Symfony but it doesn't seem to be working right. Below is the snippet of symfony code:
$this->getResponse()->setHttpHeader('Content-Type', 'application/json; charset=utf-8');
return $this->renderPartial('listJsonResponse',
array('jsonSlots' => json_encode($this->jsonQuery)));
The above works fine and hits the partial. All that is in my partial is this:
<?php echo $jsonSlots ?>
Now according to Firebug this gets populated properly. Below is a copy of the response
[{"id":"1","schedule_day":"Mon","start_time":"09:00:00","concurrent_appointments":"2","currentCount":"2"},{"id":"2","schedule_day":"Mon","start_time":"09:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"3","schedule_day":"Mon","start_time":"09:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"4","schedule_day":"Mon","start_time":"09:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"5","schedule_day":"Mon","start_time":"10:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"6","schedule_day":"Mon","start_time":"10:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"7","schedule_day":"Mon","start_time":"10:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"8","schedule_day":"Mon","start_time":"10:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"9","schedule_day":"Mon","start_time":"11:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"10","schedule_day":"Mon","start_time":"11:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"11","schedule_day":"Mon","start_time":"11:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"12","schedule_day":"Mon","start_time":"11:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"13","schedule_day":"Mon","start_time":"12:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"14","schedule_day":"Mon","start_time":"12:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"15","schedule_day":"Mon","start_time":"12:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"16","schedule_day":"Mon","start_time":"12:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"17","schedule_day":"Mon","start_time":"13:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"18","schedule_day":"Mon","start_time":"13:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"19","schedule_day":"Mon","start_time":"13:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"20","schedule_day":"Mon","start_time":"13:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"21","schedule_day":"Mon","start_time":"14:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"22","schedule_day":"Mon","start_time":"14:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"23","schedule_day":"Mon","start_time":"14:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"24","schedule_day":"Mon","start_time":"14:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"25","schedule_day":"Mon","start_time":"15:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"26","schedule_day":"Mon","start_time":"15:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"27","schedule_day":"Mon","start_time":"15:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"28","schedule_day":"Mon","start_time":"15:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"29","schedule_day":"Mon","start_time":"16:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"30","schedule_day":"Mon","start_time":"16:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"31","schedule_day":"Mon","start_time":"16:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"32","schedule_day":"Mon","start_time":"16:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"33","schedule_day":"Mon","start_time":"17:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"34","schedule_day":"Mon","start_time":"17:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"35","schedule_day":"Mon","start_time":"17:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"36","schedule_day":"Mon","start_time":"17:45:00","concurrent_appointments":"2","currentCount":"0"}]
Note if I take out the Content/Type header it changes slightly. I get the same response tab as above but also an html tab with the above parsed into html. Which shows like this:
[{"id":"1","schedule_day":"Mon","start_time":"09:00:00","concurrent_appointments":"2","currentCount":"2"},{"id":"2","schedule_day":"Mon","start_time":"09:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"3","schedule_day":"Mon","start_time":"09:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"4","schedule_day":"Mon","start_time":"09:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"5","schedule_day":"Mon","start_time":"10:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"6","schedule_day":"Mon","start_time":"10:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"7","schedule_day":"Mon","start_time":"10:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"8","schedule_day":"Mon","start_time":"10:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"9","schedule_day":"Mon","start_time":"11:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"10","schedule_day":"Mon","start_time":"11:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"11","schedule_day":"Mon","start_time":"11:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"12","schedule_day":"Mon","start_time":"11:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"13","schedule_day":"Mon","start_time":"12:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"14","schedule_day":"Mon","start_time":"12:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"15","schedule_day":"Mon","start_time":"12:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"16","schedule_day":"Mon","start_time":"12:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"17","schedule_day":"Mon","start_time":"13:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"18","schedule_day":"Mon","start_time":"13:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"19","schedule_day":"Mon","start_time":"13:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"20","schedule_day":"Mon","start_time":"13:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"21","schedule_day":"Mon","start_time":"14:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"22","schedule_day":"Mon","start_time":"14:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"23","schedule_day":"Mon","start_time":"14:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"24","schedule_day":"Mon","start_time":"14:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"25","schedule_day":"Mon","start_time":"15:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"26","schedule_day":"Mon","start_time":"15:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"27","schedule_day":"Mon","start_time":"15:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"28","schedule_day":"Mon","start_time":"15:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"29","schedule_day":"Mon","start_time":"16:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"30","schedule_day":"Mon","start_time":"16:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"31","schedule_day":"Mon","start_time":"16:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"32","schedule_day":"Mon","start_time":"16:45:00","concurrent_appointments":"2","currentCount":"0"},{"id":"33","schedule_day":"Mon","start_time":"17:00:00","concurrent_appointments":"2","currentCount":"0"},{"id":"34","schedule_day":"Mon","start_time":"17:15:00","concurrent_appointments":"2","currentCount":"0"},{"id":"35","schedule_day":"Mon","start_time":"17:30:00","concurrent_appointments":"2","currentCount":"0"},{"id":"36","schedule_day":"Mon","start_time":"17:45:00","concurrent_appointments":"2","currentCount":"0"}]
I know the JSON function is hitting, but it isn't parsing the success function and alerting me any sort of data. the JavasScript is shown below and is wrapped in a jquery ready tag
$.getJSON('/frontend_dev.php/module/listJSONSlots', function(data) {
alert(data);
});
Any ideas why I can't get to the alert?
You do not need to render a template, you can skip that and directly return something from your action. Try this:
return $this->renderText(json_encode($this->jsonQuery));
you need is to amend your partial
<?php $sf_data->getRaw('jsonSlots'); ?>
or use a simpler way from the actions
$this->getResponse()->setHttpHeader('Content-Type', 'application/json; charset=utf-8');
$this->renderText(json_encode($this->jsonQuery));
Try json_encode($input, true) to force it to encode as an object.
Technically JSON's top-level container must be an object (enclosed with {}) and not an array (enclosed with []).
The value of a property on a JSON object can be an array, but an array is not a JSON object.
I don't know about Synfony and its renderPartial method. But clearly it replaces special characters by their &...; equivalent. You should look for a way to disable this
Related
Getting data from json through jquery
I am trying to learn how to retrieve data from a json obj that I return from PHP but I can not figure out how to get the values. My data looks something like this: [{"user_name":"herp"},{"email":"herp.derp#gmail.com"},{"yy":"yyyy"},{"mm":"mm"},{"dd":"dd"}] My client-side script looks something like this: $.ajax({ type : 'POST', url : 'serverside/get_installningar.php', dataType : 'json', success : function(data) { } }); I would like to type something like data.user_name to retrieve the user_name and so on. But is there a method for doing this? I have looked in the forum but can't find the right thing.
What you have is an array of objects and so you going to need to know where it is to get user_name, data[0].user_name see below for structural details, [ {"user_name":"herp"}, // <-- data[0] {"email":"herp.derp#gmail.com"}, // <-- data[1] {"yy":"yyyy"}, // <-- data[2] {"mm":"mm"}, // <-- data[3] {"dd":"dd"} // <-- data[4] ] As AndrewR pointed out, This will work, but it would be better to fix the JSON format coming from PHP. {"user_name":"herp","email":"herp.derp#gmail.com","yy":"yyyy","mm":"mm","dd":"dd"} and then his original plan will work.
as of jquery 1.4.1 you can do this natively jQuery.parseJSON Do that on the data.responseJSON to convert to JS object. See How do I convert a JSON string to a JavaScript object in jQuery?
Use data.parseJSON();. It returns an object exactly the way you want it.
You are actually returning an array not a json object Your data needs to look like this: {{"user_name":"herp"},{"email":"herp.derp#gmail.com"},{"yy":"yyyy"},{"mm":"mm"},{"dd":"dd"}} Try installing Firebug to debug the return value of your page if its a properly formatted JSON.
use it like: console.log(data[0].user_name); For a easy acces members of your json, try virtualising it in a nice format so you can understand where you have array and where you have object. [] means array {} means object I recommand a chrome extension: JsonView and for example, take a JSON request like this. Just open it in a tab and it will be nicely formated. Also it shows you in the bottom left corner how to access what you are hovering over.
Ajax post success data: Can you separate results?
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.
decode json as html
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>" )
Sending PHP json_encode array to jQuery
ok, i guess I need help ! I searched with every keyword I could think off, but I still cant figure out, please help. Am more of a php guy, and I've just started with jQuery. Basically, what I am trying to do is to send a jQuery post from a click function. And based on whatever is returned by my php function, show/hide 2 divs. My php function returns a "json_encode" array with 2 simple values, like such : //==================PHP code ================================== $message_for_user = "blah blah"; $calculatedValue = 1230; $responseVar = array( 'message'=>$message_for_user, 'calculatedValue'=>$calculatedValue ); echo (json_encode($responseVar)); //==================PHP code End ================================== My javascript code is supposed to accept the values returned by php : //==================Javascript code ================================== $("div.calculator_result").click(function() { $.post('myCalculator.php' ,{qid:itemID},function(response) { $("div.calculation_value").show(500).html(response['calculatedValue']); $("div#message_for_user").show(500).html(response['message']); } } //==================Javascript code End ================================== Unfortunately, on the javascript side of my project, the divs are not updated with the values returned by my php functions .... where am I wrong? I hope I was clear in my question, if not, do let me know, and I shall provide any extra info required. Another thing is that earlier, I was echo'ing only a single value, that is the calculated value (echo $calculatedValue), and everything worked fine, its only after I shifted to echo'in the json encode array that things dont work
var json = $.parseJSON(response); alert(json.message);
Try setting the dataType option: $.post('myCalculator.php' ,{qid:itemID},function(response) { $("div.calculation_value").show(500).html(response['calculatedValue']); $("div#message_for_user").show(500).html(response['message']); }, 'json'); NB I have also added the closing brackets ) where you have missed them.
You must parse the JSON response. jQuery has this built-in functionality (thankfully, because otherwise IE6 and 7 don't natively support JSON). Set a variable equal to this: $.parseJSON(response) And then, if you're not familiar with JSON format, check the response headers (using Firebug or similar,) and that will help you pick which keys' values you want. If you're looping, I would look into for in statements once the response has been parsed. EDIT: Using $.getJSON, the parsing is done automatically. Write less, do more. :)
All you gotta do, its tell the Ajax call that you're receiving data type "json". In other words... $.ajax({ url: "external_file", method:"post", dataType: "json", // **************** Note dataType**************** success:function(response){ console.log(response) // Response will be a javascript array, instead of a string. }, error: function(){ alert('something went wrong.') } })
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.