Multiple jQuery AJAX calls conflicts? - php

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.

Related

How to have only one processing file for multiple AJAX call

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

Ajax post not sending data to PHP file

So I am working on a project in which I have to pass some form data to a database without reloading the page using Ajax. But the $_POST variable in the PHP file is always empty. I do know that I am actually getting the data from the form since I can print and it looks okay in the javascript code:
$(document).ready(function () {
$('form').on('submit', function (event) {
// prevent page from refreshing
event.preventDefault();
$.ajax({
url: 'post.php',
type: 'POST',
data: {name: 'tony'},
dataType: 'json',
success: function (response) {
$('#message').html(response);
}
});
//return false;
});
});
And this is the php code:
<?php
//var_dump($_POST);
if (isset($_POST['name'])) {
$name = $_POST['name'];
echo $name;
} else {
echo "error";
}
?>
Use this code instead, you won't need to manually define the parameters to be sent because it will be automatically set by FormData():
$('#form').submit(function(event) {
event.preventDefault();
var data = new FormData(this);
$.ajax({
url: "post.php",
type: "POST",
data: data,
contentType: false,
processData: false,
success: function(result) {
console.log(result);
}
});
});
So, turns out I am just stupid.. It was actually working properly after all but I was checking if it works the wrong way. I was actually navigating to the php file by entering the url expecting to see my data printed on the php page. Finally, I checked the response of the POST request and it was working just fine.Thank you for your answers and I apologize for wasting your time.
try this,
$('form').on('submit', function (event) {
// prevent page from refreshing
event.preventDefault();
$.ajax({
url: 'post.php',
method: 'POST',
data: {name: 'tony'},
success: function (response) {
$('#message').html(response);
}
});
});

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.

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"

jquery .load not loading immediately after loading data

I was wondering if this was making an asynchronous request...write now Im using:
<script type='text/javascript'>
$(document).ready(function() {
var ktitle = $('.hiddentwo').text();
$('div#tab2').load('morefour.php?title=' + encodeURIComponent(ktitle));
});
</script>
what Im doing though is adding text in the first, into the database, on the current php file (addtext.php). Im passing the Id of the current document to the morefour.php and that is loading the added text on the second tab...the thing is, Im having to refresh to see the content again. Im running on localhost btw.
For more clarity, Im running another jquery script that on clicks, retrieves this data to send it to a php file to enter into a database
$(".button").click(function() {
var content = $(this).siblings().outerHTML();
$.ajax({
async: false,
type: "POST",
url: "tosqltwo.php",
data: {
content: content
}
});
});
$(function(){ //shorthand of $(document).ready
$('div#tab2').html($.ajax({
type: "GET", //if you are doin $_GET['title'] in morefour.php
url: "morefour.php",
data : {title:ktitle},
dataType: 'html', //i am not sure about this part
async: false
}).responseText)
});
or you can try
$(function(){
$.ajax({
url : 'morefour.php',
data : {title:ktitle},
type:'GET',
dataType:'html',
success: function(data) {
$('div#tab2').html(data);
}
});
});
you can use $.ajax function with async to false.
$.ajax({
async: false,
url : 'morefour.php',
data : 'title=' + encodeURIComponent(ktitle),
success: function(data) {
$('div#tab2').html(data);
}
});

Categories