Problems with $.getJSON in certain browsers - php

I have a php file that outputs json encoded text via
echo '(' . json_encode( $final ) . ')';
And i have a javascript file that fetches that page
$.getJSON(file, function(data){
var object = eval(data);
alert(object); //for testing
...
When any browser other than firefox 3.5 visits the page that calls .getJSON it alerts null
BUT!!! If i take the text that is output by the php file paste it into a new file and load that via .getJSON it works fine. It's only when its output by php that it doesn't work.
The only difference i can see is that the PHP file's content length is 2 more than the other, i can't figure out why.
Thanks
UPDATE
I created a small array to test it with other data and it's working. There's something in my data that's causing the issue. Looking now...
a call to array_merge is the culprit.

data is not a string, it is a JSON object. Therefore eval will not work on it. Try the following instead:
$.getJSON(file, function(data){
alert(data); //for testing

I've narrowed it down to a call to array_merge that is corrupting the data somehow.

Related

server not parsing php file called from jquery ajax

Im using a basic jquery ajax call.
I make a call to a php file without input parameters with option datatype set to json.
I want the server to parse the php which queries a table in a mysql db, convert it to array and finally encode it to json and return.
I tried a test call from the browser by copying the php file url in the address field, and it shows that it works, since I can see a blank page with all the rows of the table in json formatting.
Instead, when calling from my javascript code the $.ajax call fails with error
Requested JSON parse failed
which means ajax call was expecting json (since I set option datatype to that) but received another format.
So I tried removing the datatype option from the call, and lo and behold I got a response success, but what did I received from my php file?
Well, it was the whole code in the file, like the server doesn't parse it cause it thinks it's plain text.
Is there a way out of this problem? Thanks.
Send also content header with json data
<?php
header('Content-Type: application/json');
echo json_encode($data);
The ajax function is expecting a JSON encoded document so you have to send a header with the response saying that the response contains JSON. Something like this:
<?php
header('Content-Type: application/json');
// All your code here
echo json_encode($someArray);
?>
I'm an idiot, I may answer my own question, I was debugging jquery from visual studio, which automatically instatiates an iis web server, and it explains why it was treating php files like text files. Obviously under apache everything works fine.
Sorry for taking your time....

How to pass Javascript object to php to make sql query and return data as a downloaded csv file?

I use jquery to set a get query to a php script which then queries the database and writes to the screen, but I can't get it to trigger the download, even with headers.
The steps are as follows:
create a link that the user clicks to download the data
javascript sends the query parameters to php
php queries the database and writes the file
client downloads the file
But I can't get step 4 to happen.
Step 1: (this is a table object that also contains the parameters:
d3.select("#some-div").append('a")
.attr("href", "javascript: void(0)")
.on("click", function() { this.saveAsCSV() };
Step 2: Javascript file to make query:
var saveAsCSV = function(params) {
var tmp_params = $.extend({}, params);
tmp_params['State'] = "NM";
$.get('php/get_data.php', tmp_params);
}
php to return query:
...
header("Content-type: application/text-csv");
header("Content-Disposition: attachment; filename=query_result.csv");
while($row = $result->fetchArray() {
print "$row";
}
...
It works fine in that it correctly queries and will print the data in the javascript function (so it will print it to console.log if I add that into the get return function), but I can't figure out what I should do differently to make it just download it directly.
One thing I've tried is to do the following on the params object:
var param_string = encodeURIComponent(JSON.stringify(params));
location.href = 'http://www.mysite.com"+param_string;
But that both takes the user away from the page and fails to download the data.
EDIT: I should clarify that the php file does output the query well in csv format. The problem seems to be that using the $.get() function does not trigger a download regardless of the php headers. Maybe I need to just provide a simple link with the parameters in the URL address, but I'm not sure how to get a javascript object into a URL format so that the php script can interpret it.
You could open a popup/new window/tab/whatever with your URL php/get_data.php?State=NM (perhaps additional parameters). It should download the output.
But your output might be wrong because you just print the variable $row which is an array. If you try to print an array that way it will just show Array.
You will need to properly output your rows. Unfortunately I don't know the CSV structure well enough to help you with that problem.
You can make an AJAX call for this using something like jQuery and it will pop up the download box while keeping the user on the page. Do something like this:
$.ajax({data: {download: 'query_result.csv'}, type: 'GET', url: 'download.php', cache: false });
I've tried this a few times for a previous employer and it always worked great. Although I did it mostly with .zip and .docx files.
I figured it out!
Basically, my encoding was wrong. I don't want to encode with
encodeURIComponent(JSON.stringify(params));
The result isn't readable by the php script. However, it works to just use $.param().
To summarize, the download is triggered by creating the URL link and then using location.href to link to it. Hence everything else is the same, but instead of the $.get() in step 2, I do:
var url_params = $.param(tmp_params);
location.href = url_params;
Which generates the download. Thanks!

JSON Response keeps coming back undefined (ajax file upload)

I'm currently using Valum's Ajax File uploader to do same-page file uploads. For my script, I need to pass the final file path (after it gets uploaded) back to the client-side and store it in a variable, however, I keep getting "undefined" for responseJSON['filename']. I've tried tons of different solutions and nothing seems to work (changed datatype from json to text, played around with the way PHP sent the response, etc. etc.)
There must be something simple I'm overlooking here....
All help is welcome. Thanks!
EDIT: JS is here: http://jsfiddle.net/acw9V/ for the PHP portion, I'm using the default PHP code in Valum's zip archive.
Update: still no luck... keep getting back undefined from responseJSON. I'm wondering if there's some way to just return whatever message is echo'd in PHP, maybe I could work with that?
I think that 'responseJSON' in fact is STRING , not an array. (assuming that you just echo-ing your output in php and you cannot echo array) To be treated as array, after receiving, responseJSON should be eval-ed.
var data = eval(responseJSON);
(eventually: var data = eval ("(" + responseJSON + ")"); )
then data['filename'] should contain uploaded file name (if this was specified in php)

How to correctly return json to IE8 from ajax php script

I am using this ajax file upload script, and all works well in firefox http://valums.com/ajax-upload/
But it does not work in IE8.
EDIT: Ok, i've narrowed down the problem. In my php ajax response I do this
$result['table_1']='<b>text</b>';
echo json_encode($result);
The result I see in the IE developer tools looks like this
JOURNAL : [uploader] innerHTML = {"table_1":"<B>text<\/b>"}</B>
The end of the inner html got messed up, and the json got messed up with the correct ending tag somehow ending up outside the json??
I am using php 5.2
You should try validating your JSON response with JSONLint. On the other hand, if you've got PHP >= 5.3.0, you can use json_last_error() to verify what's causing PHP to fail on the encoding process.
I had a similar problem Invalid JSON: {"text":"<H2>Update Complete<\/H2>"}</H2> with ie and solved it by using
http://www.captain.at/howto-php-urlencode-javascript-decodeURIComponent.php
(that site is no longer programming I found a similar function here What is the equivalent of JavaScript's encodeURIcomponent in PHP?) on the PHP side
$response->text .= encodeURIComponent("<H2 class='action_result'>Update Complete.</H2>");
return json_encode($response);
and in the js I used
function showResponse(responseText, statusText, xhr, $form) {
var response = jQuery.parseJSON (responseText);
$('#ajax_form_response')[0].innerHTML = decodeURIComponent(response.text);
}
Ok, I found a olution that works. This library works through an iframe, so to return text like
$result='<b id="1">text</b>';
I have to manually encode and decode the " myself because they get messed up in the iframe.
So the final php looks like this
$result['table_1']=htmlentities(str_replace('"','|',getRowHTML()));
echo json_encode($result);
And then to manually decode in the javascript looks like this
function(id, fileName, responseJSON)
{
$('#table_1 tbody').html
(
//this line decodes responseJSON.table_1
$("<div/>").html(responseJSON.table_1.replace(/\|/g,'"')).text()
);
}

jQuery getJSON to external PHP page

I've been trying to make an AJAX request to an external server.
I've learned so far that I need to use getJSON to do this because of security reasons ?
Now, I can't seem to make a simple call to an external page.
I've tried to simplify it down as much as I can but it's still not working.
I have 2 files, test.html & test.php
my test.html makes a call like this, to localhost for testing :
$.getJSON("http://localhost/OutVoice/services/test.php", function(json){
alert("JSON Data: " + json);
});
and I want my test.php to return a simple 'test' :
$results = "test";
echo json_encode($results);
I'm probably making some incredible rookie mistake but I can't seem to figure it out.
Also, if this works, how can I send data to my test.php page, like you would do like test.php?id=15 ?
The test.html page is calling the test.php page on localhost, same directory
I don't get any errors, just no alert ..
It could be that you haven't got a callback in test.php. Also, json_encode only accepts an array:
$results = array("key" => "value");
echo $_GET['callback'] . '(' . json_encode($results) . ')';
// the callback stuff is only needed if you're requesting from different domains
jQuery automatically switches to JSONP (i.e. using script tags instead of XMLHttpRequest) when you use http://. If you have test.html and test.php on the same domain, try using relative paths (and no callbacks).
Be careful with moff's answer. It's got a common XSS vulnerability: http://www.metaltoad.com/blog/using-jsonp-safely
The simplest solution would be to add the below code before any output to your test.php file, then you have more flexibility with what methods you use, a standard ajax call should work.
header ('Access-Control-Allow-Origin: *');
However, use the json callback thing when your getting data from a server beyond your control.

Categories