Strange issue with Json & PHP - javascript

There is any reason why a json string fail to be evaluated (transport.responseText.evalJSON();) on the server but works on my local installation ?
I'm doing a simple ajax request like this one:
new Ajax.Request(
this.saveUrl, {
method: 'post',
parameters: Form.serialize(this.form),
onLoading: function () {
totals.update('<div class="loading-ajax"> </div>');
},
onSuccess: function (transport) {
if (transport.status == 200) {
var data = transport.responseText.evalJSON();
totals.update(data.shipping_method);
}
},
onFailure: checkout.ajaxFailure.bind(checkout)
}
);
On server side I output an array containing some html:
$data = array(
'shipping_method' => $shipping_method,
'payment_method' => $payment_method
);
echo json_encode($data);
I have tried to valorize $total and '$other' as empty string '' but I get the same result:
transport.responseText.evalJSON(); return an "unexpected token"
As said above the weird thing is that on my local it works ( the output is the same as the server but js doesn't trigger any error )
I'm struggling with this almost all day ... any help is really appreciate thanks
UPDATE:
console.log(transport.responseText)
-> {"shipping_method":"","payment_method":""}
Inspecting the server response 'network tab' in chrome I can see a small difference, in comparison to my local: there is a small red dot before the response content if ( is say \ufeff if I move the mouse over it, I'm not sure about the meaning ... )

After some test I found out that the issue is encoding used in some PHP files, my co-worked had the brilliant idea to switch to ANSI. (ISO-8859)
For some reason these files coded with ANSI produced JSON content to be different:
chrome inspector was showing a red dot -> Byte_order_mark \ufeff character (aka BOM)
This probably means the BOM character is missing and this was breaking the json parse.
SOLUTION:
After I parsed and cleaned all my project files from the BOM character, chrome doesn't show the red dot in the inspector and the issue is gone
Still it is not clear why on my local installation the issue was not present while on the server it was ( both linux ) but there are probably multiple settings involved here ...
To clean your files see: Elegant way to search for UTF-8 files with BOM?

you can use map function to evaluate json value
$.map(transport, function (item){
totals.update(item.total);;
});
I think its Working fine

Related

Codeigniter 4 enviroment make JSON.parse fail

I'm new in codeigniter 4
I just started a new project in Codeigniter 4, and i got an error using JSON.parse,
Unexpected token < in JSON at position 30
I get two different results from using different enviroments:
Default// did not make any change to codeigniter config
-The code run totaly fine, though for a second i manage to see a bug in console
-The bad thing, in this enviroment most of debugging tools are deactivated something that i would like to have while working.
SetEnv CI_ENVIRONMENT production // which makes the debugging tools from CI4 appear, this line is in .htacess
-The code stops at JSON.parse and get the error described before in console
So here it is how my code is estructured:
//controller
echo json_encode(array('status' => 0,'message'=>'Access denied'));
//response rgets data from callback from a controller
console.log(response);//{status:0,message:'Access denied'}
data=JSON.parse(response); //error
//Other fixes i already tried
data=JSON.parse(JSON.stringify(response)); //Works fine, but returns a string, need an object
data=JSON.parse(JSON.parse(JSON.stringify(response))); //error
data=JSON.parse("{status:0,message:'Access denied'} "); //Even trying to use directly a JSON format throws error
data=JSON.parse({status:0,message:'Access denied'}) //error, without the comas
data=JSON.parse([{status:0,message:'Access denied'}]) //error
The debbuging tools seem to stop the loading when they find a bug, but i have not managed to find what i am doing wrong. Hope you can help me with this and thanks in advance.
EDIT
I´m using webix libraries for request, but they return string format.
I tried manually what you suggested,but the result was the same. It works if use CI4 in production env, but fails at development mode.
//Solutions tried
response = JSON.parse({"status":0,"message":"Access denied"});//error
response = JSON.parse("{'status':0,'message':'Access denied'}");//error
echo json_encode(array('status' => 0,'message'=>'Access denied'));
//the response should be like this
{"status":0,"message":"Access denied"}
and then use like this
data=JSON.parse(response);
and kindly check your datatype during the post and it should be a json

PHP $_GET and underlines

I have a very short piece of PHP that I use to make HTTP requests from JavaScript.
<?php echo file_get_contents($_GET['url']); ?>
I have used it successfully in a few projects, but am running into a problem with making requests in my current project. Based on my searching, I believe it may be caused by the underscore in the request, though through my searching and not knowing PHP, I have not been able to confirm that.
Below is an example of what I am doing from JavaScript:
$.get("grabber.php?url=" + "http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW", function(forecast) {
console.log(forecast);
});
If I copy the url and put in it in a browser, I get back the JSON that I requested. When I use the code above, I end up getting an error message from NOAA:
Wrong Product : Product cannot be null or empty Wrong Time zone: Time zone cannot be null or empty Wrong Unit:Unit cannot be null or empty Wrong Format: Format cannot be null or empty Wrong Date: The beginDate cannot be null or empty
Do I need to use a regex for the underscore in PHP? Is there some other issue that I do not understand?
Thanks.
You need to send it encoded, which will convert all the underscores/spaces/ampersands etc. with their encoded equivalents:
var url = "http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW";
$.get("grabber.php?url=" + encodeURIComponent(url), function(forecast){
console.log(forecast);
}
Using encodeURIComponent() on that URL shows:
http%3A%2F%2Ftidesandcurrents.noaa.gov%2Fapi%2Fdatagetter%3Fstation%3D8573364%26begin_date%3D20160202%26end_date%3D20160203%26product%3Dpredictions%26units%3Denglish%26time_zone%3Dgmt%26format%3Djson%26application%3Dposeidonweathercom%2B%26datum%3DMLLW
Alternatively, if you just want to access the JSON data and handle it within the JavaScript function, you can retrieve the data via the URL directly, without having to encode the URL:
$.get("http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW", function(forecast) {
console.log(forecast);
});
Um why do you even need your php code ... the code below will work just fine and eliminate your server overhead.
$.get("http://tidesandcurrents.noaa.gov/api/datagetter?station=8573364&begin_date=20160202&end_date=20160203&product=predictions&units=english&time_zone=gmt&format=json&application=poseidonweathercom+&datum=MLLW", function(forecast) {
console.log(forecast);
});

Posting long text from scripted browser (phantomjs) to a php script wont go over 2kb /2400 char

im doing some data scraping using phantomjs (basically its a browser you can code in and run it from command line)
i'm collection information about football matches (teams / countries / leagues , .... ) each as an object , put them all in an array , encode array to jason format and post the result to a php script
result could be a very long text based on amount of games on each day and when that happens i wont get the full text on the php script
in the php script i've stored the posted data in a text file to see whats going on , each time its about 2.3kb max and 2397~ characters
while the original posted text which i can see on the terminal is about 40kb and 40000 chars
so something must be limiting the characters here is my php.ini info which is more than enough :
post_max_size -> 20M
max_input_vars -> 100000
memory_limit -> 256M
here the simplified version of my code :
var res = page.evaluate(function(sport) {
var matches = new Array();
$('div#table-matches').find('.table-main').find('tr').each(function(index, element) {
var obj = {
teams : $(this).find('td').text() ,
link : $(this).find('td').find('a:last').attr('href') ,
};
matches.push( obj );
});
return matches ;
});
var postBody = 'sport='+sport+'&data='+JSON.stringify(res);
console.log(postBody);
page.open('http://xxxxx/result/save', 'POST', postBody, function(status) {
phantom.exit();
});
here is what i got in the php script :
[{"country":"Japan","league":"Emperors Cup","link":"/soccer/japan/emperors-cup/kobe-urawa-65k5LIMh/","match_date":"2015/12/26 04:00","teams":"Kobe - Urawa"},
{"country":"England","league":"Ryman League","link":"/soccer/england/ryman-league/wingate-finchley-metropolitan-police-rwuqgSz9/","match_date":"2015/12/26 12:00","teams":"Wingate
the json code has been cut off in the middle , so its not a valid json
is there anything else i should do ?
Usually it's much simpler to look for the answer when HTML that your code operates on is provided in the question (a link to the site is as good).
Luckily you'fe left some clues in a portion of json file, namely the link to one of the pages from the scraped site: /soccer/england/ryman-league/wingate-finchley-metropolitan-police-rwuqgSz9/
If we find it with Google and look at the source it will be clear that data in php script is truncated right at the title of the team «Wingate & Finchley - Metropolitan», that contains an ampersand, which serves as a delimiter for variables and values sent via an URI request and breaks your data variable into several others.
So, to amend your script you just have to encode the data string properly:
var postBody = 'sport='+sport+'&data='+encodeURIComponent(JSON.stringify(res));
Other way to find the cause of this issue would be to check $_SERVER and $_POST arrays at the server side, just dumping it to a file and looking if the whole data was really present, since you've already done great job checking PHP config that it should be present.
A way to go around the issue, had it not been solved (if, for example, PhantomJS had a weird bug with POST equests), would be to create a temporary file with data and send to php the path to that file (presuming the parsing is done on one and the same server):
var fs = require('fs');
var filename = '/tmp/scraped_' + (new Date()).getTime() + ".json";
fs.write(filename, JSON.stringify(res), 'w');
page.open('http://xxxxx/result/save', {"filename" : filename}, function(status) {
phantom.exit();
});

Issue With JSON Data

I'm having a weird issue with some JSON data.
{
"title" : "Counties",
"data": [
{
"Name": "Baker",
"latlng": [
"44.65488,-118.42475",
"44.64548,-118.38275",
"44.62488,-118.34425",
"0,0",
"1,0"
]
}
]
}
When I use .getJSON for the file with this data I am getting an syntax error but if I take out the last two entries from the latlng array it will work correctly.
I put the JSON though the linter at jsonlint.com and it says it's valid JSON but chrome and firefox can't parse it for some reason.
The code that is getting the json file:
$(function() {
$.getJSON("json/counties.json", function(data){
console.log(data);
});
$(document).ajaxError(function(event, jqxhr, settings, exception){
console.log(exception);
});
});
The exception that is logged from Chrome
SyntaxError {}
And the exception that is logged from Firefox
[15:07:33.965] (new SyntaxError("JSON.parse: unexpected non-whitespace character after JSON data", "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js", 3))
As far as I can tell there aren't any characters after the JSON in the data, here's a screen shot
Your code is all working fine for me, and the data you're showing is fine, so there must just be something weird going on in your environment.
First thing I'd suggest is to watch your raw HTTP response in Fiddler or your browser's network tab, and see if there's anything unexpected there - maybe you've got a proxy server appending garbage to your data or something like that.
If not, then try opening up your counties.json file in a binary editor and look for any unexpected byte in there, maybe something invisible or a funky quotation mark or something. This is all ASCII here in your example, so it should be pretty easy to spot any character that doesn't belong.

Json object in jquery can't be read?

I am trying to read the finance info from the google page into a json object.
Code is below:
try {
$.getJSON("http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&jsoncallback=?",function(data){
alert(data);//var jsondata = data;
//jsonobj = $.parseJSON(jsondata);
//alert(jsonobj[0].id);
});
} catch(e) {
alert(e.toString());
}
However I keep getting this error all the time on firebug
invalid label
"id": "4052464"
Is there any way this info can be read. My ultimate goal is to create a windows 7 gadget that doesnt use server side scripting and can be used from any Windows 7 system.
Appreciate all the help.
John
Response isn't valid JSON (response is prefixed with //), so jQuery won't be able to parse it correctly anyway.
To solve change &jsoncallback=? to &callback=?
so
$.getJSON("http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&callback=?", function(data) {
alert(data)
});
The response from Google has two leading /'s, making the response invalid JSON... for some reason.
Because of this, you cannot use jQuery.getJSON, as it expects a JSON response. Instead, you should use jQuery.get, and parse the JSON yourself after removing the two leading slashes.
jQuery.get('http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&jsoncallback=?', function (string) {
var validJson = string.slice(2);
var obj = jQuery.parseJSON(validJSON);
// use obj
});
Two additional points:
No JSONP is being used, so you don't need the jsoncallback=? in your request URL
The Windows Sidebar has been retired, so you cannot publish you finished gadget to the official gallery.

Categories

Resources