I have a method delete ajax call to remove a field from table, but on click my console shows this error
and i get same error for my another post method ajax. And both works perfectly on my localhost and not on server. this is my ajax code,
function delSubTask(sid,id){
var place = 'sub-'+sid;
var badge = 'badge-'+id;
var count = document.getElementById(badge).innerHTML;
count--;
$.ajax({
type: "DELETE",
url: "/myurl/"+sid,
data: {id:id},
success: function(data) {
console.log(data);
var e = document.getElementById(place);
$(e).fadeOut( "slow", function() {
// After animation completed:
$(e).remove();
});
document.getElementById(badge).innerHTML=count;
},
error: function(){
alert('Failed to delete #errsub25');
$('input:checkbox').removeAttr('checked');
}
});
}
It is hard to say because there are many reasons to cause HTTP 500 internal error. Mostly, it about your service on the server.
In my experience, it might because of CORS (more explanation here https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) because moving from localhost to actual server usually has this problem.
Or you might give more information about what is the response (or debug by yourself).
Related
I have tried this as an answer from my previous question, but it does not work it just reports 500 Internal Server Error and Firebug does not report any details of the error:
(function worker() {
$.ajax({
url: 'buildmarkers.inc.php',
type: 'POST',
success: function(data) {
$('.result').html(data);
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 30000);
}
});
})();
when I try it like this it is working:
<?php include('buildmarkers.inc.php')?>
Your real question is, "Why am I getting a 500 error." and the answer to that can't be determined without the code for buildmarkers.inc.php. You aren't seeing anything in firebug because it's a server side error. If you modify your javascript and add an error function, you'll see it fail on the client.
(function worker() {
$.ajax({
url: 'buildmarkers.inc.php',
type: 'POST',
success: function(data) {
$('.result').html(data);
},
error: function(data){
console.log("Save me Tom Cruise! The server is on fire!");
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 30000);
}
});
})();
Ajax call will get the file with relative path of URI (based on DOCUMENT_ROOT or webserver), it might be different with include() in PHP that uses absolute path of current script file. You might:
Check the folder structure of your project, is there any difference between your script path and "buildmarkers.inc.php"'s one?
Does it have any rewrite rule on you webserver?
You should check the error log of your webserver, it should show helpful messages.
when i try to click the share button i get Failed to load resource: the server responded with a status of 500 (Internal Server Error) in the console and alert says Ajax request has encountered an error knowing that this doesn't happened on staging just on production and on safari or firefox.
I spent hours trying to figure it out
here is my code
$(document).on("click",".btn-share-generate-js",function(e) {
var url = $(this).data("share-url");
var id = $(this).data("id");
var message = $("input:radio.vt:checked").val();
var clickedBtn = $(this);
clickedBtn.find(".icon-link").addClass('hide');
clickedBtn.find(".icon-arrows-cw").removeClass('hide');
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: {
'share[message]': message
},
success: function(data) {
clickedBtn.find(".icon-link").removeClass('hide');
clickedBtn.find(".icon-arrows-cw").addClass('hide');
if (data.error == true) {
alert(data.error_message);
} else {
replaceShareButtonWith(data.share_url);
}
},
error: function(){
clickedBtn.find(".icon-link").removeClass('hide');
clickedBtn.find(".icon-arrows-cw").addClass('hide');
alert("Ajax request has encountered an error.")
},
});
return false;
});
$(document).on("click",".social-media-reshare-btn",function(e) {
var url = $(this).attr("href");
window.open(url, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=245,width=550');
return false;
});
thanks
If your server responds with a 500 error, the only reason is that you are sending a slightly different request causing the server-side misbehave. You should open the developer console (of Safari and/or Firefox), switch to the Network tab, and retry the action. Now you can inspect the entire outgoing request to see how it is different from the browsers that work fine.
Once you have the root cause of the problem, you can decide either
the client is sending something wrong: so now you determine how to fix the above code
the server should not fail given this slightly different incoming request: so you should fix the server code
before I explain my issue I would like to mention that I'm a naive on jsonp. This is actually my very first attempt to work with JSONP.
Im using jquery ajax call to pullback data from a website.
my jquery code is below
$.fn.checkTPS = function(){
return this.each(function(){
var interval;
$(this).on('keyup', function() {
var api_key = 'asdfasfsadfsadfsad';
var format = 'json';
var username = 'dame#example.co.uk';
var self = $(this);
var selfValue;
var feedback = $('.tps-feedback');
if(interval === undefined){
interval = setInterval(function(){
if(selfValue !== self.val()) {
selfValue = self.val();
if (selfValue.length > 9){
$.ajax({
url: 'https://www.selectabase.co.uk/api/v1/tps/' + selfValue + '/',
type: 'get',
dataType: 'jsonp',
data: {
format: format,
username: username,
api_key: api_key
},
success: function(data) {
console.log(data);
},
error: function() {
},
jsonp: 'jsonp'
});
}
}
},3000);
}
});
});
};
I want to accommodate a service from selectabase.co.uk, according to them this is how I should use the service https://www.selectabase.co.uk/api/v1/tps/[number]/?format=json&username=[username]&api_key=[api key]
when I send request using ajax I get this error Uncaught SyntaxError: Unexpected token : and when clicked this opens up
{"ctps": false, "number": "1452500705", "resource_uri": "/api/v1/tps/01452500705/", "tps": false} by the way this I want but don't know what's this error is unexpected token :
I've copied the following link from inspect element tab (you can see the image below) I think this is the call that has been generated by json https://www.selectabase.co.uk/api/v1/tps/01452500705/?jsonp=jQuery17102731868715648129_14120077325500&format=json&username=dame40example.co.uk&api_key=asdfasfsadfsadfsad&_=14120077325500
I copied the link below from inspect element > source tab in chrome.. I think I should add an image to describe properly where this json data and link I've copied from.
I hope I've manage to convey my message across... please help if you have any Idea what do i need to add... Regards
The format=json in your query string should probably be format=jsonp. The server is replying with JSON, but you're expecting a JSONP response. But I don't know that they support format=jsonp, it's just a guess.
Alternately, if that server supports CORS and allows requests from your origin, you could handle JSON instead (just remove dataType: "json" from your ajax call). Beware that that would require that the user be using a browser that properly supports CORS, which IE8 and IE9 don't. (They support CORS, but not via the normal XMLHttpRequest object, and this is a browser inconsistency that jQuery doesn't smooth over for you. If you search, though, you can find "plugins" or similar that will handle it.)
I have a web application written in ASP.NET MVC 4. Client side richly uses JQuery to perform requests to save and retrieve data, during the user experience. In certain moments the user can change some data and click a button-like link to save it. For architecture/performance/requirements restrictions, this process is made in two steps:
A POST request is sent to the server to a given URL (which will fire a certain action of a certain controller), containing a JSON object;
On the first POST success a timer is set to run a second POST to the same server, but different URL (another action in the same controller), with no content at all.
The second POST will just start a complementary process and conclude what was started by the first one. However, it never gets the server. The $.ajax method fires the error handler.
A simplified version of the first request code is
$.ajax({
url: self.opcoes.urlCreate,
type: "POST",
data: JSON.stringify(lancamento),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
self.LancarDia(250);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Não foi possível incluir o lançamento. O servidor retornou\n" +
ajaxErrorMessage(jqXHR, textStatus, errorThrown));
}
});
The method LancarDia() receives the miliseconds amount to set the timer for the second request, so the idea is to wait 250 miliseconds and then send the second request. The LancarDia() code is:
MyClass.prototype.LancarDia = function (milisegundos) {
var self = this;
if (milisegundos) {
if (self.timerLancarDia)
clearTimeout(self.timerLancarDia);
self.timerLancarDia = setTimeout(function () {
self.LancarDia();
self.timerLancarDia = undefined;
}, milisegundos);
return;
}
$.ajax({
url: self.opcoes.urlLancarDia + self._dataAtual.format("MM/dd/yyyy"),
type: "POST",
success: function (data) {
if (self.opcoes.onLancou)
self.opcoes.onLancou(self._dataAtual);
},
error: function (jqXHR, textStatus, errorThrown) {
var mensagem = "Não foi possível atualizar o MUMPS. Motivo:\n" +
ajaxErrorMessage(jqXHR, textStatus, errorThrown);
alert(mensagem);
}
});
}
Notice that the first POST always work and the second fails many times but not always. When it fails what I get is:
jqXHR.status == 0
jqXHR.readystate == 0
textStatus == "error"
errorThrown == ""
In its first version, the code didn´t use any timers. On the success of the first POST the second was immediatly sent. Changing to the current implementation was reported to reduce the frequency of the problem, but it still happens.
Only Chrome shows this problem, FireFox and IE run clean.
Have anyone faced and solved this problem?
Thanks in advance
You mention the second POST never gets sent to the server, how are you verifying this? It sounds more like a race condition where the second request is being sent before the server is ready for it (e.g. it is still doing something that was started by the first request).
After a long study, our infrastructure staff figured out that the problem was caused by the caching policy of the browser (Chrome) and the caching policy configured in the web server (IIS 7).
After configuring IIS to add no-cache in the cache-control response header, the problem disapeared.
I am sending lots of data using jquery ajax method to web sever and client side respond only after receiving acknowledgment from server, now suppose network connection lost in MIDDLE of ajax call then how to detect this situation.
$.ajax({
url:'server.php',
data:'lots of data from 200KB to 5MB',
type:'post',
success: function(data)
{
alert('Success');
//some stuff on success
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Failure');
//some stuff on failure
}
});
This is my code and and it does not give error in middle of ajax call if get internet is disconnected.
NOTE : I cant use time out because data size is vary from 200kb to 5MB and server response time calculation is not feasible.
Try this:
First create a "ping" ajax call with setInterval every 5 seconds
function server_ping()
{
$.ajax({
url:"url to ping",
type: "POST"
});
}
var validateSession = setInterval(server_ping, 5000);
then arm your .ajaxError trap:
$(document).ajaxError(function( event, request, settings ) {
//When XHR Status code is 0 there is no connection with the server
if (request.status == 0){
alert("Communication with the server is lost!");
}
});
Remember Ajax calls are Asynchronous by default, so when the pings are going to the server and the request cannot reach the server the value on the XHR status is 0, and the .ajaxError will fire and you must catch the error and handle the way you want it.
Then you can send your data to the server, if the connection is lost when sending the data you get the error reported by the ping.
If your server was not very crowded, probably you could use a timer to start detecting the connection regularly when you start transferring the data (by using another ajax calling, for instance each 5 seconds). now you can use timeout.
Btw,
1)timeout doesn't always means network error. sometimes server's down also causes "timeout"
2)if the driver is down on client device, xhr.status = 0, and no timeout
I had a similar problem and solved it with a simpel try/catch and a re-try delay of (say) 2 seconds:
function myAjaxMethod()
{
try
{
$.ajax({ ... });
} catch (err)
{
console.log(err.message);
setTimeout(function(){myAjaxMethod(),2000});
}
}
I faced a similar situation like yours and fixed it by having a network check for every 5 seconds and if network is disconnected i would abort the ajax request manually which will end the ajax request.
Here i get the ajax XmlHttpRequest in the beforeSend event of the Jquery ajax call and use that object to abort the ajax request in case of network failure.
var interval = null;
var xhr = null;
$.ajax({
beforeSend: function(jqXHR, settings) {
xhr = jqXHR; // To get the ajax XmlHttpRequest
},
url:'server.php',
data:'lots of data from 200KB to 5MB',
type:'post',
success: function(data)
{
alert('Success');
//some stuff on success
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Failure');
//some stuff on failure
},
complete: function(data)
{
alert('Complete');
//To clear the interval on Complete
clearInterval(interval);
},
});
interval = setInterval(function() {
var isOnLine = navigator.onLine;
if (isOnLine) {
// online
} else {
xhr.abort();
}
}, 5000);
Try adding timeout: while constructing your $.ajax({}).
Also make sure to set cache: false, helpful sometimes.
Refer to Jquery's ajax() : http://api.jquery.com/jQuery.ajax/#toptions
You will get much more information there!
My thought s on your problem[updated]
#RiteshChandora , I understand your concern here. How ever I can suggest you to do 2 things.
As you have post data ranging from 200kb to 5mb, you might want to choose a maximum timeout. and trigger for the same. Yes, this might be problematic, but with the design you chosen, the only way to monitor the POST progress is to do this way. if not, see point 2.
I went through the flow, you are asking the user to copy the response Json from FB to your url. there are some problems here,
The json data has sensitive information about the user, and he is posting it on a url without SSL encryption.
Why should you prompt the user to post the acquired data on to your server? it should be easier if you user sever side scripts. Also you should never post huge data from the client to the server in occasions like these, where you could retrieve the same form the FBserver->your sevrer on the server side.
My suggested solution : after the user is authenticated , retrieve his friends list on the server side. do whatever you want on the server side, and display the result on the users screen.
This way all the burden will be taken by your server, also there is no need for the user to do any nasty json posting on your url.
Btw, your app idea is cool.
error: function(xhr, textStatus, thrownError)
{
alert(xhr.status);
alert(thrownError);
alert(textStatus);
}
Try them..
TextStatus (besides null) are "timeout", "error", "abort", and "parsererror".
When an HTTP error occurs, thrownError receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error."
If Internet disconnects,the response wont be received and maximum it would be a timeout message..