auto load data from database using jquery - php

I would like to display newly inserted data from database. I found the below code from another question and it does what I want but it only shows the data when clicked. So can someone tell me how can I make the data auto load every 5 secs?
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "second.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<input type="button" id="display" value="Display All Data" />
<div id="responsecontainer" align="center">

$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "second.php",
dataType: "html", //expect html to be returned
success: function (response) {
$("#responsecontainer").html(response);
setTimeout(load, 5000)
}
});
}
load(); //if you don't want the click
$("#display").click(load); //if you want to start the display on click
});

Try to add setTimeout:
success: function(response){
$("#responsecontainer").html(response);
setTimeout(success, 5000);
}

You can use function setTimeout as a timer to trigger. For detail, please look at below code:
$(document).ready(function() {
loadData();
});
var loadData = function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "second.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
setTimeout(loadData, 5000);
}
});
};

You may use jquery's setInterval() or setTimeout() inside onload();
refer to the following questions, its answer explains well what you need exactly.
Calling a function every 60 seconds

Related

Call ajax after success

I made an ajax request to get the name of each button I click...
Then I want to put everything in that url into "#Container".(url define a page that has some codes)
It works for me at the first time...but for the other times I have to reload the page to show me the details of each button and it doesn't show me details of other buttons that clicked after first desired button..
$(function () {
$('button').click(function () {
var data= $(this).val();
$.ajax({
url: '/myurl',
type: 'post',
dataType: 'json',
data: {
data: data
},
success: function (data) {
$('#container').html(data);
}
});
});
});
What should I do?
Is there something preventing of running the ajax for next times ?
Try with $(document).on('click', instead of $('button').click like below
$(function () {
$(document).on('click','button',function () {
var data= $(this).val();
alert(data);
$.ajax({
url: '/myurl',
type: 'post',
dataType: 'json',
data: {data: data},
success: function (data) {
$('#container').html(data);}
});
});
});
You will need to re-bind ajax event because of its re-rendering DOM after an ajax request completes. All those elements under #container are not virtual part of DOM and your click event only works for pre-existed elements.
Try this
Wrap ajax event in a separate function
function ajaxEvent(data){
$.ajax({
url: '/myurl',
type: 'post',
dataType: 'json',
data: {data: data},
success: function (data) {
$('#container').html(data);
clickEvent(); //note this function attachment I added below
}
});
}
You can wrap your click event into a function
function clickEvent(){
$('button').off('click');
$('button').on('click',function(){
ajaxEvent($(this).val());
});
}
Now js looks like
<script>
$(function(){
clickEvent();
});
function ajaxEvent(data){
$.ajax({
url: '/myurl',
type: 'post',
dataType: 'json',
data: {data: data},
success: function (data) {
$('#container').html(data);
}
});
}
function clickEvent(){
$('button').off('click');
$('button').on('click',function(){
ajaxEvent($(this).val());
});
}
</script>
Also I see you are passing ajax data as $('button').val() which is not correct. Use a input type text if you want to send a data to server.

AJAX GET function using hyperlink?

I'm trying to use AJAX GET function in my code instead of POST.
i have a few hyperlinks which look like this:
<a class=netro" href="mypage.php?search=dog"></a>
<a class=netro" href="mypage.php?search=cats"></a>
<a class=netro" href="mypage.php?search=donkey"></a>
<a class=netro" href="mypage.php?search=apples"></a>
and in mypage.php I have this:
if (isset($_GET['search'])) {
$search = $_GET['search'];
////rest of my code////
}
without AJAX, the page page works fine and it gets the results bases on $search properly.
but with AJAX, i get nothing back in response that I get from AJAX.
this is my ajax code:
$(document).ready(function() {
$(function() {
$('.netro').click(function(event) {
event.preventDefault();
var urlssg = "mypage.php"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: urlssg,
dataType: "html", //expect html to be returned
success: function (response) {
$("#col1").html(response);
//alert('sent');
}
});
});
});
});
could someone please advise on this issue?
Thanks in advance,
You need to provide the search parameter along with the request. Try this:
$(document).ready(function() {
$('.netro').click(function(event) {
event.preventDefault();
var $a = $(this);
$.ajax({
type: "GET",
url: $a.attr('href'), // note that this will include the querystring param
dataType: "html", //expect html to be returned
success: function (response) {
$("#col1").html(response);
}
});
});
});
Here is a clean, simple approach:
HTML
<a class="netro" id="dog">Dog</a>
<a class="netro" id="cats">Cat</a>
<a class="netro" id="donkey">Donkey</a>
<a class="netro" id="apples">Apples</a>
JS/JQUERY
$(function() {
$(".netro").click(function(e) {
e.preventDefault();
var sId = $(this).attr("id");
$.ajax({
type: "GET",
url: "mypage.php?search="+sId ,
data: { search: search_id },
dataType: "html",
success: function (data) {
//Do something with the response data....
}
});
});
});

