Unexpected token for ajax request - ajax

I am using json with jquery's ajax. There are two options for results in this code:
one of them null result
one of them is html result for example ...
When I used firefox this code result not enter if(sdata!="") or sdata!=null
If I try to return with json type it's return, but I don't return html token. It returns an exception
unexcepted token <
How can I solve?
$.ajax({
url: '#Url.Action("RefreshPage", "VeriAktarim")',
type: "POST",
data: { key: id },
success: function (sdata) {
if (sdata != "") {
$("#" + change).closest("tr").replaceWith(sdata);
}
},
error: function (req, status, error) {
alert(status + "error" + error);
}
});

Related

Combine AJAX and API calls

I am working with APIs. My logic is 1st add a grade (POST), 2nd get the gradeID (GET), 3rd add grades to students (PUT). My problem is that I have to use the gradeID in the API call to add the grades.
How do I do using AJAX to get the result from one call and then pass to another call?
here is my ajax:
$.ajax({
type: 'post',
url: "doRequest.php",
data: postData,
success: function(data) {
var output = {};
if(data == '') {
output.response = 'Success!';
} else {
try {
output = jQuery.parseJSON(data);
} catch(e) {
output = "Unexpected non-JSON response from the server: " + data;
}
}
$('#statusField').val(output.statusCode);
$('#responseField').val(format(output.response));
$("#responseField").removeClass('hidden');
$("#responseFieldLabel").removeClass('hidden');
},
error: function(jqXHR, textStatus, errorThrown) {
$('#errorField1').removeClass('hidden');
$("#errorField2").innerHTML = jqXHR.responseText;
}
});
}
Is there a way tho have an ajax inside of other?

How to get(handle) Error (Not Acceptable & Internal Server Error) Exception content in Ajax

I added internal Error (throw exception) in server side. Now I want to handle this error in client side. However , I get error content undefined.
I am using Postman , and see my response is JSON format, it has response parameter like "Message". I tried to parse JSON , and again I got Cannot read property 'Message' of undefined
Ajax function defined like this:
function Ajax(url, method, json, successFunction, errorFunction, skipErrorDlg) {
$.ajax({
url: url,
data: json,
type: method,
contentType: 'application/json',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', GlobalAuthToken);
},
processData: false,
dataType: 'json',
success: function (data) {
successFunction(data);
},
error: function(event, jqxhr, settings, thrownError) {
if (errorFunction != null) {
errorFunction();
}
}
});
}
I used this function in my code , error part like this, In this function how can I get exception content?
function(event, jqxhr, settings, thrownError)
{
alert("ERROR HAPPENED");
var responseString = JSON.stringify(event);
alert(responseString.Message);
alert("event" + event.Message);
},
Postman Result:
{
"Message": "Please select corresponding template."}
Expected Result should be : Please select corresponding template.
I solved the problem, if you face this kind problem , trying like this:
function showAjaxError(event, jqxhr, settings, thrownError) {
var msg = "";
if (event.hasOwnProperty('responseJSON')) {
var resp = event['responseJSON'];
msg = (resp && resp.hasOwnProperty('Message')) ? resp.Message : "";
msg = msg + ((resp && resp.hasOwnProperty('ExceptionMessage')) ? "\n\n" + resp.ExceptionMessage : "");
if (resp && resp.hasOwnProperty('InnerException')) {
msg = msg + ((resp && resp.InnerException.hasOwnProperty('ExceptionMessage')) ? "\n\n" + resp.InnerException.ExceptionMessage : "");
}
} else {
msg = event.responseText;
}
}

Ajax - Parse oData Response

