how to load data without page refresh using ajax - php

Here is my code for loading data
$(document).ready(function() {
$.get('get-answers.php', {
project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
}, function(data) {
$('#dispaly-answers').append(data);
});
});
This code retrieves data from database and working fine. But problem here is that if I add new data on the database, this data doesn't show up without page refresh.
So I don’t want to refresh the page to get the data. It should be displayed once new data added to database.
Any suggestions on this issue?
P.S : I also tried .ajax(), didn’t work.
Here is my $.ajax() request
$(document).ready(function() {
$.ajax( {
type: "GET",
url: "get-answers.php",
data: { project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
},
cache: false,
success: function(data) {
$('#dispaly-answers').append(data);
},// success
})// ajax
});
Does the same as $.get()

If your goal is to refresh the page data without refreshing the page, you can put your code in an interval timer and let it auto refresh every x seconds, like below.
setInterval(getAnswer(), 1000);
note: setInterval fires again and again until you clear it, while setTimeout only fires once.

The Ajax-Function get only called once: In the moment the document is ready (fully loaded). You have to use setTimeout to create a timer, which calls the function every minute or whatever you want. Like this:
function getData() {
setTimeout(function(){
$.get('get-answers.php', {
project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
}, function(data) {
$('#dispaly-answers').append(data);
getData();
});
}, 3000);
}

Here is my final approach
$(document).ready(function() {
setInterval(function(){
$.ajax( {
type: "GET",
url: "get-answers.php",
data: { project_question_id: <?=$project_question_id?>,
project_id: <?=$project_id?>
},
cache: false,
success: function(data) {
$('#dispaly-answers').html(data);
},// success
})// ajax
}, 1000);
});
Without creating and calling function getData(), this code working fine. Also I have changed .append(data) to .html(data).
But still I'm not happy with my code because it is constantly retrieving data from database that makes data server busy.
Whatever I wanted to tasks has to be done and it is done.

Try this you just need to replace this file retrieve_query.php and this id query-div with yours.
setInterval(function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
$('#query-div').html(this.responseText);
}
};
xmlhttp.open("GET","retrieve_query.php",true);
xmlhttp.send();
},1000);

Related

jQuery Live Search keyup show loading

I am trying to display a loading animation and hide the search input box before the ajax request has been sent, the ".se-pre-con" element is the loader.
As you can see below I am tring to show this in the beforeSend of the ajax request. However, when the user is typing in the search box then stops for the delay specified (1000ms) the input box still displays throughout the ajax request but it is unresponsive.
Then the results are returned, and the loading animation does the fadeOut so it the show() must be triggering but the page remains unchanged until the results are returned. I want to prevent the unresponsive page effect and show a loading animation during the request. Any help is much appreciated.
$(document).ready(function() {
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
$('#search_field').keyup(function() {
var target = $(this);
delay(function() {
getSearchResults(target.val());
}, 1000);
});
function getSearchResults(str) {
$.ajax({
beforeSend: function(){
$(".se-pre-con").show();
$("#search_field").hide();
},
url: "http://example.com/Search_Results.php",
dataType:"html",
data: {"search_term": str},
method: "post",
async: false,
success: function(data){
if(data !== null) {
$("#search_default").hide();
$("#search_results_wrapper").html(data);
}
$(".se-pre-con").fadeOut("slow");
$("#search_field").show();
$("#search_field").focus();
},
error: function(){
$(".se-pre-con").fadeOut("slow");
$("#search_field").show();
$("#search_field").focus();
}
});
}
});
I found the solution.
Solution
It started working when I removed the option:
async: false

Do not want to wait till server response to the AJAX request

I have created a long polling using jQuery / PHP. and it is working perfectly. The issue is when a user click on other links or refresh the current page, it will hang on the current page till it get response from last AJAX request from server.
I have set about 30 sec in the server side to pick the latest data, means if someone sent a request to get the latest data, he cannot go to another page or refresh the current page till it returns the response. The worse case is, if the server didnt find the latest data, it will send the response after 30 sec.
I have use the following code to abort the request.
window.onbeforeunload = function(event) {
xhr.abort();
}
I have check on the console before and after execute xhr.abort() it shows readyState=1 and then readyState=0. Does this means xhr.abort() executed successfully? But why still the page hang on the current page till it returns the response.
Please help me to solve my issue. I don't want to wait until the server response when user click on other link or refresh page or do other stuff on the page.
This is my jQuery code
function setNoti(ntotal)
{
var t;
xhr = $.ajax({
type: "POST", url: myURL, data: "", dataType: "JSON", cache: false, async: true,
success: function(data) {
// do my work here
clearInterval(t);
t = setTimeout(function() {
setNoti(20);
}, 1000);
return false;
},
error: function()
{
clearInterval(t);
t = setTimeout(function() {
setNoti(0);
}, 40000);
return false;
}
});
}
You are assigning an xhr which can then be used to abort the request on subsequent calls to the function.
function setNoti(ntotal)
{
if (xhr) {
xhr.abort();
}
var t;
xhr = $.ajax({
type: "POST", url: myURL, data: "", dataType: "JSON", cache: false, async: true,
success: function(data) {
// do my work here
clearInterval(t);
t = setTimeout(function() {
setNoti(20);
}, 1000);
return false;
},
error: function()
{
clearInterval(t);
t = setTimeout(function() {
setNoti(0);
}, 40000);
return false;
}
});
}
No need for the window.onbeforeunload handler, which being a separate event is likely being called at the wrong time.
I have added session_write_close() in the server side and it is working perfectly. Following post helped me to find the solution :)
Multiple AJAX requests delay each other

two ajax functions at the same time? not working

