JSON, Syntax error : unexpected token I(...) - javascript

I've a such js-function, which sends data to file, which contains a function, which sends back JSON-response:
function deleteCategory(id){
console.log(id);
$.ajax({
url: '<?php echo $cfg['options']['siteurl']; ?>/gears/ajax.deletePkgCatAsideMenu.php',
type: 'POST',
dataType: 'JSON',
data: {idItem:id},
success: function(data) {
console.log(data);
if (data.type=='error') {
notify(data.type, data.type, data.text);
} else{
document.location.reload();
}
},
error: function(v1,v2,v3) {
alert('Ошибка!\nПопробуйте позже.');//in english it will be: alert('Error!\nTry again later.');
console.log(v1,v2,v3);
}
});
}
In the end of that file these actions take place:
$q = 'DELETE FROM `pkg_cat_aside_menu` WHERE pkg_cat_ddlist_id='.$idItem;
$db->query($q);
exit(json_encode(array('type'=>'ok','text'=>'Удаление произведено!')));
//or in english: exit(json_encode(array('type'=>'ok','text'=>'Deleted!')));
This is a response text:
"int(13) {"type":"ok","text":"\u0423\u0434\u0430\u043b\u0435\u043d\u0438\u0435 \u043f\u0440\u043e\u0438\u0437\u0432\u0435\u0434\u0435\u043d\u043e!"}"
And error syntax error: unexpected token i(...)
I think, it take place, because I did actions with data base (delete), which response a deleted record number (13), and it has been included to json-respose. How to fix it?

int(13) makes me think that you have a var_dump( $idItem ); somewhere earlier in your PHP code, which is causing the response to be invalid.

Related

ajax post call not working

I am trying to call MVC Controller from jquery but not able to place the call. Is there any problem in below code
Please figure out that if any problem and also I am not getting any error.
url="http://localhost:49917/Account/SaveAddress"
this.SaveAddress = function (url, addressData)
{
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: JSON.stringify(addressData),
contentType: 'application/json; charset=utf-8',
success: function (responseDetail) {
},
error:function(e)
{
},
});
return 0;
};
public async Task<ActionResult> SaveAddress(AddressListViewModel addressListVM)
{
bool response;
string message;
if (addressListVM.ID <= 0)
{
response = await Task.Run(() => AccountManager.Instance().AddAddress(addressListVM));
message = response ? "New address added successfully." : "Failed to add new address.";
}
else
{
response = await Task.Run(() => AccountManager.Instance().UpdateAddress(addressListVM));
message = response ? "Selected address updated successfully." : "Failed to update selected address.";
}
ModelState.Clear();
return Json(new { responsestatus = response, message = message }, JsonRequestBehavior.AllowGet);
//return PartialView("_AddressDetail", BuildAddressListEntity(
// UserManager.FindById(User.Identity.GetUserId()), response, message, addressListVM.ID, true));
}
Yes, you are missing a closing bracket at the end of the this.saveaddress function
this.SaveAddress = function (url, addressData)
{
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: JSON.stringify(addressData),
contentType: 'application/json; charset=utf-8',
success: function (responseDetail) {
},
error:function(e)
{
},
});
after all of that .. you need one more closing bracket:
}
;)
What does the console display? If you are using Chrome then right-click, choose Inspect, and find the Console tab. If you are calling the AJAX function correctly then something must be displayed in this Console tab which will probably lead you in the right direction better than I could with the information I have.
Put a breakpoint in your success and error functions. If it hits the error function then the issue is either that the controller action was not found or that the data is not valid json (either the post data or return data). You should add the errorThrown parameter to the error function so you can easily see what the issue is. You also do not need to stringify the data if it is already valid json, but if it is a string representing json data, you will need to use json.parse (sorry for the incorrect case).

Ajax post not received by php

I have written a simple code. In order to avoid flooding a JSON server, i want to break up the JSON response in pieces. So my jquery code should be parsing one variable ("page") to the php page that handles the JSON Oauth Request. On success, it should append the DIV with the latest responses.
My code should be working, except for the fact that my ajax post is not being received by my php file.
Here goes
archief.html
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: page,
success: function() {
console.log(page);
$.get("trytocombinenewageandgettagsendates.php", function(archief) {
$('#archief').append(archief);
});
},
error: function(err) {
alert(err.responseText);
}
});
return false;
});
The php file doesn't receive anything.
var_dump($_POST);
gives me array(0) { }.
Very strange, i'd really appreciate the help!
You are sending a string instead of key-value pairs. If you want to use $_POST you need to send key-value pairs:
...
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function() {
...
If you send a single value or string, you would need to read the raw input.
Also, you are sending 2 GET requests and 1 POST request to the same file. Is that intentional? Note that only the POST request will have the $_POST variable set.
Thank you for your help and not letting me post "this still doens't work" posts :)
I made the mistake of loading the "unConsulted" php file [$.get("trytocombinenewageandgettagsendates.php"] upon success. Instead, i append the response of the PHP.
The working code below:
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
//$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function(response){
$("#archief").append(response);
},
error: function(err) {
alert(err.responseText);
}
});
return false;

send data to json from php

