Hi Guys the problem is simple but I can't resolve it - it happen only in FIREFOX here is code:
$.ajax({
type: "POST",
url: validUrl,
data: serializedForm,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType(jsonMimeType);
}
},
dataType: "json",
success: function(resp){
console.log(resp);
var arr = jQuery.parseJSON(resp);
}
});
console.log give such answer:
["emailAddress.used", "register.confirmRulesError"]
I have error in:
var arr = jQuery.parseJSON(resp);
Full error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
This happens only in FireFox and I can't find solution.
Response header is: Content-Type application/json;charset=UTF-8
Any ideas how to solve this ?
try without parse json you data.because,
response data look like this,
["emailAddress.used", "register.confirmRulesError"]
if you tring to parse,need key,value pair in json,that is reason it thorw exception.
{["emailAddress.used", "register.confirmRulesError"]}//not allowed.
Related
I come asking because I can't find any more trail for my problem. Hope someone could help me :)
Since several week, all in a sudden, my json got a weird unreadable character, provoking ajax request to raise an error instead of success state.
My code didn't change. I tried more tips like a simple boolean as return in the json. But nothing can help.
I lighten the code in order to avoid possible wrong character data.
I get an SyntaxError: Unexpected '' on line 1 when i try to validate on jsonlint he detects the wrong character
my code server side in php is the following :
$resultat = array();
$resultat['Success'] = true;
echo json_encode($resultat);
and my js ajax request :
var param = [{ name: "tbActionToDo", value: "InitialiseMailbox" }];
$.ajax({
type: "POST",
url: "actions/DatasourceEmail.php",
data: param,
dataType: "json",
dataFilter: function(data, type){
return data;
},
error: function(xhj, statut, thrown){
Notify("Danger", xhj.responseText);
},
success: function(result){
// do something
}
});
Thanks for your time and help !!
I have an ASP.Net MVC Application and I got a JSON response from the server using this code segment.
public JsonResult GetVehicleByID(string VehicleID)
{
db.Configuration.ProxyCreationEnabled = false;
var res = from type in db.Vehicles
where type.ID == VehicleID
select new
{
ID = type.ID,
RegNo = type.RegNo
};
return Json(res, JsonRequestBehavior.AllowGet);
}
The code above returns the following Json (Google Postman)
[
{
"ID": "000001",
"Type": "Internal"
}
]
I handled the response using following jQuery Ajax
function GetVehicle(id) {
$.ajax({
async: true,
url: "GetVehicleByID?VehicleID=" + id,
cache: false,
dataType: "json",
contentType: "application/json",
success: function (data) {
//Parsing Method 1
//var a = jQuery.parseJSON(data);
//console.log(a.Type);
//Parsing Method 2
var b = $.parseJSON(data);
console.log(b['Type']);
}
});
}
I was unable to extract the Type element from this response. There are several similar questions in the Stack Overflow & solutions of those questions are about parsing. I tried to parse in 2 ways but the browser log gives following error
Uncaught SyntaxError: Unexpected token o in JSON at position 1
Helping is highly appreciated than flagging this question as duplicate.
Try just console.log(data[0].Type). I believe jQuery is already parsing the response as JSON for you because you specified dataType: "json" and the response from the server had the right Content-Type header.
As #smarx said jQuery already decoded json for you, so you can access directly to the Type from the data variable, but if not, you can parse the json response with the JS function parse:
var json_data = JSON.parse(data);
console.log(json_data);
I'm trying to make a graphic with jqplot extracting the values vía mysql ajax, I have read so much information about this, i'm IT and to me it's a little embarrasing making this question. It's causing me a big headache :(
I've spent 20 days resolving this but i can't alone myself, anyone can help me please? I have tried almost everything (json.parse, parsejson, getjson, datatype html, datatype json, method get and post.....)
I know it will be easy...
Why crash when i try to do JSON.parse(resultado) ?
http://jsonlint.com/ say it's a Valid Json, but when I try to do JSON.parse he give me an exception saying ("JSON.parse: unexpected character at line 1 column 1 of the JSON data")
It seems is the [ character
Here is the php:
<?php include('conex.php');
$datos=mysql_query("SELECT * FROM Meteorologia");
$arrDatos = array();
while ($rs=mysql_fetch_assoc($datos))
$arrDatos[] = array_map('utf8_encode', $rs);
echo json_encode($arrDatos);
?>
I obtain:
[{"FECHA":"2015-01-01","OZONO":"3","KT":"2","VV":"4"},{"FECHA":"2016-03-03","OZONO":"68","KT":"86","VV":"78"}]
The js is:
try
{
var strHtml = "";
$.ajax({
global: false,
dataType: "html",
async: false,
type: "POST",
url: $("#form").attr('action'),
data: $("#form").serialize(),
success: function(resultado){
alert('success!!'+resultado);
console.log(typeof resultado);
console.log(resultado);
//var datosRecibidos = JSON.parse(resultado);
//var datosRecibidos = jQuery.parseJSON(resultado);
var lista = "";
$.each( resultado, function( key, value ) {
if(value.FECHA == "2015-01-01")
{
alert('si!!');
}
else
{
alert('sino!!');
}
});
},
error: function(data){
alert('Error!!: '+data);
}
});
}
catch(ex)
{
alert("catch!!"+ex);
}
With the $each key value ... can i move inside the array?
After trying a lot of things (changing datatype json,html,..., method get, post...)
I debugging with the address file:///C:/xampp/htdocs/traerdatos/index.html
instead of http://localhost/traerdatos/index.html
So the solution is to CHANGE THE ADDRESS TO LOCALHOST
(Thanks to reformed that helps me with his vision)
Novel error =)
I've got two pages that use the same js-file to call certain PHP-file and get data from there in JSON format. Although the data that gets in the PHP-file AND data that gets out is exactly the same, Ajax on the second page returns 'parsererror' SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data.
$.ajax({
type: 'POST',
dataType: "json",
data: {objtyp: this.objtyp, objid: this.objid},
url: '/admin/getfieldsadd.php',
success: function(data) {
//not going to happen
},
error: function (xhr, status, text) {
switch (status) {
case 404:
alert('File not found');
break;
case 500:
alert('Server error');
break;
case 0:
alert('Request aborted');
break;
default:
alert('Unknown error: ' + status + " " + text);
}
}
So have anybody encountered the same problem?
This sounds reminiscent of the dreaded BOM. Excerpt from that link:
At the beginning of a page that uses a Unicode character encoding you
may find some bytes that represent the Unicode code point U+FEFF BYTE
ORDER MARK (abbreviated as BOM).
The BOM, when correctly used, is invisible.
Perhaps check that the file's encoding is set to UTF8 Without BOM.
Maybe a mime type error.
Try to add the beforeSend property like this in your AJAX call :
$.ajax({
type: 'POST',
dataType: "json",
data: {objtyp: this.objtyp, objid: this.objid},
url: '/admin/getfieldsadd.php',
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/json");
}
},
...
}
It appears the trouble was in jQuery version. Now that it's updated all seems to work fine.
This question already has answers here:
JSON+Node.js - Unexpected token o
(2 answers)
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 9 years ago.
The following ajax call gives the following result:
$.ajax({
type: "POST",
url: //**My full URL goes here**,
data: {sources: sources},
dataType: "json",
success: function(data) {
alert(data);
alert(data.length);
for (var i = 0; i < data.length; i++)
{
alert(data[i]);
}
}
});
Result:
data:
[objject object],[objject object],[objject object]
length:
3
in loop:
[objject object]
[objject object]
[objject object]
and the following code , in which I just added:
var data = $.parseJSON(data);
$.ajax({
type: "POST",
url: //**My full URL goes here**,
data: {sources: sources},
dataType: "json",
success: function(data) {
var data = $.parseJSON(data);
alert(data);
alert(data.length);
for (var i = 0; i < data.length; i++)
{
alert(data[i]);
}
}
});
The above code gives me the following error:
Uncaught Syntax Error: Unexpected token o
Why is that? Am I doing something wrong? How can I fix it?
The data is already a parsed object since you are passing dataType: 'json', so there is no need to parse it again.
Again to debug and inspect the value of data, use console logging instead of alert(), like console.log(data)
Stop use alert to debug, use console.log instead.
success: function(data) {
// in the browser console, you will see the data structure.
// then do what you want
console.log(data);
// ...