I have a simple AJAX script that suppose to to call a PHP file and get data back.
window.addEvent('domready', function() {
$('dbform').addEvent('submit', function(e) {
new Event(e).stop();
var intervalId =setInterval(function()
{
var Ajax2 = new Request({
url: '/tools/getdata.php',
method: 'post',
data: 'read=true',
onComplete: function(response)
{
$('results').set('html', response);
}
}).send();
},1000);
var postString = 'subbutton=' + $('subbutton').value;
var Ajax = new Request({
url: '/tools/getdata.php',
method: 'post',
data: postString,
onRequest: function()
{
$('message').set('text', 'loading...');
},
onComplete: function(response)
{
$('message').set('text','completed');
clearInterval(intervalId);
},
onFailure: function()
{
$('message').set('text', 'ajax failed');
}
}).send();
});
});
The file that it is submitting too is.
$object= new compare();
if(isset($_POST['subbutton'])=='Run')
{
// This take about 5 minutes to complete
$run=$object->do_compare();
}
if(isset($_POST['read'])=='true')
{
/// in the mean time, the first ajax function is suppose to return data from here..while
// the do_compare() function finish.
// the problem is that it only return it once the do_compare() finish
///
echo 'read==true';
}
the script is working fine, expect, that when the Ajax request check the file every one second, it doesn't return any thing from $_POST['read'], till $run=$object->do_compare(); has finished.
why does it do that? what What I am trying to accomplish is that one Ajax function get data from do_compare function and the other ajax function also independently get that from the getdata.php file.
The problem is in line:
if(isset($_POST['subbutton'])=='Run')
isset returns boolean true or false so if $_POST['subbutton'] is set than it returns true and due to the weak type system of php true == 'Run' because 'Run' evaluates to true. Use
if(isset($_POST['subbutton']) && $_POST['subbutton'] === 'Run')
and
if(isset($_POST['read']) && $_POST['read'] === 'true')
Are you using session in the PHP AJAX handlers? If so, your session file is probably blocked.
Second: Javascript is internally single threaded in the browser (see google for more information).

2 Mootools AJAX function at the same time?

I'm new to Javascript and Mootools and I was wondering if someone can help me learn by solving a problem that I currently have.
index.php has a form, which submit to it self and initiate this code
if($_POST['subbutton']=='Run')
{
$data=$object->do_compare();
}
I would like to know, how can I do a mootool ajax function, that will send the post['run]'
to a php script file ( data.call.php ) where the object reside and have it run.
however, I don't want any respond from data.class.php, as that object writes it's results to a txt file (data.txt)
the 2nd part,
would be an ajax function (that also run at the same time as the first ajax function) and reads a php file, every 5 seconds and bring the data back to index.php
so the squence of operations will be
index.php
form get clicked and start 2 ajax functions.
the first one, only submit the POST['run'] to a php script.
the second function, will go to another php file and get a respond from it every 5 seconds.
I didn't test the below, so use at your own risk. But that's pretty much the gist of it.
_form.addEvent('submit', function(event) {
// your first call
new Request.JSON({
url: "your-first-rpc",
data: {
subbutton: "Run"
},
onSuccess: function(response) {
// handle response here.
}
}).post();
// your second call which runs every 5 secs.
(function() {
new Request.JSON({
url: "your-second-rpc",
data: {
subbutton: "Run"
},
onSuccess: function(response) {
// handle response here.
}
}).post();
}).periodical(5000);
});
<script type="text/javascript">
window.addEvent('domready', function() {
$('dbform').addEvent('submit', function(e)
{
new Event(e).stop();
var intervalId =setInterval(function(){
var Ajax2 = new Request(
{
url: '/tools/getdata.php',
method: 'post',
data: 'read=true',
onComplete: function(response)
{
$('21').set('text', response);
}
}
).send();},1000);
var postString = 'subbutton=' + $('subbutton').value;
var Ajax = new Request({
url: '/tools/getdata.php',
method: 'post',
data: postString,
onRequest: function()
{
$('message').set('text', 'loading...');
},
onComplete: function(response)
{
$('message').set('text','completed');
clearInterval(intervalId);
},
onFailure: function() {
$('message').set('text', 'ajax failed');
}
}).send();
});
});
</script>

jQuery ajax request awkward issue

So I have this ajax request. When the user clicks an edit link, I fetch the ID of the entry and refresh the page with the data of that entry loaded into a form.
Here's my problem: This only works with the alert showing before the ajax call. When I leave out the alert, I get an ajax error (though the id is being posted) and the PHP page just reloads. Moreover, it only works when I put the newDoc stuff as a success callback. The exact same lines as a complete callback and the page reloads. Moreover, this occurs in Firefox only.
jQuery('a.edit').on('mousedown', function (e) {
e.preventDefault();
var id = jQuery(this).attr('data-title');
alert('test');
jQuery.ajax({
url: document.location,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
},
error: function () {
alert('error');
}
});
});
What can I do?
EDIT: This must be a timing issue. I just noticed that when I click and hold the edit link for a second or so, everything works fine. When I do a short click, it doesn't. So I tried wrapping the ajax in setTimeout(), but that didn't help. Any other ideas?
Try to use location.href in place of document.location,
jQuery.ajax({
url: location.href,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
},
error: function () {
alert('error');
}
});
location is a structured object, with properties corresponding to the parts of the URL. location.href is the whole URL in a single string.
Got it!
The problem is the way Firefox handles the mousedown event. It seems to abort the ajax call as soon as you relase the mouse button. I changed the event to click and everything is fine now.
jQuery('a.edit').on('click', function () {
var id = jQuery(this).attr('data-title');
jQuery.ajax({
url: document.location,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
}
});
});

Categories