How to have only one processing file for multiple AJAX call - php

I wanted to know how we can have only one processing file for multiple ajax call. Files like delete.php and update.php
For example, if there are two tables, one for invoice and the other for stock, and In order to delete them through ajax, I would have to create two processing files (delete-invoice.php and delete-stock.php). How can I have just one processing file instead of creating multiple files
// Ajax call to delete invoice
$('.delete_invoice').on('click',function(){
var invoice_delete_id = $(this).data("invoicedelete");
var element = this;
$.ajax({
url: 'includes/delete_invoice.inc.php',
type: 'POST',
data: {invoice_delete_id:invoice_delete_id},
beforeSend: function(){
$("#loadgif").show();
},
complete: function(){
$("#loadgif").hide();
},
success: function(delete_invoice_result){
$(element).closest('tr').remove();
}
});
});
// Ajax call to delete stock
$('.delete_stock').on('click',function(){
var stock_delete_id = $(this).data("stockdelete");
var element = this;
$.ajax({
url: 'includes/delete_stock.inc.php',
type: 'POST',
data: {stock_delete_id:stock_delete_id},
beforeSend: function(){
$("#loadgif").show();
},
complete: function(){
$("#loadgif").hide();
},
success: function(delete_stock_result){
$(element).closest('tr').remove();
}
});
});
How can I shorten this process? Hope you got an idea of what I'm trying to achieve. Thank you

Related

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.

Trying to pass a variable from JQuery to PHP

So, I've looked at several questions and answers here, and they all seem to point in the same direction, but I just can't make it work. . .
I want to read a variable from a file in JQuery, add one to it, then pass it to php to write the new value to the file. I have separate HTML/JavaScript and PHP files.
In the Javascript, I have:
$(document).ready(function(){
var data
$.get('scoredir/data.txt', function(data) {
count = parseInt(data);
count = count +1;
});
$.ajax({
type: 'POST',
url: 'savedata.php',
data: { 'numberOfPlays' : count },
success: function (response) {
//alert (response);
}
});
});
In the php file (savedata.php), I have:
<?php
$data = $_POST['numberOfPlays'];
file_put_contents("scoredir/data.txt", $data);
?>
It seems like the php file just isn't getting the variable. Anyone know what's wrong?
You're having typical asynchronous AJAX issues. You're $.ajax command is running before your $.get command has completed it's request.
For a quick-fix, try something like this instead:
$(document).ready(function(){
var data;
$.get('scoredir/data.txt', function(data) {
count = parseInt(data);
count = count +1;
$.ajax({
type: 'POST',
url: 'savedata.php',
data: { 'numberOfPlays' : count },
success: function (response) {
//alert (response);
}
});
});
});
Also, look into deferred objects and promises.
I think behavior of ajax is async so one is getting completed and other is not or may be vice-versa, so you can do this:
$(document).ready(function(){
$.get('scoredir/data.txt', function(data) {
var count = parseInt(data); // you can declare your variable here
count = count + 1;
$.ajax({
type: 'POST',
url: 'savedata.php',
data: { 'numberOfPlays' : count },
success: function (response) {
//alert (response);
}
});
});
});
One thing I noticed is, $.get is just a shorthand, it is already an asynchronous ajax call. Therefore, in order to work with the result (e.g. count) of that request, your second ajax call needs to go inside the callback of $.get like so:
$(document).ready(function(){
var count;
$.get('http://echo.jsontest.com/key/22', function(data) {
count = parseInt(data.key);
count = count +1;
$.ajax({
type: 'POST',
url: 'savedata.php',
data: { 'numberOfPlays' : count },
success: function (response) {
//alert (response);
}
});
});
});
Demo: http://jsfiddle.net/3Pykx/

Ajax call not updating first time

I used Ajax call for display data and update data. Ajax call working well but it's not updating at single time. database updating well in server. For UI part it's not updating.
Used Ajax Call
$('#loginbutt').click(function(){
$.post('data.php',{action: "update"},function(res){
$('#result').html(res);
});
var servertime = $("#timer1").text();
var dataString = 'current_time='+ servertime;
$.ajax({
type: "POST",
url: "inset_intime.php",
data:dataString ,
cache: true,
beforeSend: function(html) {
document.getElementById("lastfive").innerHTML = '';
},
success: function(html){
$("#lastfive").append(html);
}
});
});
it's updating data .php but not updating inset_time.php. data is inserting well inti server. but UI not updating. IN data.php i given insert query for insert data. In inset_time.php i given select query for displaying data. but why it's not at a time when i click on loginbutt.
Try this
$(document).ready(function(){
$('#loginbutt').live('click',function(){
$.post('data.php',{action: "update"},function(res){
$('#result').html(res);
});
var servertime = $("#timer1").text();
var dataString = 'current_time='+ servertime;
$.ajax({
type: "POST",
url: "inset_intime.php",
data:dataString ,
cache: true,
beforeSend: function(html) {
document.getElementById("lastfive").innerHTML = '';
},
success: function(html){
$("#lastfive").append(html);
}
});
});
});

How to prevent multiple loading PHP script calling JS script?

