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.
Related
i wrote a code that will add records to data base then return the message to a specific div
now I need to know how to clear text boxes after I get the result to the div?
$(document).ready(function() {
$('#message').submit(function(e) {
e.preventDefault()
$.ajax({
url: 'processmsg.php',
data: $(this).serialize(),
method: 'POST',
success: function(resp) {
$('#error_msg').html(resp);
}
})
})
})
$(document).ready(function() {
$('#message').submit(function(e) {
e.preventDefault()
$.ajax({
url: 'processmsg.php',
data: $(this).serialize(),
method: 'POST',
success: function(resp) {
$('#error_msg').html(resp);
$('#FullName').html("");
$('#Email').html("");
$('#PhoneNumber').html("");
$('#Message').html("");
}
})
})
})
$(document).ready(function() {
$('#message').submit(function(e) {
e.preventDefault()
$.ajax({
url: 'processmsg.php',
data: $(this).serialize(),
method: 'POST',
success: function(resp) {
$('#error_msg').html(resp);
let frm = document.getElementsById('#message')[0];
frm.reset(); // Reset all form data
}
})
})
})
if it's a regular html form then from.reset();
$(document).ready(function () {
$('#message').submit(function (e) {
e.preventDefault()
$.ajax({
url: 'processmsg.php',
data: $(this).serialize(),
method: 'POST',
success: function (resp) {
$('#message')[0].reset();
}
});
});
});
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.
i have a div that shows the total sum of some products:
<div class="total-price"><?php echo (!empty($cart)) ? $cart['total'] : '0'; ?> $</div>
with ajax, i'm adding products to cart ... se the page is not reloading.
How to refresh the div after I add the product to cart?
The ajax that i'm using:
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
data: $(this).serialize(),
success: function () {
$(".success-message").slideDown().delay(5000).slideUp();
$(".total-price").something...;
}
});
})
</script>
Thank you!
You can do something like this:
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
data: $(this).serialize(),
success: function () {
$(".success-message").slideDown().delay(5000).slideUp();
var oldPrice = $('.total-price').text() * 1;
var itemPrice = "15"; //the price that should be added
$('.total-price').text(oldPrice + itemPrice);
}
});
})
</script>
You should be returning a total basket value from your /tdt/order path.
In the PHP script you should echo some JSON data with all the required information, for example
echo json_encode(array("totalPrice" => "£10.01"));
Then you need to parse this information into your Javascript and update the pages elements;
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
$(".success-message").slideDown().delay(5000).slideUp();
$('.total-price').val(data.totalPrice);
}
});
})
</script>
The above ajax request will expect the data returned to be JSON, you will then use this to update the total-price element.
You can use something like angularjs or knockoutjs - for angular you would update your model - for knockout you would use the self.object.push(value) i.e.,
function OrderViewModel() {
var self = this;
self.myOrder = ko.observableArray([]);
self.addOrderItem = function () {
$.ajax({
type: "post",
url: "yourURL",
data: $("#YOURFORMFIELDID").serialize(),
dataType: "json",
success: function (value) {
self.myOrder.push(value);
},
headers: {
'RequestVerificationToken': '#TokenHeaderValue()'
}
});
}
}
ko.applyBindings(new orderViewModel());
</script>
</pre>
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
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