this is first time I'm facing the issue. I have used AJAX many times.
I'm calling an AJAX to update page content. AJAX call is after each 2 sec. For some Hits it working properly but after that I'm getting following Alert on FIREFOX browser
And this happens only on FIREFOX, I'm not getting such a alert on chore browser
My Code is :
function search_by_location (location_id) {
console.log(location_id);
setInterval(function(){
$.ajax({
type:"POST",
url: "<?php echo BASE_URL.'controller/function'?>",
data:{"key":location_id},
cache:false,
success:function(data){
$("#custom_div").html("");
$("#custom_div").html(data);
search_by_location (location_id);
},
error:function(err){
console.log(err);
}
});
}, 2000);
}
What is the issue ? I think this is because multiple hits and page update. Is it cache related thing ?
The issue is because you're making the AJAX request every 2 seconds, but you're also starting a new timer every time a request completes. Therefore the number of requests you're making grows exponentially. You should remove the search_by_location() call in the success handler:
function search_by_location (location_id) {
setInterval(function() {
$.ajax({
type: "POST",
url: "<?php echo BASE_URL.'controller/function'?>",
data: { key: location_id },
cache: false,
success: function(data){
$("#custom_div").html(data);
},
error: function(err){
console.log(err);
}
});
}, 2000);
}
Also note that a better pattern to follow is to use setTimeout() on the successful completion of a request. This will stop requests from backing up on the client when they take longer to complete than the poll interval:
function search_by_location (location_id) {
$.ajax({
type: "POST",
url: "<?php echo BASE_URL.'controller/function'?>",
data: { key: location_id },
cache: false,
success: function(data){
$("#custom_div").html(data);
},
error: function(err){
console.log(err);
},
complete: function() {
setTimeout(function() {
search_by_location(location_id);
}, 2000);
}
});
}
You may also want to look in to using websockets if you require the client to always have immediate access to up-to-date data. Polling patterns can end up DDoS-ing your own server if you aren't careful.
Related
I'm trying to stop my setInterval() call. The best would be to identify whenever my AJAX request is fulfilled. So, If I got my AJAX GET response, then clearinterval().
$(document).on('submit', '#post-form', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/send',
data: {
room_name: $('#room_name').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
},
success: function(data) {
//alert(data)
}
});
$(document).ready(function com() {
loop = setInterval(function() {
$.ajax({
type: 'GET',
url: "/trafic",
success: function check(response) {
//SOME CODE//
},
error: function(response) {
//SOME CODE//
}
});
}, 1000)
setTimeout(clearInterval(loop), 10000);
})
});
I tried to set a timeout, but it is very imprecise as it may take longer/shorter than the delay. So I would need something like if GET successful {clear interval()}
You need to move the clearInterval() call into the success callback of the AJAX call. You'll also need to move the loop interval higher up in your code so that it can be referenced from the success callback.
I'm also not sure why the loop interval is wrapped in a $(document).ready() call, because you can be assured that the document is ready if it is submitted. Also, the variable loop is awfully ambiguous. Try using the name of the API endpoint instead, like traffic.
Try this code:
$(document).on('submit', '#post-form', function(e) {
e.preventDefault();
const traffic = setInterval(function() {
$.ajax({
type: 'GET',
url: "/trafic",
success: function check(response) {
clearInterval(traffic);
},
error: function(response) {
//SOME CODE//
}
});
}, 1000);
$.ajax({
type: 'POST',
url: '/send',
data: {
room_name: $('#room_name').val(),
csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
},
success: function(data) {
// some code
}
});
});
Can I ask you first why did you use setInterval on this HTTP request ? You are probably using more computation power than you need.
You should probably make the request async (e.g https://petetasker.com/using-async-await-jquerys-ajax)
If you want to wait for an event to appear, you may want to have a look at web sockets (https://www.tutorialspoint.com/websockets/index.htm)
I'm trying to make a GIF-loader, which will be shown as long as my AJAX request is being processed. I'm using the jquery loader plugin.
The problem is, the GIF doesn't move when the browser is busy processing the AJAX request, though it is moving, when setting it to visible for testing purposes.
I've tested it in 3 major browsers.
This is an extract of my code. The real code is, of course, much more complex:
$("#myButton").click(function() {
$.loader({
className: "blue-with-image-2",
content: ''
});
getData();
});
function getData() {
$.ajax({
type: "GET",
url: "https://jsonplaceholder.typicode.com/photos",
success: function(data) {
// do something with data
console.log(data)
$.loader('close'); // close the loader
},
error: function(jqXHR, status, error) {
console.error(status, error);
}
});
}
Here is a fiddle with that example code.
The funny thing is, when testing this particular code in jsFiddle, it does
work. But not my real code, which is almost the same, but just more complex.
Use function 'beforeSend' in ajax call
function getData() {
$.ajax({
type: "GET",
url: "https://jsonplaceholder.typicode.com/photos",
beforeSend: function() {
$('#response').html("<img src='/images/loading.gif' />");
},
success: function(data) {
// do something with data
console.log(data)
$.loader('close'); // close the loader
},
error: function(jqXHR, status, error) {
console.error(status, error);
}
});
hi i am calling a php file using ajax after an interval of time. In my php file i simply echo a text line. But it didnt show me any output after time interval..
here is my ajax code form where i am calling my php file..
<script>
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: {"token": "your_token"}, });
}, 5000);
});
</script>
code inside the process.php file
<?php
echo "hello testing";
?>
You aren't handling the response from php script. You need to get it by success parameter in ajax. Try this:
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: 'x=1&y=2', // data here! use query strings like this or;
// data: { x: '1', y: '2' }
success: function(response) { alert(response); } // alert the response text
// returns 'hello testing'
error: function(){ alert('error while posting data'); }
});
}, 5000);
});
User the success and error function of ajax. for eg
$.ajax ({
url: 'process.php',
type:'post'
data:data1,
success: function (response) {
//alert response here you will get the value hello testing
alert (response);
},
error {
alert ('error');
}
});
You should modify your code to use the response.
<script>
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: {"token": "your_token"},
success:function(str){
$("#YOUR_ELEMENT").html(str);
}
});
}, 5000);
});
Just change your JQuery script to show the response after successful request it can be done with done() or success functions.
<script>
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: { token: "your_token"}}).done(function(msg){
$("#response").append(msg);
};
}, 5000);
});
This will append reponses to #response every 5s when ajax request is successful.
the success block, which handles the data returned from remote script is present in your code. you may need to add something like this .
JS CODE:
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: {"token": "your_token"},
}).done(function( data) {
//data received from remote script
});
}, 5000);
});
Happy Coding :)
Timeout is not the culprit here.
We need to make sure that you have a server where process.php resides and its running fine.
Make sure the path for the file process.php is right. You can use browser's developer tools. When the request is made you will see a new entry under "Network" tab of the developer tools. Exploring it you can get the url at which it the file should be available.
I would suggest using Google Chrome's "postman" extension to test the ajax call before implementing it in your code.
Also you need to have a callback that will run in case of request success or failure. Once you get the string in success response, you can do whatever you intend to do with it.
<script>
$(document).ready(function() {
setTimeout(function() {
$.ajax({
url: 'process.php',
type: 'post',
data: {"token": "your_token"} //removed the comma from last argument
}).done(function(serverResponse) {
alert( "Success: " + serverResponse ); //Will show success alert with concatenated text string if the request is successful
}).fail(function(serverResponse) {
alert( "Error: " + serverResponse.message); //Will show error alert with concatenated error message
});
}, 5000);
});
</script>
the php page sends the string "hello testing", and you have to manage it.
take a look here for an example: click me
I am having an issue with IE related to jQuery and ajax. Chrome and Firefox work just fine, but my ajax calls are disappearing in IE.
After making the ajax call, neither the success nor the fail functions are being called. I can see the response in the IE console, and I know my controller action is being hit.
$.ajax({
url: controllerUrl
type: 'POST',
dataType: 'json',
cache: false,
data: {
id: customerId
},
success: function () {
alert('success!');
},
error: function () {
alert('failed!');
}
});
Has anyone else seen this issue?
fail: function () {
alert('failed!');
}
fail is not a valid jQuery ajax setting. I believe you are looking for error.
Also, cache: false, does nothing with POST requests.
Note, jQuery does not append the time stamp with POST requests.
The source code clearly demonstrates this. (summarized from https://github.com/jquery/jquery/blob/master/src/ajax.js)
var rnoContent = /^(?:GET|HEAD)$/;
s.hasContent = !rnoContent.test( s.type );
if ( !s.hasContent ) {
/* code to append time stamp */
}
You are missing a comma , after your URL parameter:
$.ajax({
url: controllerUrl, // <--- you were missing this comma!
type: 'POST',
dataType: 'json',
cache: false,
data: {
id: customerId
},
success: function () {
alert('success!');
},
error: function () {
alert('failed!');
}
});
I editted my ajax data but it still shows the old version while I am sure I saved it I even reopened the file and checked the location. It's like it is cached.
This is the actual code:
function setMessages(roomId, username, message){
$.ajax({
type: "get",
url: "http://www.sinansamet.nl/chatdistract/ajax/setMessages.php",
data: { roomId:roomId, username:username, message:message },
success: function(html) {
strReturn = html;
}
});
}
But what it sees is
function setMessages(id){
$.ajax({
type: "get",
url: "http://www.sinansamet.nl/chatdistract/ajax/setMessages.php",
data: { id:id },
success: function(html) {
strReturn = html;
}
});
}
Which was the old code.
The error is given in the console as "undefined id"
Do a browser refresh cache on most browsers it can be done by pressing CTRL + F5
Search google for clearing your browser cache.
the a in ajax stands for asynchronous.
the function is returning before the callback of the ajax call is being called.