my json script is:
// add button .click
$('a.add').click(function(){
$('#loader').show();
var url = "/?"+$("form[name='jsms_add']").serialize();
ajx = $.ajax({
url: url,
type: 'post',
data:{ajax:1},
dataType: 'json',
success: function(r) {
$('#loader').hide();
if(r.r != 0){
alert("ok");
jsmsalert($('#alert_add'),'success',r.m);
apendtable(r.r)
$("tr").removeClass("odd");
$("tr.viewrow:odd").addClass("odd");
$("tr.editrow:odd").addClass("odd");
$('td[colspan="7"]').remove();
}
else{
jsmsalert($('#alert_add'),'error',r.m,0);
}
},
error: function(request, status, err) {
$('#loader').hide();
jsmsalert($('#alert_add'),'error','error...');
alert( "ERROR: " + err + " - " );
}
});
and in my php file i have
$data = array(
'r' => '1',
'm' => '1',
);
json_encode($data);
now i want to know that how can i send a value to json that r.r != 0 be true and my success code execute?
In Firefox the error is "SyntaxError: JSON.parse: unexpected character"
this code used by another site by i don't know what happend in php file
my problem is that how can i send some data (for example r=1) to my json, because i want to check that if r=1 (means success) do something and show text from m (message) in my page
please help me to correct php file
thank
In your php file make sure you are echoing the encoded data,
like so:
$data = array(
'r' => '1',
'm' => '1',
);
echo json_encode($data);
If you don't echo the data it will not make it back to your JavaScript.
If your JavaScript is what's throwing the errors try commenting out the dataType: 'json', and console logging the return. It might be php is throwing errors that jquery is refusing to parse.
$.ajax({'url': url,type: 'post',data:{ajax:1}, success: function(returnData){
console.log(returnData);
}});

Uncaught SyntaxError: Unexpected token {

Error prompted when execute console.log($obj.longurl) from the Chrome Developer Console
Uncaught SyntaxError: Unexpected token {
$.ajax.complete
L jquery.min.js:19
N
Below is the script I execute from a HTML page and submit a form to call an external PHP file.
Javascript is called from http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js
$('#shortener').submit(function(e) {
e.preventDefault();
$('#status').text('');
$.ajax({
cache: false,
type: "POST",
dataType: "json",
data: $('#shortener').serialize(),
url: $('#shortener').attr('action'),
complete: function (XMLHttpRequest, textStatus) {
console.log(XMLHttpRequest);
$obj = JSON.parse(XMLHttpRequest.response);
if ($obj.loginResult == "Passed") {
($('#longurl').val() === "") ? console.log("Empty longurl") : console.log($obj.longurl);
} else {
$('#status').text("Login Failed");
};
}
});
return false;
});
PHP
echo json_encode(array('loginResult' =>'Passed'));
echo json_encode(array('longurl' => BASE_HREF . $shortened_url));
typeof $obj.longurl is string but don't know why it can be returned to the $('#shortener').val(), anyone have similar experience and have the solution?
Your PHP code is producing invalid JSON. You are basically echoing two JSON encoded objects after each other, which overall results in invalid JSON. It will look like:
{"loginResult": "Passed"} {"longurl": "<some URL>"}
The second { is the syntax error.
It should either be an array of objects (although that would be a strange structure)
[{"loginResult": "Passed"}, {"longurl": "<some URL>"}]
or one object
{"loginResult": "Passed", "longurl": "<some URL>"}
Create and encode one array:
echo json_encode(array(
'loginResult' => 'Passed',
'longurl' => BASE_HREF . $shortened_url
));
Another problem might be that, at least officially, the jqXHR object passed to the complete callback doesn't have a .response property. Since you also already set the dataType: 'json' option, there is no need for you to parse the response explicitly.
Here is an improved version of your code:
$.ajax({
cache: false,
type: "POST",
dataType: "json",
data: $('#shortener').serialize(),
url: $('#shortener').attr('action'),
}).done(function (data) {
if (data.loginResult == "Passed") {
($('#longurl').val() === "") ? console.log("Empty longurl") : console.log(data.longurl);
} else {
$('#status').text("Login Failed");
}
});

ajax catch correct error code

i have this little code to post to my server
$.ajax({
type: 'POST',
url: 'post.php',
data: { token: '123456', title: 'some title', url: 'http://somedomain.com', data: '' },
success: function(data){
alert (data)
}
});
Wondering how i can "catch" the different errors for ajax request:
for eg, post.php return 'token error' when invalid token has been posted, or 'invalid title' for missing title.
Thanks in advance
If the server sends something else than 200 status code you could use the error handler:
$.ajax({
type: 'POST',
url: 'post.php',
data: {
token: '123456',
title: 'some title',
url: 'http://somedomain.com',
data: ''
},
success: function(data){
alert(data);
},
error: function() {
alert('some error occurred');
}
});
If your server performs some validation on the request arguments maybe it could return a JSON object containing the error information (and set the proper Content-Type: application/json):
{ error: 'some error message' }
In this case you could handle this in the success callback:
success: function(data) {
if (data.error != null && data.error != '') {
// TODO: the server returned an error message
alert(data.error);
} else {
// TODO: handle the success case as normally
}
}
// build the initial response object with no error specified
$response = array(
'error' => null
);
// the data checks went fine, process as normal
if (data is ok) {
$response['some_object'] = value;
// something is bad with the token
} else if (bad token) {
$response['error'] = 'token error';
// something is bad with the title
} else if (bad title) {
$response['error'] = 'bad title';
// some other error occured
} else {
$response['error'] = 'unspecified error';
}
// output, specifying that it's JSON data being returned
header('Content-Type: application/json');
echo json_encode($response);
and....
// $.ajax({ ...
success: function(data){
if (!data.error){
alert('OK!');
}else{
alert('Error: '+data.error);
}
}
// });
Something like that perhaps? (Unless you're talking legitimate AJAX errors, in which case supply the error: function(x,t,e){} ajax option or use .ajaxError)
What I like to do is set the dataType for the $.ajax() to 'json' and then in the PHP page you can just echo a json_encode()ed associative array. This will let you reference the values via your function parameter data (i.e. data.success, data.message). Let me know if you need some examples.
You probably want to set the 'error' handler function, which would treat the error you received.
Take a look at http://api.jquery.com/jQuery.ajax/ in the error setting.

Categories

Resources