Requesting a file through Ajax - javascript

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.

Related

Why is res.sendfile() doesn't work when I call from jQuery ajax?

Issue:
The first ajax is working properly in the main.js, the second one is doing its job at first look but I think there might be a bug somewhere. I can reach the getProducts method after I click to the button.
The product_list.html file should appear on the browser screen, but it doesn't.
I get no error message on the front-end or the back-end.
This is what I noticed: After click to the button -> F12 -> Network -> products -> I can see here a status code: 200 and the product_list.html file content as response.
In case the POST ajax call succeeds and in the case I add: location.href = "/products";, the browser will load product_list.html
I use the get ajax call because i need to pass the jwt token in the req header. (I deleted the jwt authentication parts from the code below because I narrowed down the error to the $.ajax() and res.sendFile() relationship)
//routes.js
routes.get("/products", ProductController.getProducts);
//ProductController.js
var root = path.join(__dirname, '../../views');
module.exports = {
getProducts(req, res){
console.log("getProducts!"); //I can see in the console
res.sendFile("product_list.html", {root}) //It doesn't render the html
},
}
//main.js
$("#btn-login").click(function(){
$.ajax({
type: 'POST',
url: "http://localhost:8000/login",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({
"username": $("#login-user").val(),
"password": $("#login-pwd").val(),
}),
success: function(data){
if ($("#login-chkbx").is(':checked')){
$.ajax({
url: "http://localhost:8000/products",
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader("user", localStorage.getItem("user"));
},
});
}
}else{
console.log("Checkbox is not checked");
}
}
});
});
What causes the issue and how to solve it?
Thanks!
file should appear on the browser screen
No it does not and it should not. The file should be returned to the ajax function call in the success callback:
$.ajax({
url: "http://localhost:8000/products",
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader("user", localStorage.getItem("user"));
},
success: function (file) {
// The file is in the "file" variable above.
// Do whatever you want with it. For example you can replace
// the current page with the returned file:
document.body.innerHTML = file;
}
});
That is the whole point of AJAX - a mechanism for programmers to override the normal flow of HTTP requests that loads the response to the browser page. If it allows you to not load the response to the browser page it also means it will not automatically load the response to the browser page - because doing so will not allow you to not load the response.
If you want to automatically load the response then don't use ajax:
// Replace $.ajax(... with:
window.location.href = "http://localhost:8000/products";
However, this method does not allow you to set custom request header.
in your frontend code you do nothing with the GET /products response
the backend sendfile as the name says it just sends the file over to the requester. Being an ajax call, it must be rendered by the frontend code.
Add something like success: response => $('body').html(response)

Ajax- XHR failed loading with internal server error 500

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

High CPU Usage and Synchronous XMLHttpRequest Warning With setInterval() and AJAX

I want to update a shell command output each second using AJAX.
However, Chrome CPU usage is too high and output update seems to be updating so fast ( not one second )
Here is the HTML Document:
<script src='jquery-2.2.4.js'></script>
<script>
setInterval(function() {
$.ajax({
url: "test.php",
success: function(data) {
$("body").html(data);
},
async: true
});
}, 1000);
</script>
</body>
And here is the shell command I'm actually using:
system("dir C:");
It would be better to use a setTimeout which will be called after every successful ajax completion.
You could setup also an error handler in the $.ajax because a network fail might happen and call there again the setTimeout(function(){myajaxfunction();},1000);
var myajaxfunction = function() {
$.ajax({
url: "test.php",
success: function(data) {
$("body").html(data);
setTimeout(function(){myajaxfunction()},1000);
},
async: true
});
};
myajaxfunction();
I found the solution. The AJAX request URL was the same URL I requested from which caused an infinite recursive loop.
So what I did is to request it from another PHP page which contains the data I actually need.

jQuery.jsonp not invoking success callback

I'm using this jQuery plugin to make cross-domain requests to a website. Here's the relevant part of my program:
$.jsonp({
url: "http://soniccenter.org/source/utilities/codebot.php",
data: data, //data is defined
beforeSend: function() {
$('.loading').show();
},
success: function(response) {
$('.output').html(response);
},
error: function() {
$('.output').html("Failed to access TSC. Perhaps the website is down?");
},
complete: function() {
$('.loading').hide();
}
});
}
I can tell the request was successful via my browser's network recorder (200 response code and the text I expect to receive), but the error callback seems to run instead of the success callback because that's what shows up after complete is invoked.
Is this some kind of asynchronous/synchronous problem or...?

Which of the following javascripts long polling code should I use?

I wanted to use long polling.
I google it and found many helpful resources, and since many, I am getting confuse which is better.
Following are three code snippets from two place.
https://gist.github.com/jasdeepkhalsa/4353139
// Long Polling (Recommened Technique - Creates An Open Connection To Server ∴ Fast)
(function poll(){
$.ajax({
url: "server",
success: function(data)
{
//Update your dashboard gauge
salesGauge.setValue(data.value);
},
dataType: "json",
complete: poll,
timeout: 30000
});
})();
// The setTimeout Technique (Not Recommended - No Queues But New AJAX Request Each Time ∴ Slow)
(function poll(){
setTimeout(function(){
$.ajax({
url: "server",
success: function(data)
{
//Update your dashboard gauge
salesGauge.setValue(data.value);
//Setup the next poll recursively
poll();
},
dataType: "json"});
}, 30000);
})();
https://github.com/panique/php-long-polling/blob/master/client/client.js
function getContent(timestamp)
{
var queryString = {'timestamp' : timestamp};
$.ajax(
{
type: 'GET',
url: 'http://127.0.0.1/php-long-polling/server/server.php',
data: queryString,
success: function(data){
// put result data into "obj"
var obj = jQuery.parseJSON(data);
// put the data_from_file into #response
$('#response').html(obj.data_from_file);
// call the function again, this time with the timestamp we just got from server.php
getContent(obj.timestamp);
}
}
);
}
My question is which code is long polling best practice?
Which one should I use?
Thanks in advance.
The first approach is better on my opinion:
If server configured for long polling with timeout more than 30000, then with first one you will have breaking request by timeout and a new request will be sent, success() function would not be called
(while complete() will be, also error could be handled in error() like this
error: function(x, t, m) {
if(t==="timeout") {
alert("got timeout");
} else {
alert(t);
}
}
).
While in the second one a new request would be sent after 30000 and so you would have unpredictable behavior on a client side (two requests can receive the same answer, so data could be duplicated).
If server configured for long polling with less than 30000, then in second approach data on a client side would not be updated in time.
If server configured for long polling with 30000, then it should not be any difference.
To summarize: in first approach situation is controllable, while in second one - not always.

Categories