Multiple jQuery AJAX calls conflicts?

I am trying to create a simple shopping cart using AJAX and PHP.
Everything works as it should BUT 1 thing doesn't work all the time and it seems that it fails to execute. (it works 3 times out of 5).
to explain this issue please take a look at the code bellow:
jQuery(document).ready(function() {
//////////////////////LETS RUN OUR ADD TO CART FEATURE USING AJAX //////////////
$(function(){
$('.form1').on('submit', function(e){
$( "#preloader" ).fadeIn( 850 );
// prevent native form submission here
e.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'),// <-- get method of form
url: $(this).attr('action'),
//url: "cart.php",
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
$( "#preloader" ).fadeOut( 850 );
}
});
});
});
//////////////////////LETS RUN LOAD THE cart-header.php ON PAGE LOAD USING AJAX //////////////
$(document).ready(function () {
function load1() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "cart-header.php",
dataType: "html", //expect html to be returned
success: function (data2) {
$('#headerCart').html($(data2));
//setTimeout(load2, 500);
}
});
}
load1();
});
//////////////////////LETS LOAD THE cart-header.php on form1 submit USING AJAX //////////////
<!----- This is the part that SOMETIMES Fails to work --->
$(function(){
$('.form1').on('submit', function(load2){
// prevent native form submission here
load2.preventDefault();
// now do whatever you want here
$.ajax({
type: "GET",// <-- get method of form
url: "cart-header.php",
//url: "cart.php",
dataType: "html", // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
//$('#test').load('cart.php #total').html();
$('#headerCart').html($(data));
}
});
});
});
//////////////////////LETS RUN OUR DELETE FROM CART FEATURE USING AJAX //////////////
$(document).on('submit', '.delForm', function(dleItem){
// prevent native form submission here
dleItem.preventDefault();
// now do whatever you want here
$.ajax({
type: $(this).attr('method'),// <-- get method of form
url: "cart-header.php",
//url: "cart.php",
data: $(this).serialize(), // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
$('#headerCart').html($(data));
}
});
});
});
//////////////////////LETS GET THE QUANTITY OF CURRENT ITEMS ADDED IN THE CART USING AJAX/////////////
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "cart.php",
//url: "cart-header.php",
dataType: "html", //expect html to be returned
success: function (data) {
$('.item_count').html($(data).find('#total').text());
//$('#headerCart').html($(data));
setTimeout(load, 1000);
}
});
}
load();
});
I have commented the code so you can see the parts of the code and what they do.
the issue is this part:
//////////////////////LETS LOAD THE cart-header.php on form1 submit USING AJAX //////////////
<!----- This is the part that SOMETIMES Fails to work --->
$(function(){
$('.form1').on('submit', function(load2){
// prevent native form submission here
load2.preventDefault();
// now do whatever you want here
$.ajax({
type: "GET",// <-- get method of form
url: "cart-header.php",
//url: "cart.php",
dataType: "html", // <-- serialize all fields into a string that is ready to be posted to your PHP file
beforeSend: function(){
},
success: function(data){
//$('#test').load('cart.php #total').html();
$('#headerCart').html($(data));
}
});
});
});
As I mentioned above, this code works fine but it only works when it wants to as if it has mind of its own!
could someone please advise on this issue?
Thanks in advance.

