Uncaught SyntaxError: Unexpected token { - javascript

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");
}
});

Related

Ajax call is throwing an Invalid Character error

I am working on a Java application using Struts 1.2. I am facing a blocking error when I make an AJAX call to a Struts action.
The struts action, getInfos.html, is called successfully but after that when I make the AJAX call I get the following error in the console:
Invalid Character/parsing error
The data variable is a correct JSON format. Why would it trigger this error?
I've gone through all the similar questions online but I don't know why it's triggering an invalid character error.
$.ajax({
type: "POST",
url: "getInfos.html",
dataType: "json",
async: false,
cache: false,
data: {
Code: "code1",
type: "type",
mand: "mand",
signature: "signature"
},
success: function(data) {
console.log('succes');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log('my error is : ' + errorThrown);
}
});
In the execute method that is handling the ajax request, i am calling the attributes using the request
final String code = (String) request.getAttribute("code");
final String signature = (String) request.getAttribute("signature");
final String type= (String) request.getAttribute("type");
/*
Making a call to a webservice using the attributes bellow,
using **response** Object
*/
if (reponse != null &&
(CodeReponseHttp.OK.equals(reponse.getCodeReponse()))) {
jsonObj.put(SUCCESS_CALL, true);
} else {
jsonObj.put(SUCCESS_CALL, false);
}
return new JsonResult(jsonObj);
But they are set to null; which means that the ajax data is not passed into the request, when I debug the execute method and I explicitly set values to these attributes everything works fine.
new JsonResult(jsonObj) is a generic class with a constructor that accepts a JSONObject
Like Rory McCrossan Comment it could be the response you got is not a json and your code expect a json response
When i comment dataType param it work fine
$.ajax({
type : "POST",
url : "getInfos.html",
//dataType : "json",
async: false,
cache: false,
data: JSON.stringify({
Code : "code1",
type : "type",
mand : "mand",
signature : "signature"}),
success : function(data){
console.log('succes');
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log('my error is : ' + errorThrown);
}
});
The problem had been solved, after debugging, the response type was not a JSON since there is a redirection to an error page if an exception is thrown, the exception was thrown because the data attributes were null, and it turned out that they are parametres not attributes, so getting the parameters solved the problem.
request.getParameter("code");
thank you all for your collaboration.

Jquery throws an 'Illegal invocation' error

I'm trying to create a forum and jquery throws an 'illegal invocation' error.
Here is my jquery code:
$('#formSumbit').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'data-get.php',
type: 'POST',
data: new FormData(this),
contentType: false,
dataType: 'json',
success: function(value) {
var serialize = $.parseJSON(value);
if (serialize.success == 'false') {
$('.alert').fadeIn().delay(3000).fadeOut();
$('.alert-msgText').html(serialize.datamsg);
}
}
});
});
And here is my PHP code:
<?php
$user = $_POST['user'];
$msg = $_POST['message'];
if(empty($user)&&empty($message)) {
$data = array(
'success' => 'false',
'datamsg' => 'Please fill the textboxes'
);
echo json_encode($data);
} else {
mysqli_query($con,"INSERT INTO forums(name,message) VALUES ('$user','$msg')");
$data = array(
'success' => 'true',
'datamsg' => 'Done!'
);
echo json_encode($data);
}
exit();
?>
When the textboxes are empty and i click the submit button, nothing seems to work and jquery throws an illegal invocation error. I don't understand what the problem is. Can you please help?
And thanks in advance!
1) You have a typo mismatch between your form and your JavaScript:
<form id="formSubmit" and $('#formSumbit') - it should be $('#formSubmit') to match the spellings.
2) Unless you are trying to upload files via this AJAX request, then you can simplify things by replacing data: new FormData(this), contentType: false, with just data: $(this).serialize(). This will get rid of the illegal invocation error.
3) Writing dataType: 'json' means that jQuery will automatically try to parse the data coming from the server as JSON, and convert it. Therefore, in your "success" function, value will already be parsed and converted to an object. In turn therefore, using $.parseJSON is not necessary. You can just access value.success directly, for instance.
Here's a fixed version:
$('#formSubmit').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: 'data-get.php',
type: 'POST',
data: $(this).serialize(),
dataType: 'json',
success: function(value) {
if (value.success == 'false') {
$('.alert').fadeIn().delay(3000).fadeOut();
$('.alert-msgText').html(value.datamsg);
}
}
});
});
Working demo: https://jsfiddle.net/khp5rs9m/2/ (In the demo I changed your URL for a fake one, just so it would get a response, but you can see where I have altered it and left your settings in the commented-out part).

ajax response data is undefined

i have problem with ajax post submit
here is my script
function postad(actionurl) {
if (requestRunning) return false ;
if (! $("#editadform").valid()) {
validator.focusInvalid();
return false ;
}
$('#ajxsave').show() ;
requestRunning = true ;
var postData = $('#editadform').serializeArray();
$.ajax(
{
url : actionurl,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$('#diverrors').html(data.errors) ;
$('#divalerts').html(data.alerts) ;
if (data.status=='success') { alert(data.status);
$('#siteid').val(data.siteid) ;
if ($('#adimager').val())
$('#divlmsg').html(data.alertimage) ;
$('#editadform').submit() ;
} else {
$('#ajxsave').hide() ;
}
},
error: function(jqXHR, textStatus, errorThrown)
{
$('#ajxsave').hide() ;
},
complete: function() {
requestRunning = false;
}
});
$('.btn').blur() // remove focus
return false ;
}
This works on if (textStatus=='success') {
but when the action fails, alert(data.status) shows Undefined.
Using FireBug, I can see that the data is correctly returned. Why is data.status "Undefined" then?
If you don't specify the dataType field of an $.ajax() call in jQuery, it formats the response as plain text. A workaround to your code would be to either include dataType: "JSON" into your $.ajax() parameters, or alternatively, in your success function, parse the plain text response as a JSON object, by using the folllowing:
data = JSON.parse(data); // You can now access the different fields of your JSON object
UPDATE:
yes i have not status field in action url, how to add data status field in php code?
When creating your PHP script that is intended to return the JSON data, you first need to build an array and then encode it as JSON.
So, suppose you have a PHP script that either succeeds and produces some data that you put into a $data variable, or fails, then the following style could be adopted:
<?php
// ^^ Do your PHP processing here
if($success) { // Your PHP script was successful?
$response = array("status" => "success!", "response" => $data);
echo json_encode($response);
}
else {
$reponse = array("status" => "fail", "message" => "something went wrong...");
echo json_encode($response);
}
?>

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).

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

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.

Categories

Resources