I am trying to retrieve data from a web service using an ajax call. The call is succeeding, because I am able to successfully print the data in the console using console.log(). However when I attempt to take my data, and convert from a string into an array, the code fails. I am currently trying to use eval, but have also tried to use JSON.parse. Both fail with an error of Uncaught SyntaxError: Unexpected identifier. Any ideas on how to get around this?
$.ajax({
type: "POST",
url: (redacted)
data: (redacted)
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
console.log(response.d);
var data = eval("[" + response.d + "]");
This is where my code fails. Like I said, console.log(response.d) works, with an output simlilar to this: { 'code':'1234', 'description':'Record 1'}, { 'code':'1234', 'description':'Record 2'}, { 'code':'1234', 'description':'Record 3'}
Is my problem the use of eval? Any input would be greatly appreciated
First, I would use JSON.parse() here instead of eval for decoding JSON strings.
However in this case I believe the return data has already been decoded by jQuery. console.log(response.d) returns a nice looking object and not a "{...}...." string correct?
Related
Ajax request is executing, but it returns not curent_day variable but null.
Js:
$.ajax({
url: 'planing/next-day',
data: {new_curent_day: $('.owl-item.center .slide_day').text()},
dataType: 'json',
type: 'POST',
success: function(curent_day) {
alert(curent_day);
},
error: function(xhr, status, error) {
alert(xhr.responseText + '|\n' + status + '|\n' +error);
}
});
Controller:
public function actionNextDay() {
if (Yii::$app->request->isAjax){
$this->planing_model->curent_day = Yii::$app->request->post('new_curent_day');
return Json::encode($this->planing_model->curent_day);
}
}
May be the problem is your are sending the POST data as JSON so your not able get it through
Yii::$app->request->post('new_curent_day');
Try this they have updated JSON parser set and to get the JSON value through yii.
Error in accessing post json data in yii2
Use the Javascript console and debugger in your browser to see what $('.owl-item.center .slide_day') contains. Make your API endpoint log what it gets in the post variables.
The typos in variable names make me worry that you might refer to the wrong thing. planing has two n's, curent has two r's. This code looks consistent at least but if I came across this code I would suspect current and curent got mixed up.
I am developing i small app that displays some JSON data
inside of a listview. To receive the data I am using a simple request.
And I am getting always the same issue:
Uncaught SyntaxError: Unexpected token :
my code:
$.ajax({
url: 'http://localhost/documents.json',
data: {
format: 'json'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
dataType: 'jsonp',
success: function(data) {
// do something with the data
},
type: 'GET'
});
});
My JSON file is valid. I checked it with a JSON validator.
Invalid JSON (no matter how mangled) cannot generate a JavaScript syntax error if you parse it with JSON.parse() or any decent dedicated parser (and that's what jQuery does). The same happens with all other standard data types (XML, HTML, plain text...). All symptoms suggest you're expecting JSONP but getting some other data type. The builtin browser network pane should reveal what you're getting exactly.
Whatever, if you only want JSON and nothing but JSON you should simplify your code as follows:
Omit protocol and host:
url: 'http://localhost/documents.json',
should be:
url: '/documents.json',
(Probably not required, but will help to void errors.)
Ask for the correct data type:
dataType: 'jsonp',
should be:
dataType: 'json',
Do not parse again what jQuery already parsed for you:
var json = $.parseJSON(data);
should be:
var json = data; // Yeah, nothing :)
This should be enough for local AJAX. If you really need a cross-site request (I asked twice and never got an answer) you have to tweak your server to either return the appropriate CORS headers or implement JSONP data type and change your client-side code accordingly because you'll no longer have JSON—because JSONP is not JSON!
Check if your json is valid by using jsonlint.com or you can use jsonmate.com. These are very helpful to me when I'm debugging json.
Also - it would help to have a link to the full code. Use jsfiddle.net to put your code into - then link it to this post. This will help the community debug your code.
I've searched around for this error and none of the solutions appear to help me with what I am getting. I am doing an ajax request, and I am trying to retrieve the json output released by the server. I can print out the json that i am trying to capture (via console.log()) not process it in the jQuery.parsejson(). I keep getting a "Uncaught SyntaxError: Unexpected token o" error. Please can someone advise?
my code:
// Make ajax request
$.ajax({
url: 'http://localhost/multipleFileUpload_adam/webservice/delete_pdf.php',
data: {delete_array: jsonString},
dataType: 'json',
type: 'POST',
success: function(data){
console.log(data);
var x = jQuery.parseJSON(data);
},
console.log(data) gives the following ( am trying to retrieve the 'success_deleted' array:
Object {success_delete: Array[2], unsuccess_delete: Array[0], input array: Object}
if I remove the line of code :
var x = jQuery.parseJSON(data);
Then I am able to get the console.log(data) to work. if i add it i get the error mentioned above.
This line:
dataType: 'json',
tells jQuery to ignore the content-type returned by the server and always parse the response as if it was JSON.
Then:
success: function(data){
The JavaScript value (which is an object) that you get from parsing the JSON is passed into data.
This line:
jQuery.parseJSON(data);
Takes the value of data (an object)
Converts it into a string (which will be "[object Object]")
Tries to parse that string as JSON (which it isn't).
Then I am able to get the console.log(data) to work. if i add it i get the error mentioned above.
Yes. That is the expected behaviour. Don't do that. Just work with the already parsed data in data.
there is a parse error because data is already an object so it is expecting json and getting Object. 'O' is the unexpected character. Try without the parseJSON function.
I want to use AJAX and the SoundCloud API to get the tracks of a user.
jQuery.ajax({
url: 'http://api.soundcloud.com/resolve?url=http://soundcloud.com/[SOME USER]/tracks/&format=json&consumer_key=[MY KEY]&callback=?'
, dataType: 'jsonp'
, success: function( data ) {
console.log( data );
}
});
I can see that chrome gets the json data but I get the error
Uncaught SyntaxError: Unexpected token ILLEGAL
in the console.
The issue is probably that the json file is an json array. Could that be the error?
And if yes, how can I convert the array into single objects?
The problem is that the description field in track id #159500192 ('Summer Chords Pt. 2' (Electro House Mix)) has invisible characters that are not legal inside of JavaScript strings, so the JavaScript parser chokes when trying to the run the JSONP response as a script. SoundCloud should encode these values when serving content via JSONP.
Because SoundCloud supports CORS, you don't need to use JSONP at all. You can simply request the file directly, by removing the callback=? parameter and using dataType: json (not jsonp):
jQuery.ajax({ url: "https://api.soundcloud.com/resolve?url=http://soundcloud.com/[USER]/tracks/&format=json&consumer_key=[KEY]",
dataType: 'json',
success: function(d) { console.log(d); }
});
I am using Laravel 4 as a backend (though I don't think it is necessarily causing an issue here), and am trying to do some AJAX validation (to preserve dynamically populated dropdowns).
First of all, the code I am using to call the AJAX request:
$('#add_character_submit').click(function(e) {
e.preventDefault();
$.ajax({
url: '{{ URL::route("addcharactercheck") }}',
type: 'POST',
dataType: 'json',
data: {
'name': $('#name').val().replace('/[^a-zA-Z0-9\s\-\(\)\.\,]+/', ''),
'gender': $('#gender').val().replace('/[^0-9]+/', ''),
'server': $('#server').val().replace('/[^0-9]+/', ''),
'faction': $('#faction').val().replace('/[^0-9]+/', ''),
'race': $('#race').val().replace('/[^0-9]+/', ''),
'class': $('#class').val().replace('/[^0-9]+/', ''),
'path': $('#path').val().replace('/[^0-9]+/', '')
}
}).done(function(response) {
console.log(response);
}).fail(function(response) {
console.log(response.errors);
});
});
And then this is the response I am getting:
{"success":false,"errors":{"name":["Please pick a name"],"server":["Please pick a server"],"faction":["Please pick a faction"],"race":["Please pick a race"],"class":["Please pick a class"],"path":["Please pick a path"]}}
If I put that into a JSON validator, it says it passes.
I am returning the response as Content-Type: application/json and I have dataType: 'json' in the AJAX request as above, however trying to console.log(response.errors) results in undefined.
I have also tried using $.parseJSON on the response, however that gives an unexpected character type error (note this is just to double check).
If I type the following in the console:
var x = {"success":false,"errors":{"name":["That name is not available"],"faction":["Please pick a faction"],"race":["Please pick a race"],"class":["Please pick a class"],"path":["Please pick a path"]}}
console.log(x.errors);
Then it correctly outputs the errors in the console.
Despite searching a good dozen or so similar questions here on SO, they all seem to suggest an accepted answer of one or both of the above - I can't find anything different to try.
The right answer was established in the comments:
On .fail, jQuery returns a jqXHR object, instead of data. The data you're looking for is in the responseText property of this object.
.fail(function(jqXHR) {
var json = $.parseJSON(jqXHR.responseText);
console.log(json);
});