two ajax request from one page

Simply I would like to load data from two php page using jquery. I put the below code together, however only the one works not both. Any ideas?
$(document).ready(function() {
loadData();
});
var loadData = function() {
$.ajax({
type: "GET",
url: "second.php",
dataType: "html",
success: function(response){
$(".hm_m_un").html(response);
setTimeout(loadData, 1000);
}
});
};
$(document).ready(function() {
loadData();
});
var loadData = function() {
$.ajax({
type: "GET",
url: "test.php",
dataType: "html",
success: function(response){
$(".rx").html(response);
setTimeout(loadData, 1000);
}
});
};
You're overriding your first loadData variable with the second one. Give it a different name and you'll be fine.
As a note, you don't need to call $(document).ready() twice, you can technically call it once. I would write this as something like:
function descriptiveFunctionName() {
$.ajax({
type: "GET",
url: "second.php",
dataType: "html",
success: function(response){
$(".hm_m_un").html(response);
setTimeout(loadData, 1000);
}
});
}
function anotherDescriptiveFunctionName() {
$.ajax({
type: "GET",
url: "test.php",
dataType: "html",
success: function(response){
$(".rx").html(response);
setTimeout(loadData, 1000);
}
});
}
$(document).ready(function() {
descriptiveFunctionName();
anotherDescriptiveFunctionName();
});
Please note though this was a very lazy answer, user Machavity's code is much better for reuse, although you may want to just use a callback sent to loadData for more flexibility in the future.
You've named them all the same. Try some consolidation
$(document).ready(function() {
window.setInterval(function() { loadData('second.php', $('.hm_m_un')); }, 1000);
window.setInterval(function() { loadData('test.php', $(".rx")); }, 1000);
});
var loadData = function(page, ele) {
$.ajax({
type: "GET",
url: page,
dataType: "html",
success: function(response){
ele.html(response);
}
});
};
Very simple....you declared a variable loadData and assigned it to a function.
You then used same variable to assign to another function, thereby wiping out first instance. Use different variable names

jQuery Ajax = success return page

Ok so I know long hand ajax but trying to use the jQuery short cut. I have two documents
form.php
submit.php
In my "form" page I am calling the "submit" page to process the insert. I am currently using the jquery ajax:
<script type="text/javascript">
jQuery('form').submit(function() {
string = jQuery("form").serializeArray();
jQuery.ajax({
type: "POST",
url: "submit.php",
data: string,
dataType: "json",
})
return false;
});
</script>
When I view firebug it is processing the ajax fine. I am getting 200 and post parameters are set. What I am trying to do is have the ajax return the submit.php file. I know it has something to do with the "success" function but I don't know how to add this. I tried a few things like:
<script type="text/javascript">
jQuery('form').submit(function() {
string = jQuery("form").serializeArray();
jQuery.ajax({
type: "POST",
url: "submit.php",
data: string,
dataType: "json",
success: function(html){
alert(html);
}
})
return false;
});
</script>
and
<script type="text/javascript">
jQuery('form').submit(function() {
string = jQuery("form").serializeArray();
jQuery.ajax({
type: "POST",
url: "submit.php",
data: string,
dataType: "json",
success: function(html){
$('.result').html(data);
}
})
return false;
});
</script>
but neither of these are working. Again I am simply trying to send the ajax request and then return the contents of the submit.php page. Not only does the submit.php page hold the script to process the php/ajax insert but it also display success statements like "insert was successful" so that is why I need to not only run the script in the page but also return the contents of that page. Thank you for any help.
Chagne the dataType:'json' to dataType:'html' for the callback that you wish to display the contents of submit.php.
You were close in your second attempt, but you made a typo. Try:
success: function (data) {
$('.result').html(data);
}
Also, unless your server is returning JSON, you probably want to change the dataType:
dataType: "html"

Categories