I have an error in my ajax:
Cannot read property '0' of undefined
dmpConnectInstance.hl_readCpxCard(getCpsPinCode(), function (a) {
var path = "cpx";
$.ajax({
type: "POST",
url: path,
data: a,
success: function (data) {
//
$("#res").html("okyou" + data.PracticeLocations[0].s_practiceLocationName);
console.log('yooo' +
data.PracticeLocations[0].s_practiceLocationName);
}
,
error: function () {
console.log('ko');
}
});
});
Here is the json format:
{
"PracticeLocations":[
{
"s_practiceLocationActivity":"SA07",
"s_practiceLocationHealthcareSettings":"SA07",
"s_practiceLocationName":"CABINET M. INFIRMIER3681"
}
],
"i_remainingPinCodeInputs":3,
"s_given":"ALAIN",
"s_internalId":"00B6036814",
"s_name":"INFIRMIER3681",
"s_profession":"60",
"s_professionOid":"1.2.250.1.71.1.2.7",
"s_speciality":"",
"s_status":"OK"
}
I think I have a problem with the data, when I debug data I got empty message.
Otherwise if I put directly into the function:
console.log('yooo'+a.PracticeLocations[0].s_practiceLocationName);
I got the result.
The JSON content you display in your post, is that what is going in or coming out, and how did you confirm the result if indeed the case? The nature of the error is saying that data.PracticeLocations is null and doesn't contain anything at position 0. If data came back as a truly empty result, then that would make sense and including the code that returns your response would help.
Your subsequent statement in the post was:
console.log('yooo'+a.PracticeLocations[0].s_practiceLocationName);
This has a.PracticeLocations, not data.PracticeLocations, which variable a is not referenced anywhere. I presume that is a typo?
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 am having a problem with this code, could someone help me out?
<script type="text/javascript">
$(document).ready(function()
{
$obj = $.get('getSesion.php',function(data){ } );
//$dato=JSON.stringify(obj);
//$dato=dojo.toJson(obj);
alert($obj);
if($obj != 'NULL')
{
$('#apDiv7').load('logeado.php');
}else{
$('#apDiv7').load('deslogeado.php');
}
}
);
</script>
The problem is that from $obj I get [object Object]. I searched how to convert it but I had no success.
MORE DETAILS. From data I can get a number (0-infinite) or the string NULL. Depend on what value I get, in apDiv7 I will load login window or a window's user connected.
I tried
var data =$obj.d;
but i get "undefined" string
Console log
http://imageshack.com/a/img46/4004/ufgv.jpg
Solution for this case:
var msg = $.ajax({type: "GET", url: "getSesion.php", async: false}).responseText;
.get is an async call, so you should be doing this logic in the callback:
$.get('getSesion.php',function(data) {
console.log(data);
});
Always use console.log so you can actually expand the complex object. Then simply reference the property names of the data response object.
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}}
I'm trying to fetch a custom JSON feed I have written with jQuery using the getJSON method. For an unknown reason the URL seems to be having cache_gen.php?location=PL4 stripped from the end and replaced with [object%20Object] resulting in a 404 error occurring.
Here's the jQuery I'm using:
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
console.log(api_location + '?location=' + user_location);
jQuery.getJSON({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
From the console log I can see the URL string is calculated correctly as: http://weatherapp.dev/cache_gen.php?location=PL4
However the second line in the console is: Failed to load resource: the server responded with a status of 404 (Not Found).
Can anyone point me in the right direction with this?
UPDATE 19/01/2013 23:15
Well, I've just converted so that is fits the docs perfectly using $.ajax. I've also added a fail event and logged all of the data that gets passed to it.
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
var url = api_location + '?location=' + user_location;
console.log(url);
jQuery.ajax({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log('textStatus: ' + textStatus );
console.log('errorThrown: ' + errorThrown );
console.log('jqXHR' + jqXHR);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
After this my console gives me the following information:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
I have ensured the headers for the JSON feed are current, and the feed is definitely serving valid JSON (it effectively caches a 3rd party service feed to save costs on the API).
The reason why you see this error:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
Is because your JSON is invalid. Even if a response comes back from the server correctly, if your dataType is 'json' and the returned response is not properly formatted JSON, jQuery will execute the error function parameter.
http://jsonlint.com is a really quick and easy way to verify the validity of your JSON string.
I was running into the same issue today. In my case I was assigning a JSON object to a variable named 'location' which is a reserved word in JavaScript under Windows and appearantly is a shorthand for windows.location! So the browser redirected to the current URL with [object%20Object] appended to it. Simple use a variable name other than 'location' if the same thing happens to you. Hope this helps someone.
Check out the actual function usage:
http://api.jquery.com/jQuery.getJSON/
You can't pass on object parameter into $.getJSON like with $.ajax, your code should look like this:
jQuery.getJSON('api_location + '?location=' + user_location)
.done(function() {
//success here
})
.fail(function() {
//fail here
});
To maybe make it a little clearer, $.getJSON is just a "wrapper function" that eventually calls $.ajax with {type:'get',dataType:'JSON'}. You can see this in the link I provided above.