I created a simple voting system (+ and -) on Ajax for users comments. One page have 50 posted comments and you can vote for each "plus" or "minus". This data sent through the PHP script to the database. However, if a user votes, the PHP script is called 50 times - it is visible in Chrome developer tool. There are errors - more value than expected. Here is my code (two DIV buttons and the script).
Tell me please how to change the code to the script (up_vote.php or down_vote.php) is called only once.
<script type="text/javascript" src="raitings/jquery.js"></script>
<script type="text/javascript">$(function() {$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if(name=='down')
{
$(this).fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">');
$.ajax({type: "POST", url: "raitings/down_vote.php", data: dataString, dataType : "html", cache: false, success: function(html)
{ parent.html(html);}
});
}
else
{
$(this).fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">');
$.ajax({type: "POST", url: "raitings/up_vote.php", data: dataString, dataType : "html", cache: false, success: function(html)
{ parent.html(html);
} });
}
return false;
});
});
</script>
//php code below;
echo "<div class=\"box1\"><div class=\"up\">".$up."</div>"
."<div class=\"down\">".$down."</div></div>\n";
Using jQuery, it's important to know that events are stackable, even if the event is exactly the same. For example:
$(".vote").click(function() { alert("hi"); });
$(".vote").click(function() { alert("hi"); });
$(".vote").click(function() { alert("hi"); });
If we ran these three lines verbatim, we'll have 3 different events attached. That is, we would get 3 alerts one after the other by clicking in an element with the vote class.
In addition, oftentimes it happens that pages being loaded through ajax carry the same <script></script> block of the parent page, and when this is the case, the code is inadvertently being processed again and again with every ajax call.
While I was not able to pinpoint exactly how is this happening by the code you provided, it seems this is the most likely scenario: your click handler event is being loaded several times, and as a result one click triggers several ajax calls.
The quick and dirty solution when this presents as I mentioned in the comments is replacing:
$(".vote").click(function()
By:
$(".vote").unbind("click").click(function()
Which thanks to the unbind function forces it to discard previously attached events every time a new one is attached, thus preventing it from having more than one event attached no matter how many times the code is processed.
While this will work, the better solution is, of course, to locate where is the js code being loaded multiple times and make sure it is loaded just once.
$(".vote").each(function () { $(this).click( clickHandler .... etc should solve your problem.
I don't fully understand how your version works but I would do it similar to this:
+
-
Where 200 would be the unique id of the comment.
Then have a vote_up() and vote_down() function defined in a JavaScript and add your ajax requests there.
That way it should not call the script more than once when +/- button is clicked.
You can disabled button before send you ajax request.
// Sample:
$(function() {
$(".vote").click(function() {
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
parent.fadeIn(200).html('<img src="raitings/dot.gif" align="absmiddle">');
if(name=='down')
{
$.ajax({
type: "POST",
url: "raitings/down_vote.php",
data: dataString,
dataType : "html",
cache: false,
beforeSend: function() {
parent.attr("disabled", true);
},
success: function(html) {
parent.html(html);
}
});
} else {
$.ajax({
type: "POST",
url: "raitings/up_vote.php",
data: dataString,
dataType : "html",
cache: false,
beforeSend: function() {
parent.attr("disabled", true);
},
success: function(html) {
parent.html(html);
}
});
}
return false;
});
});

Calling AJAX from jQuery and displaying a waiting message

I'm very new at AJAX calls from jQuery and I'm a bit stuck trying do to this; I have an AJAX call from jQuery like this:
$(document).ready(function() {
$('tr.table-row').click(function(){
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) {//the_output_here}});
});
});
This script is inside a web page triggered when the user hits a particular row (<tr></tr>) from a table. stats-render.php outputs HTML text with some info and graphics. This answer some times takes a while (15 seconds), so I would like to show the user a waiting message when he/she triggers the script and when the call returns an answer show the output text in a div (lets call it <div id="render-div">).
So the questions are, how can I show a waiting message? If you know a good script for showing this in a modal, I would appreciate it.
How can I output the result from stats-render.php into a div?. Thank you so munch for any help!
Just display a loading message in the div where the results go in the interim.
$(document).ready(function() {
$('tr.table-row').click(function(){
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) { $('div.for-results').html( /* d... */ ); });
$('div.for-results').html('loading...');
});
});
Or for even more fun:
$(document).ready(function() {
$('tr.table-row').click(function(){
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) {
clearInterval(loading);
$('div.for-results').html( /* d... */ );
});
$('div.for-results').html('loading');
var loading = setInterval(function() { $('div.for-results')[0].innerHTML += '.' }, 1000);
});
});
The easiest option is probably to check out the jquery-loading plugin.
I just do a simple show the message before the call, and hide it on the success callback like this:
However I think jquery might have a callback option when the ajax call starts, and when it stops.
$(document).ready(function() {
$('tr.table-row').click(function(){
//Show the loading message, or chage a css class, or what have you.
$('#loadingmessagetext').show();
$.ajax({ url: 'stats-render.php', data: {ref: $(this).attr('id')}, type: 'post', success: function(d) {
//Hide the loading message
$('#loadingmessagetext').hide();
//the_output_here
}
});
});
});

Categories