I have an ajax call that gets data from a REST api.
$.ajax({
url: "http://localhost:52139/odata/WEB_V_CIVIC_ADDRESS",
data: { enteredText: "'" + $('#addressTextField').val() + "'" },
type: "GET",
dataType: 'json',
ContentType: "application/json",
success: function (data) {
alert(JSON.stringify(data));
response($.map(data.accountaddressList, function (item) {
return {
item: item.civicaddress,
value: item.accountNumber,
label: item.civicaddress
}
}));
},
error: function (data, xml, errorThrown) {
alert('Error loading address list: ' + errorThrown);
}
});
The odata returned from that call looks like:
{
"#odata.context":"http://localhost:52139/odata/$metadata#WEB_V_CIVIC_ADDRESS/AValues.Classes.Entities.AccountAddress","value":[
{
"#odata.type":"#AValues.Classes.Entities.AccountAddress","accountNumber":88887,"rowNumber":0,"civicaddress":"123 Fake St"
},{
"#odata.type":"#AValues.Classes.Entities.AccountAddress","accountNumber":88888,"rowNumber":0,"civicaddress":"321 Faker St"
}
]
}
So the current code throws an 'Undefined' error on the line: response($.map(data.accountaddressList, function (item) {
How do I map the 'civicaddress' and 'accountNumber' from each value in the odata response to 'item'?
Thanks.
I got it, needed to change it to response($.map(data.value, function (item)

WebKitFormBoundary header on file ulpoad

To avoid sharing a third-service api token, I want to upload my files trough my node server.
To do this, I've my webpage sending my files in ajax to my node server which is sending them to the 3rd party api.
so :
client > ajax > node > api
My file succeed to arrive on the third party service but with WebKitFormBoundary header and footer.
------WebKitFormBoundaryBvPXh46XrNOYDFJn
Content-Disposition: form-data; name="file"; filename="Screen Shot 2014-11-20 at 15.01.45.png"
Content-Type: image/png
<< file bytes >>
------WebKitFormBoundaryBvPXh46XrNOYDFJn--
Ajax code :
$.uploadFiles = function(file){
var data = new FormData();
data.append('file', file, file.name);
console.log(data);
$.ajax({
//url: 'https://slack.com/api/files.upload?token=xoxp-2964595734-2964595740-3128685143-b1796a&channels='+settings.joinedChannel+'&pretty=1',
url: '/app/fileUpload?token='+settings.token+'&channel='+settings.joinedChannel,
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR)
{
if(typeof data.error === 'undefined')
{
// Success so call function to process the form
//submitForm(event, data);
console.log(data);
}
else
{
// Handle errors here
console.log('ERRORS: ' + data.error);
}
},
error: function(jqXHR, textStatus, errorThrown)
{
// Handle errors here
console.log('ERRORS: ' + textStatus);
// STOP LOADING SPINNER
}
});
};
Node code
app.post('/app/fileUpload', isAuthorized, function(req, res, next) {
var token = req.param('token');
var channel = req.param('channel');
var req = req;
models.app.find({ where: { token: token, active: true } }).success(function(application) {
slack.uploadFile(application.slack_api_token,channel,req);
return res.status(200).json({ success: true, message: "Uploading" });
});
});
[....]
uploadFile: function uploadFile(applicationToken,channel,file) {
var formData = {
// Pass a simple key-value pair
token: applicationToken,
// Pass a simple key-value pair
channels: channel,
// Pass data via Streams
file: file
};
request.post('https://slack.com/api/files.upload?pretty=1', { formData: formData }, function (error, response, body) {
if (!error && response.statusCode == 200 && typeof body.ok !== "undefined" && body.ok == true) {
console.log("OK");
//console.log(body);
} else {
console.log("Not OK");
//console.log(response);
}
});
},
FIXED : with formidable and this code to manage the file stream :
file: {
value: fs.createReadStream(stream.file.path),
options: {
filename: stream.file.name,
contentType: stream.file.type
}
}

Facebook wall post using ajax post request inconsistent with Chrome and IE

I am using the posted code for posting content to a Facebook wall.
FB.init({ appId: 'my app id', status: true, cookie: true, xfbml: true, oauth: true })
$('#share_button').click(function (e) {
if ($('#textfield').val() != 'Whats Happening' && $('#textfield').val() != '') {
var lin = window.location.href;
FB.login(function (response) {
if (response.authResponse) {
console.log("User is connected to the application.");
var accessToken = response.authResponse.accessToken;
var fbURL = "https://graph.facebook.com/me/feed?access_token=" + accessToken;
$.ajax({
url: fbURL,
data: "message=" + $('#textfield').val() + "&picture=MyUrl/images/logo.png&name=FutureZoom&link=MyUrl",
type: 'POST',
success: function (resp) {
$('#ValidationMessage').html(' Post has been shared on your wall!')
.css('color', 'green');
setTimeout(function () {
$('#ValidationMessage').html('');
}, 3000);
},
error: function (request, status, error) {
alert("Facebook Error : \n" + request.responseText + '\n' + status + '\n' + error);
}
});
}
}, { scope: 'publish_stream' });
}
else {
$('#ValidationMessage').html(' Please write something to share!')
.addClass('red');
}
});
Above is working fine in Firefox browser but problem is with IE and Chrome.
In Chrome, above code posts the comment on wall but when returns, it goes into error block instead of success. Below is the error getting in chrome.
Facebook Error:
{
"id": "100002506055900_30229318964214"
}
parseerror
SyntaxError: Unexpected token:
And in IE, nothing happens. Neither posts the comment nor returns in error/success block.
What could be reason?
Instead of doing a AJAX call to post something to the user's timeline, you should use the FB.api function in the Facebook JavaScript SDK instead. It simplifies the process:
FB.api('/me/feed', 'post', { message: body, picture: pic }, function(response) {
if ( !response || response.error ) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
You can see the documentation for the JS call here: http://developers.facebook.com/docs/reference/javascript/FB.api/
You will be able to reduce your code quite a bit by using this method.

Resources