Jquery ajax unload page error on chrome - javascript

Only event unload page call function ajax this die
$( window ).on('unload',function(e) {
e.preventDefault();
ajax_delete_support_models(12);
});
-ajax run
function ajax_delete_support_models(sm_id){
var token = getTokenFromBrown();
var data_submit = {'csrfmiddlewaretoken':token,'sm_id':sm_id}
var ajax_data = $.ajax({
type: "POST",
url: 'http://localhost/delete-support-models/',
data :data_submit,
async : false,
error: function (request, status, error) {
console.log(request);
},
success: function(data){
console.log('ok success')
}
});
}
-- debug this
code: 19
message: "A network error occurred."
name: "NetworkError"
I using jquery ajax unload page error please help me

This is a bug in Chrome:
https://code.google.com/p/chromium/issues/detail?id=321241
More discussion here: http://productforums.google.com/forum/#!topic/chrome/5b3ePr9rMVQ

Related

Why does my jQuery getJSON call (within Office.js (Excel js add-in)) return an error?

This javascript within an Office js add-in always fails when making a get request:
function update() {
Excel.run(function (ctx) {
return ctx.sync()
.then(function () {
var company = $('#company').val();
var environment = $('#environment').val();
var apiUrl = "https://localhost:44321/api/Country";
var params = "company=" + company + "&environment=" + environment;
$.getJSON(apiUrl, params)
.done(function (result) {
showNotification(result.length);
})
.fail(function (xhr, status, error) {
//showNotification(error.statusText);
showNotification(error.length);
});
});
}).catch(function (error) {
showNotification(error);
});
}
I can see the json being returned successfully within Fiddler and JSONLint says the json is valid. Here it is:
[{"country":"UK","countryLongName":"United Kingdom","currency":"GBP"}]
I'm running on localhost with https, and have the following AppDomains in my manifest (belt and braces):
<AppDomain>https://localhost:44321/api/Country</AppDomain>
<AppDomain>https://localhost:44321</AppDomain>
<AppDomain>https://localhost</AppDomain>
However, getJSON.fail() is always invoked, with the following parameters:
xhr.responseJSON: undefined
xhr.statusText: "error"
status: "error"
error: ""
Why does getJSON always fail?
Further edit
I've tried this js instead...
$.ajax({
url: apiUrl,
dataType: 'json',
async: false,
data: params,
success: function (data) {
showNotification(data);
},
error: function (msg) {
showNotification('error : ' + msg.d);
}
});
...and now the error function is being invoked with the following parameters:
msg.responseJSON: undefined
msg.status: 0
msg.statusText: "NetworkError"
It's all to do with CORS, I found the solution in rick-strahl's post:
https://weblog.west-wind.com/posts/2016/Sep/26/ASPNET-Core-and-CORS-Gotchas#ApplythePolicy
Specifically,
"UseCors() has to be called before UseMvc()
Make sure you declare the CORS functionality before MVC so the middleware fires before the MVC pipeline gets control and terminates the request."

AJAX request not executing inside chrome alarm

I am fairly new to AJAX and recently I've implemented chrome alarm in my background script. Here is my background.js :
chrome.alarms.onAlarm.addListener(function(alarm) {
alert("Begin");
$.ajax({
type: "GET",
url: "myURLhere",
datatype : 'jsonp',
crossDomain: true,
success: function(res)
{
alert('Success1');
},
error: function() {
alert("Error occurs!");
}
});
alert("We're done");})
So the problem is that, without the alarm my ajax request was executing successfully but now its never going into the success part. I always get 3 alerts (Begin,Error occurs! and We're done) and I have been wondering why since past few days.
Here is my popup.js file where the alarms are being set.
var alarmClock = {
onHandler : function(e) {
chrome.alarms.create("myAlarm", {delayInMinutes: 0, periodInMinutes: 2} );
window.close();
},
offHandler : function(e) {
chrome.alarms.clear("myAlarm");
window.close();
},
setup: function() {
var a = document.getElementById('alarmOn');
a.addEventListener('click', alarmClock.onHandler );
var a = document.getElementById('alarmOff');
a.addEventListener('click', alarmClock.offHandler );
}}; document.addEventListener('DOMContentLoaded', function () { alarmClock.setup(); });
Thanks in advance :)

Getting Uncaught SyntaxError: Unexpected token : when reading jsonp response

