i'm trying to develop Firefox extension
problem :
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = response.json;
}
});
I want to use this request function to parse json to an array (List here) from php file.
The php my php file echo json form correctly, but I can't transform the data into javascript array to be able to use it in my addon.
if there is a better idea than using this function to do it please tell me :)
try this: MDN - JSON Object
JSON.parse and JSON.stringify
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = JSON.parse(response.json);
}
});
it's very important to use double quotes.
If you are having a problem with JSON.parse. Copy your array to scratchpad and then run JSON.stringify on it and then make sure your php file matches the strignified result.
if Addon-SDK doesnt have JSON then you gotta require the module if there is one. If there isn't one than require('chrome') and grab the component HERE
There's a bug in Noitidarts code.
why JSON.parse the request.json? If you want to parse do it on request.text
However no need to json.parse as the request module tries to parse and if successful retuns request.json
see here:
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=mozhacks&count=1",
onComplete: function (response) {
var tweet = response.json[0];
console.log("User: " + tweet.user.screen_name);
console.log("Tweet: " + tweet.text);
}
});
// Be a good consumer and check for rate limiting before doing more.
Request({
url: "http://api.twitter.com/1/account/rate_limit_status.json",
onComplete: function (response) {
if (response.json.remaining_hits) {
latestTweetRequest.get();
} else {
console.log("You have been rate limited!");
}
}
}).get();
so the likely problem is that your php is not outputting a json string that json.parse can read. make sure to use ". figure out what your php file should return by running json.stringify on a dummy object. ie:
var obj = {myarr:[1,8,9,7,89,0,'ji'],strr:'khhkjh',anothrtObj:{1:45,56:8}};
alert(JSON.stringify(obj)) //{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
so now in your php make sure your outputted text mateches this format
{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
if your php outputs something like below JSON.parse will fail on it so request.json will be null
{myarr:[1,8,9,7,89,0,"ji"],strr:"khhkjh",anothrtObj:{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,"ji"],'strr':"khhkjh",'anothrtObj':{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,'ji'],'strr':'khhkjh','anothrtObj':{'1':45,'56':8}}
Related
Trying to parse a json response from URL in javascript.
Here is what the response looks like
{"data":[{"version":"7.4.0","startDate":"2016-12- 12","totalSessions":"6208723","totalCrashes":"2944","crashRate":"0.047"},{"version":"7.4.0","startDate":"2016-12-11","totalSessions":"4979676","totalCrashes":"2378","crashRate":"0.048"},{"version":"7.4.0","startDate":"2016-12-10","totalSessions":"534913","totalCrashes":"208","crashRate":"0.039"},{"version":"7.4.0","startDate":"2016-12-09","totalSessions":"309564","totalCrashes":"147","crashRate":"0.047"},{"version":"7.4.0","startDate":"2016-12-08","totalSessions":"255597","totalCrashes":"162","crashRate":"0.063"},{"version":"7.4.0","startDate":"2016-12-07","totalSessions":"21379","totalCrashes":"12","crashRate":"0.056"}]}
I can dump the json output using
var crash = $.post('http://localhost/crash_stats.php', function(data2) {
$('#show-list').html(data2); //shows json
});
Then I tried to parse it using
document.getElementById("placeholder").innerHTML=data2.data[0].version
also tried
obj = JSON.parse(crash);
console.log(obj.data2[0].version);
But no luck.
You should tell jQuery that the AJAX function returns JSON, then it will parse it automatically for you.
var crash = $.post('http://localhost/crash_stats.php', function(data2) {
$("#placeholder").text(data2.data[0].version);
}, 'json');
Or you can call JSON.parse() yourself.
var crash = $.post('http://localhost/crash_stats.php', function(data2) {
var data = JSON.parse(data2);
$("#placeholder").text(data.data[0].version);
});
So i´m, trying send data from php to js.
PHP
$balkTypes[] = $stmt->fetchAll();
echo json_encode($balkTypes);
JS
balkTypesData = {}; //Outside Ajaxcall
success: function(result){
balkTypesData = result;
Console.log(balkTypesData);
}
Console
[[{"id":"3","typ":"Bas 200*600","hojd":"200","bredd":"600","rec":"","viktM":"135"},{"id":"2","typ":"Bas 240*600","hojd":"240","bredd":"600","rec":"","viktM":"160"},{"id":"5","typ":"Isol\u00e4tt 240*600","hojd":"240","bredd":"600","rec":"","viktM":"105"},{"id":"4","typ":"Kontur 240*600","hojd":"240","bredd":"600","rec":"","viktM":"105"},{"id":"6","typ":"Passbit","hojd":"0","bredd":"0","rec":"","viktM":"0"}]]
Now, i´d like to search my Json object?!
I´d like to find "viktM" for "typ:Bas 200*600"
//Get balkType weight/m
var searchField = "typ";
var searchVal = "Bas 200*600";
for (var i=0 ; i < balkTypesData.length ; i++){
if (balkTypesData[i][searchField] == searchVal) {
weigth = balkTypesData[i]['viktM'];
console.log(weigth);
}
}
First of all, it seams that i cannot use .lengton "balkTypsData". it gives me 410 hits. Must be all characters?
Second, i cannot find how to access part of my object.
If i use: console.log(balkTypesData[i][searchField]);
I get: "Undefined"
I have also tried to remove the "[i].
So what am i missing?
Be gentle i´m still learning.
Take a look at $.parseJSON() (jQuery) or JSON.parse() (vanilla):
With jQuery
success: function(result){
balkTypesData = $.parseJSON(result);
console.log(balkTypesData);
console.log(balkTypesData[i][searchField]);
}
Without jQuery
success: function(result){
balkTypesData = JSON.parse(result);
console.log(balkTypesData);
console.log(balkTypesData[i][searchField]);
}
When you receive the data from your AJAX request it's not JSON, just a string.
The length result that you're getting is the length of the string, not the amount of elements within the array.
Furthermore you're setting $balkTypes[] which means that you're trying to add 1 entry in the array of $balkTypes however $stmt->fetchAll(); also returns an array so you now have a nested array which is not needed.
In your PHP file change
$balkTypes[] = $stmt->fetchAll()
to
$balkTypes = $stmt->fetchAll()
this will make sure that when you fetch your data it will be an array containing all objects instead of an array containing the array of objects.
Then in your JS, instead of trying to directly read from the string, use JSON.parse() to convert the json string into a collection of JS objects/integers/arrays/strings/booleans
e.g.
success: function(result) {
balkTypesData = JSON.parse(result);
console.log(balkTypesData);
}
EDIT
As pointed out by Armen you could also set the dataType: 'json' in the AJAX request, when the AJAX request returns it will automatically do the JSON.parse() so you can just directly console.log(result); to see the output.
Within the console.log you should now see the nested structure instead of just the string.
From here on your loop which checks the values seems correct and I would not change it unless it tells you that something is wrong.
Docs: JSON.parse();
Set in your jQuery $.ajax request additional attribute dataType: 'json'
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: { params },
success: function( response )
{
// Your data will be already json no need to parse it
console.log(response);
}
});
You are encoding a JSON on the PHP side. You are not decoding it on the JS side.
You should look at JSON.parse()
I've spend over 6 hours to find an exception or a special character to find in my code but I couldn't. I checked every similar messages in here.
I'm sending the form with magnific popup. First I'm using inline popup to open my form than I'm sending all inputs to main.js to validate.
So, I just need a third-eye.
I've got: index.html, register.php, main.js
Here's the code
FORM
JS/AJAX
PHP-register.php
Here goes the error messages
JSON Output
Chrome Console:
Firefox console :
What am i missing?
For the benefit of searchers looking to solve a similar problem, you can get a similar error if your input is an empty string.
e.g.
var d = "";
var json = JSON.parse(d);
or if you are using AngularJS
var d = "";
var json = angular.fromJson(d);
In chrome it resulted in 'Uncaught SyntaxError: Unexpected end of input', but Firebug showed it as 'JSON.parse: unexpected end of data at line 1 column 1 of the JSON data'.
Sure most people won't be caught out by this, but I hadn't protected the method and it resulted in this error.
The fact the character is a < make me think you have a PHP error, have you tried echoing all errors.
Since I don't have your database, I'm going through your code trying to find errors, so far, I've updated your JS file
$("#register-form").submit(function (event) {
var entrance = $(this).find('input[name="IsValid"]').val();
var password = $(this).find('input[name="objPassword"]').val();
var namesurname = $(this).find('input[name="objNameSurname"]').val();
var email = $(this).find('input[name="objEmail"]').val();
var gsm = $(this).find('input[name="objGsm"]').val();
var adres = $(this).find('input[name="objAddress"]').val();
var termsOk = $(this).find('input[name="objAcceptTerms"]').val();
var formURL = $(this).attr("action");
if (request) {
request.abort(); // cancel if any process on pending
}
var postData = {
"objAskGrant": entrance,
"objPass": password,
"objNameSurname": namesurname,
"objEmail": email,
"objGsm": parseInt(gsm),
"objAdres": adres,
"objTerms": termsOk
};
$.post(formURL,postData,function(data,status){
console.log("Data: " + data + "\nStatus: " + status);
});
event.preventDefault();
});
PHP Edit:
if (isset($_POST)) {
$fValid = clear($_POST['objAskGrant']);
$fTerms = clear($_POST['objTerms']);
if ($fValid) {
$fPass = clear($_POST['objPass']);
$fNameSurname = clear($_POST['objNameSurname']);
$fMail = clear($_POST['objEmail']);
$fGsm = clear(int($_POST['objGsm']));
$fAddress = clear($_POST['objAdres']);
$UserIpAddress = "hidden";
$UserCityLocation = "hidden";
$UserCountry = "hidden";
$DateTime = new DateTime();
$result = $date->format('d-m-Y-H:i:s');
$krr = explode('-', $result);
$resultDateTime = implode("", $krr);
$data = array('error' => 'Yükleme Sırasında Hata Oluştu');
$kayit = "INSERT INTO tbl_Records(UserNameSurname, UserMail, UserGsm, UserAddress, DateAdded, UserIp, UserCityLocation, UserCountry, IsChecked, GivenPasscode) VALUES ('$fNameSurname', '$fMail', '$fGsm', '$fAddress', '$resultDateTime', '$UserIpAddress', '$UserCityLocation', '$UserCountry', '$fTerms', '$fPass')";
$retval = mysql_query( $kayit, $conn ); // Update with you connection details
if ($retval) {
$data = array('success' => 'Register Completed', 'postData' => $_POST);
}
} // valid ends
}echo json_encode($data);
Remove
dataType: 'json'
replacing it with
dataType: 'text'
I have the exact same issue and I've found something.
I've commented the line :
dataType : 'json',
after that it was successful but... when I did console.log(data) it returned the main index.html.
That's why you have "Unexpected token <" error and it cannot parse.
Changing the data type to text helped
dataType: 'text'
I have check with JSONlint and my json format was proper. Still it was throwing error when I set dataType: 'json'
JSON Data: {"eventinvite":1,"groupcount":8,"totalMessagesUnread":0,"unreadmessages":{"378":0,"379":0,"380":0,"385":0,"390":0,"393":0,"413":0,"418":0}}
Are you sure you are not using a wrong path in the url field? - I was facing the same error, and the problem was solved after I checked the path, found it wrong and replaced it with the right one.
Make sure that the URL you are specifying is correct for the AJAX request and that the file exists.
Sending JSON data with NodeJS on AJAX call :
$.ajax({
url: '/listClientsNames',
type: 'POST',
dataType: 'json',
data: JSON.stringify({foo:'bar'})
}).done(function(response){
console.log("response :: "+response[0].nom);
});
Be aware of removing white spaces.
app.post("/listClientsNames", function(req,res){
var querySQL = "SELECT id, nom FROM clients";
var data = new Array();
var execQuery = connection.query(querySQL, function(err, rows, fields){
if(!err){
for(var i=0; i<25; i++){
data.push({"nom":rows[i].nom});
}
res.contentType('application/json');
res.json(data);
}else{
console.log("[SQL005] - Une erreur est survenue");
}
});
});
I have got same Error while fetch data from json filesee attached link
"SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data"
So, i check the path of the json file which isn't correct,
const search = document.getElementById("search");
const matchList = document.getElementById("match-list");
//search json data and filter
const searchStates = async searchText => {
const res = await fetch('../state.json');
const states = await res.json();
console.log(states);
}
search.addEventListener('input', () => searchStates(search.value));
so that i changed the path of the file
const res = await fetch('./state.json');
& it gives me array back as a result.
so, check your path & try changed it. It will work in my case. I hope that's works..
JSON.parse() doesn't recognize That data as string. For example {objAskGrant:"Yes",objPass:"asdfasdf",objNameSurname:"asdfasdf adfasdf",objEmail:"asdfaf#asdfaf.com",objGsm:3241234123,objAdres:"asdfasdf",objTerms:"CheckIsValid"}
Which is like this: JSON.parse({objAskGrant:"Yes",objPass:"asdfasdf",objNameSurname:"asdfasdf adfasdf",objEmail:"asdfaf#asdfaf.com",objGsm:3241234123,objAdres:"asdfasdf",objTerms:"CheckIsValid"}); That will output SyntaxError: missing " ' " instead of "{" on line...
So correctly wrap all data like this: '{"objAskGrant":"Yes","objPass":"asdfasdf","objNameSurname":"asdfasdf adfasdf","objEmail":"asdfaf#asdfaf.com","objGsm":3241234123,"objAdres":"asdfasdf","objTerms":"CheckIsValid"}' Which works perfectly well for me.
And not like this: "{"objAskGrant":"Yes","objPass":"asdfasdf","objNameSurname":"asdfasdf adfasdf","objEmail":"asdfaf#asdfaf.com","objGsm":3241234123,"objAdres":"asdfasdf","objTerms":"CheckIsValid"}" Which give the present error you are experiencing.
Even if your JSON is ok it could be DB charset (UTF8) problem. If your DB's charset/collation are UTF8 but PDO isn't set up properly (charset/workaround missing) some à / è / ò / ì / etc. in your DB could break your JSON encoding (still encoded but causing parsing issues). Check your connection string, it should be similar to one of these:
$pdo = new PDO('mysql:host=hostname;dbname=DBname;**charset=utf8**','username','password'); // PHP >= 5.3.6
$pdo = new PDO('mysql:host=hostname;dbname=DBname','username','password',**array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8")**); // older versions
P.S. Outdated but still could be helpful for people who're stuck with "unexpected character".
May be its irrelevant answer but its working in my case...don't know what was wrong on my server...I just enable error log on Ubuntu 16.04 server.
//For PHP
error_reporting(E_ALL);
ini_set('display_errors', 1);
When the result is success but you get the "<" character, it means that some PHP error is returned.
If you want to see all message, you could get the result as a success response getting by the following:
success: function(response){
var out = "";
for(var i = 0; i < response.length; i++) {
out += response[i];
}
alert(out) ;
},
In some cases data was not encoded into JSON format, so you need to encode it first e.g
json_encode($data);
Later you will use json Parse in your JS, like
JSON.parse(data);
Try using MYSQLI_ASSOC instead MYSQL_ASSOC... usually the problem is solved changing that
Good luck!
I had the same error in an AJAX call in an app with pagination and or in any case with a query string in the URL
since AJAX was posting to something like
var url = window.location.href + 'search.php';
...
...
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({search: text}),
})
as soon in the browser URL was added some query string, the error "JSON.parse: unexpected character at line 1 column 1" was popping
the solution has been to simply clean the URL from any query string with
var url = window.location.href.split('?')[0] + 'search.php';
and issue got fixed
So, the error was not the formatting of the Json, instead it was a wrong URL for the POST
#Prahlad is on to something here. I've been seeing this thing for years and it just became background noise to me.
Recently I was doing some brand new stuff and I realized I was seeing that in my console (FF 98.0 (64-bit)) on Mac (12.2.1 (21D62)) where the html is being served by a local NGNIX install (nginx/1.21.6)
Here is the html being served, in it's entirety:
<!doctype html>
<html lang="en">
<head>
</head>
<body>
Some text
</body>
</html>
Now... I don't have a clue why it is happening, but I'm pretty sure it's not the code :-)
I was getting similar error: SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data".
It turns out I was sending data from the backend in JSON format already, so when it arrives on the front-end, I shouldn't use JSON.parse at all:
$.ajax({
type: "get",
url: 'https://localhost:8080/?id='+id,
success: function (response) { // <- response is already JSON
var data = $.parseJSON(response); // <- I removed this line
modalShow(data); // <- modalShow(response) now works!
}
});
I have a page that creates the following output:
<script>
var JSONObject = { "groups":['1210103','1210103','1210103','1210405'],
"prices":['279,00','399,00','628,00','129,00'],
"titles":['','','','']
};
</script>
This page is called by an ajax call:
$.ajax({url:plink,success: function(result) { }
I now need to recieve the json arrays and pass them to ordinary javascript arrays.
How do I do that?
I have tried with:
result = jQuery.parseJSON(data);
mygroups = result.groups;
myprices = result.prices;
mylabels = result.titles;
Change your page so that it just produces JSON:
{"groups":["1210103","1210103","1210103","1210405"],
"prices":["279,00","399,00","628,00","129,00"],
"titles":["","","",""]
}
Note that in JSON, you must use ", not ', for quoting strings.
Have it return a Content-Type header of application/json. If for some reason you can't set the correct Content-Type header on the response, you can force jQuery to treat the response as JSON by adding dataType: 'json' to your ajax call, but it's best to use the correct content-Type.
Then in your ajax call's success callback, result will already be a deserialized object with three properties (groups, prices, titles), which will be JavaScript arrays you can work with.
Live Example | Source
You've said in the comments below that the page is a full HTML page with the embedded script tag and you have no control over it other than the contents of the script tag, because of the CMS you're using.
I strongly suggest moving to a more flexible CMS.
Until/unless you can do that, you can simply receive the page as text and then extract the JSON. Change your script tag to something like this:
<script>
var JSONObject = /*XXX_JSONSTART_XXX*/{"groups":["1210103","1210103","1210103","1210405"],
"prices":["279,00","399,00","628,00","129,00"],
"titles":["","","",""]
}/*XXX_JSONEND_XXX*/;
</script>
Note the markers. Then you can extract the JSON between the markers, and use $.parseJSON on it. Example:
(function($) {
$.ajax({
url: "http://jsbin.com/ecolok/1",
dataType: "text",
success: function(result) {
var startMarker = "/*XXX_JSONSTART_XXX*/";
var endMarker = "/*XXX_JSONEND_XXX*/";
var start, end;
start = result.indexOf(startMarker);
if (start === -1) {
display("Start marker missing");
}
else {
start += startMarker.length;
end = result.indexOf(endMarker, start);
if (end === -1) {
display("End marker missing");
}
else {
result = $.parseJSON(result.substring(start, end));
display("result.groups.length = " + result.groups.length);
display("result.prices.length = " + result.prices.length);
display("result.titles.length = " + result.titles.length);
}
}
}
});
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
})(jQuery);
Live Copy | Source
I am newbie in OOP and I try to build an object using ajax request. What I need is to get 'responseArray' in JSON format and than work on it.
function adres(adres) {
this.adres_string = adres;
var self = this
$.ajax({
type: 'POST',
url: "http://nominatim.openstreetmap.org/search?q="+adres+"&format=json&polygon=0&addressdetails=0",
success: function(data) {
self.responseArray = eval('(' + data + ')')
}
})
//Method returning point coordinates in EPSG:4326 system
this.getLonLat = function() {
var lonlat = new OpenLayers.LonLat(this.responseArray.lon, this.responseArray.lat);
return lonlat;
}
}
The problem starts when in appilcation code I write:
var adr = new adres('Zimna 3, Warszawa');
adr.getLonLat();
This returns nothing as there is no time get the response from the server.
How to write it properly in the best way? I've read about when().then() method in jQuery. This may be OK for me. I just want to get know best practise
This is how AJAX works (notice the A-synchronous part). You are right, the moment you call adr.getLonLat() response did not yet came back. This is the design I would suggest: just pass callback function reference to adres constructor:
function adres(adres, callbackFun) {
//...
success: function(data) {
var responseArray = eval('(' + data + ')')
var lonlat = new OpenLayers.LonLat(responseArray[i].lon, responseArray[i].lat);
callbackFun(lonlat)
}
and call it like this:
adres('Zimna 3, Warszawa', function(lonlat) {
//...
})
Few remarks:
adres is now basically a function, you don't need an object here.
do not use eval to parse JSON, use JSON object.
Are you sure you can POST to http://nominatim.openstreetmap.org? You might hit the same origin policy problem
where is the i variable coming from in responseArray[i]?