I am working on a piece of code where the user clicks on a button to make a call and the status of the call is displayed to him/her.
Everything is working fine and the calls are being made too, but the server which sends the json response is on another domain and I have no control over its response. I therefore used jsonp to get the response, but no matter what i did, i keep getting the error of Uncaught SyntaxError: Unexpected token.
I am attaching my code. please help as this is a live project and I am badly stuck in it. I need a response to be alerted with the message received by the server. the message received by the server in case of success is {"success": {"status": "success", "message": "Call successfully placed"}} and in case of error is {"error": {"message": "Invalid API Key"}}. I just need to display the message part.
my code:
function makecall() {
document.getElementById('<%=click2call_submitbtn.ClientID%>').disabled = true;
var agentNum = document.getElementById('<%=lblCallFrom.ClientID%>').innerHTML;
var custNum = "+91";
custNum = custNum + document.getElementById('<%=txtNotoCall.ClientID%>').value;
document.getElementById('<%=lblCallStatus.ClientID%>').innerHTML = "Calling...";
if (validatePhone(agentNum) && validatePhone(custNum)) {
$.ajax({
url: 'http://www.knowlarity.com/vr/api/click2call/?api_key=9e69eab0-1ec7-11e3-866c-16829204aaa4&agent_number=agent_number_variable&phone_number=Caller_number_variable&sr_number=%2B918881692001&response_format=json'.replace('Caller_number_variable', custNum.replace('+', '%2B')).replace('agent_number_variable', agentNum.replace('+', '%2B')),
type: 'GET',
cache: false,
dataType: 'jsonp',
success: function (res) {
alert(JSON.stringify(res));
},
error: function (res) {
alert(JSON.stringify(res));
}
});
} else {
document.getElementById('<%=lblCallStatus.ClientID%>').innerHTML = "Num. should be a valid 10 digit mobile no.";
document.getElementById('<%=click2call_submitbtn.ClientID%>').disabled = false;
}
}
Try using this as an absolute minimum where you can pass in valid hard wired values for the numbers:
var url = 'http://ip.jsontest.com/ ';
$.ajax({
url: url,
cache: false,
dataType: 'jsonp',
success: function (res) {
if (res != undefined) console.log(res);
},
error: function (res) {
if (res != undefined) console.log(res);
}
});

ajax post error: NETWORK_ERR: XMLHttpRequest Exception 101 on android device

I have the following ajax post:
$.ajax({
type: "POST",
url: "http://sampleurl",
data: {
'email':$('#email').val(),
'password':$('#password').val(),
},
cache: false,
async: false,
crossDomain: "true",
beforeSend: function() { },
complete: function() { },
success: function(resp) {
alert(resp);
var result = $.parseJSON(resp);
if (result.result == "Success") {
alert(emailID,password);
}
else {
alert(result.msg);
}
},
error: function(request, status, error) {
//$("#LoadingImage").hide();
alert("Result = " + error);
}
});
return false;
});
It is returning with this error: NETWORK_ERR: XMLHttpRequest Exception 101 on android tablet.
I have read a bunch of SO posts on this error, most suggest that I set async to true. This DOES remove the error message- but it is still an error, and I never get valid data. It just seems to remove the error message which is not helpful.
Please help me.
Finally i got solution.. Android 4.1 and 4.2 introduce this new method: getAllowUniversalAccessFromFileURLs
Since it's not working on API below 16 the solution needs some few more lines, to assure that this inexistent method do not cause errors in previous API.
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN){
fixNewAndroid(webView);
}
#TargetApi(16)
protected void fixNewAndroid(WebView webView) {
try {
webView.getSettings().setAllowUniversalAccessFromFileURLs(true);
} catch(NullPointerException e) {
}
try use location in your domain , like ./directory/yourfile.php
I have this problem in IE7

How to handle response of a POST request in jQuery

I am trying to POST some data to my ASP.Net MVC Web API controller and trying to get it back in the response. I have the following script for the post:
$('#recordUser').click(function () {
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: $("#recordUserForm").serialize(),
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
//...
}
}
});
});
The problem with this script is that whenever I try to post the data, the jQuery comes back in "error" instead of "success".
I have made sure that there is no problem with my controller. I can get into my api method in debug mode whenever the request is made and can see that it is getting the data from the POST request and is returning it back. This controller is quite simple:
public class RecordUserController : ApiController
{
public RecordUserEmailDTO Post(RecordUserEmailDTO userEmail)
{
return userEmail;
}
}
I am not sure how I can get jQuery to print out any useful error messages. Currently when I try to debug the jQuery code using Chrome console it shows an empty xhr.responseText, nothing in "err" object and "status" set to "error" which as you see is not quite helpful.
One more thing that I have tried is to run the following code directly from the console:
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: {"Email":"email#address.com"},
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
console.log(xhr);
console.log(err);
console.log(status);
alert(err.Message);
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
}
}
});
i.e. using the same script without actually clicking on the button and submitting the form. Surprisingly, this comes back with the right response and I can see my data printed out in console. For me this atleast means that my Web API controller is working fine but leaves me with no clue as to why it is not working on clicking the button or submitting the form and goes into "error" instead of "success".
I have failed to find any errors in my approach and would be glad if someone could help me in getting a response back when the form is posted.
As suggested by Alnitak, I was using complete callback along with success and error ones. Removing complete from my code fixed the issue.
Thanks to Alnitak.

Categories