On my site i am loading shopping products with the "add to cart"-button dynamically with a jquery ajax call. For the shopping cart itself, I use jcart, jquery plugin.
When I then add an item to the cart, jcart calls a php-file with ajax and POST. All works fine, the products are correctly added to the cart, but the page reloads every time I add an item to the cart.
When I don't use the ajax call to load the products (e.g. load them directly in the page), all works fine, so there must be a conflict somewhere.
Any clues?
This is my products-function and the html.
...
<script>
function loadProducts(str) {
$.ajax({
type: 'GET',
async: true,
url: 'ajax/load.php',
data: {'max-id' : str},
cache: false,
success: function(response) {
$('#products').html(response).fadeIn('slow');
},
});
}
</script>
<script>
$(document).ready(function() {
var n = '';
loadProducts(n);
});
</script>
<script src="jcart/js/jcart.js"></script>
</body>
</html>
The jcart-Plugin with its ajax-call can befound here:
http://conceptlogic.com/jcart/standalone-demo/jcart/js/jcart.js
Here are the functions from jcart.js.
$.ajaxSetup({
type: 'POST',
url: path + '/relay.php',
cache: false,
success: function(response) {
// Refresh the cart display after a successful Ajax request
container.html(response);
$('#jcart-buttons').remove();
},
error: function(x, e) {
...
}
});
...
function add(form) {
// Input values for use in Ajax post
var itemQty = form.find('[name=' + config.item.qty + ']'),
itemAdd = form.find('[name=' + config.item.add + ']');
// Add the item and refresh cart display
$.ajax({
data: form.serialize() + '&' + config.item.add + '=' + itemAdd.val(),
success: function(response) {
// Momentarily display tooltip over the add-to-cart button
if (itemQty.val() > 0 && tip.css('display') === 'none') {
tip.fadeIn('100').delay('400').fadeOut('100');
}
container.html(response);
$('#jcart-buttons').remove();
}
});
}
...
// Add an item to the cart
// is called from the submit-buttons within each product picture
$('.jcart').submit(function(e) {
add($(this));
e.preventDefault();
});
The "loadProducts()" function puts this into #products container for each item:
<form method="post" action="" class="jcart">
<fieldset>
<input type="hidden" name="jcartToken" value="<?php echo $_SESSION['jcartToken'];?>" />
<input type="hidden" name="my-item-id" value="SDK12345" />
<input type="hidden" name="my-item-name" value="Product Name" />
<input type="hidden" name="my-item-price" value="1.00" />
<input type="hidden" name="my-item-qty" value="1" />
<ul>
<li><img src="product-image.jpg"/></li>
<li>1.00 Dollar</li>
</ul>
<input type="submit" name="my-add-button" value="Add to cart" class="button" />
</fieldset>
</form>
I'm guessing you are calling the loadProducts() function in a binded click action on your add to cart button. If you are using an element with a default click behavior. You might want to prevent that with a 'return false;' on the last line of your binded click function.
like this:
$('a.addtocart').bind('click', function(){
//logic here (ajax)
return false;
});
After your success function there's also a comma that might get messy in IE:
success: function(response) {
$('#products').html(response).fadeIn('slow');
},
Remove the comma
I think there's an error in your ajax call, try to work it out... i cant see the logic of your php file that adds products to your basket. but if you want to send the data of your form (quantity, itemid), serializing your form data should be enough. No need to pass extra get variables.
function add(form) {
$.ajax({
data: form.serializeArray(),
url: 'yourfile.php',
success: function(response) {
// logic
}
});
}
Ok, I found the solution.
As the forms are loaded via ajax, they were no correctly interpreted by jcart.js (though the functions all worked fine for themselves).
"bind" didn't work, but "live" fixed it:
$('.jcart').live('submit',function(e) {
add($(this));
e.preventDefault();
});
Related
I have an ajax script that inserts a value if it is not in the database and removes the value if it is already there, and returns 1 or 0 accordingly, based on the return value it adds or removes a class in the existing button.
I have tried with find() to take the subclass value but still it is not working.
<form method="post" class="wish" action="process.php">
<input type='hidden' id='value' name='value' value='1'>
<button type="submit" class="card-fox list active" >fan</button>
</form>
This line has active I want it to be added if it is not there and remove if it is there.
below is the ajax:
$(document).ready(function (e) {
$(".wish").on('submit', (function (e) {
e.preventDefault();
$.ajax({
url: "process.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (data) {
if (data == 1) {
$(".list", this).addClass("active");
}
if (data == 2) {
$(".list", this).removeClass("active");
}
},
error: function (e) {}
});
}));
});
the problem is that although the ajax script is being executed and everything else is working, the active class is neither adding or removing.
Use:
$(".wish").find('button').addClass("active");
$(".wish").find('button').removeClass("active");
Or:
//when form is submit, make a copy of this
let self = this;
//send ajax
//in success ajax
$(self).find('button').addClass("active");
Greetings!
The this in your ajax success function is not the form.
You can set the context of the ajax call to the for to address this.
$.ajax({
context: this, //<- this this is the form, and tells jQuery to set the this of its callbacks to the form
I am trying to send my input value to a code segment in the same page, but it doesn't work. Right now, I can't get the value in the code segment. This is my current code:
<?php
if ($section == 'codesegment') {
if ($_GET['hour']) {
echo $_GET['hour'];
//here i want call my method to update db with this value of hour...
}
if ($section == 'viewsegment') {
?>
<form id="my_form" action="#" method="Get">
<input name="hour" id="hour" type="text" />
<input id="submit_form" type="submit" value="Submit" />
</form>
<script>
var submit_button = $('#submit_form');
submit_button.click(function() {
var hour = $('#hour').val();
var data = '&hour=' + hour;
$.ajax({
type: 'GET',
url: '',
data: data,
success:function(html){
update_div.html(html);
}
});
});
</script>
Any advice?
If you want to get the value without refresh your page you have to use javascript, you can try this:
$('#hour').onchange = function () {
//type your code here
}
By the way, your php script is server side, according to this, you can't use the value without post/submit/refresh
Whenever you are using
<input type="submit">
it sends the data to the action of the form, so whenever you are clicking the submit button before the onclick function gets called, it sends the data to the action and the page gets refreshed. So instead of using input element try something like this
<button id="submit_form"> Submit </button>
two things,
1. as yesh said you need to change the input submit to button type=button and add an onClick function on that button. Or you can give a the javascript function inside a function line function sampleFn(){} and call this function onSubmit of form.
2. You need to give the javascript inside document.ready function since the script execute before the dom loading and the var submit_button = $('#submit_form'); may not found. In that case there will be an error in the browser console.
Try to add errors in the post since it will help to debug easily.
It's not possible to do on the same page. you can write ajax call to another page with data where you can do the functions with the data.
Something like this
//form.php
<form id="hour-form">
<input type="text" name="hour" id="hour">
<input type="submit" name="hour-submit" >
</form>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '#hour-form', function(e){
e.preventDefault();
var data = $('#hour').val();
$.ajax({
url: "post.php",
method: "POST",
data: {'hour':data},
success: function(data)
{
//if you want to do some js functions
if(data == "success")
{
alert("Data Saved");
}
}
});
});
});
//post.php
if(isset($_POST['hour']))
{
// do the php functions
echo "success";
}
I've never used Ajax before, but from researching and other posts here it looks like it should be able to run a form submit code without having to reload the page, but it doesn't seem to work.
It just redirects to ajax_submit.php as if the js file isn't there. I was trying to use Ajax to get to ajax_submit without reloading anything.
Is what i'm trying to do even possible?
HTML form:
<form class="ajax_form" action="ajax_submit.php" method="post">
<input class="input" id="license" type="text" name="license" placeholder="License" value="<?php echo htmlentities($person['license1']); ?>" />
<input class="input" id="license_number" type="text" name="license_number" placeholder="License number" value="<?php echo htmlentities($person['license_number1']); ?>" />
<input type="submit" class="form_button" name="submit_license1" value="Save"/>
<input type="submit" class="form_button" name="clear1" value="Clear"/>
</form>
in scripts.js file:
$(document).ready(function(){
$('.ajax_form').submit(function (event) {
alert('ok');
event.preventDefault();
var form = $(this);
$.ajax({
type: "POST",
url: "ajax_submit.php",//form.attr('action'),
data: form.serialize(),
success: function (data) {alert('ok');}
});
});
});
in ajax_submit.php:
require_once("functions.php");
require_once("session.php");
include("open_db.php");
if(isset($_POST["submit_license1"])){
//query to insert
}elseif(isset($_POST['clear1'])) {
//query to delete
}
I have "<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>"
in the html head
form.serialize() doesn't know which button was used to submit the form, so it can't include any buttons in the result. So when the PHP script checks which submit button is set in $_POST, neither of them will match.
Instead of using a handler on the submit event, use a click handler on the buttons, and add the button's name and value to the data parameter.
$(":submit").click(function(event) {
alert('ok');
event.preventDefault();
var form = $(this.form);
$.ajax({
type: "POST",
url: "ajax_submit.php",//form.attr('action'),
data: form.serialize() + '&' + this.name + '=' + this.value,
success: function (data) {alert('ok');}
});
});
Your ajax call is working perfectly. You have few conceptual error with your code -
form.serialize() will not attach submit button's info.
If you want to clear your form, you can do it using something like this
$('#resetForm').click(function(){
$('.ajax_form')[0].reset();
});
Lastly complete your task & return success or failed value to ajax call using echo like echo 'successful' or echo failed etc. Use an else condition with your code. It will be more clearer to you.
Remove the "action" and "method" attributes from the form. You shouldn't need them.
I'm using the following form to add a product to the opencart shopping cart. The problem I'm having is that after the product adds it doesn't redirect to the shopping cart but just shows a page with a product successfully added notification.
here's the form:
<form action="purchase/?route=checkout/cart/add" id="addToCartForm" method="post">
<input type="hidden" name="product_id" value="40">
<input type="hidden" name="quantity" id="quantity_field" value="">
<input type="hidden" name="price" value=>
<input type="submit" alt="Order Now" title="order now" value="Order Now test">
</form>
and the javascript code:
<script>
$(document).ready(function() {
$('form#addToCartForm input[type="submit"]').click(function(e) {
e.preventDefault(); // prevent the form from submitting
$.ajax({
type: 'POST',
dataType: 'json',
url: 'purchase/index.php?route=checkout/cart/add'
data: 'product_id=' + $('form#addToCartForm input[name="product_id"]').val() + '&quantity=' + $('form#addToCartForm input[name="quantity"]').val(),
success: function(json) {
window.location = 'purchase/index.php?route=checkout/cart';
console.log('add success');
}
});
});
});
</script>
after the form is clicked the page redirects to http://*****/purchase/?route=checkout/cart/add and the page message reads "{"success":"Success: You have added Product Name</a> to your shopping cart</a>!","total":"4 item(s) - \u00a64.40"}"
So, it does add a product, but the redirect upon 'success' doesn't seem to do anything.
the javascript console doesn't output anything with console.log('add success'); (or it moves to the shopping cart add page too quickly to see)
thanks for any help
First remove action attribute from form, its not required (and may cause confusion in debugging)
and then use following javascript
$('form#addToCartForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'purchase/index.php?route=checkout/cart/add'
data: 'product_id=' + $('form#addToCartForm input[name="product_id"]').val() + '&quantity=' + $('form#addToCartForm input[name="quantity"]').val(),
success: function (json) {
window.location = 'purchase/index.php?route=checkout/cart';
console.log('add success');
}
});
});
in your question part of your ajax requested is commented out, is it really the case or it just got commented while posting to SO ?
I'm not sure where the element with ID 'personalVirtualPrivateServerForm' is from, but clicking a button doesn't necessarily allow you to perform the e.preventDefault() you are attempting.
In your case, you are essentially saying, on click of the button perform an action, but you want to say something like:
$('form#addToCartForm').submit(function(e) {
e.preventDefault();
.... (rest of code here) ....
});
Basically, your form is submitting before you have a chance to redirect, when you want to stop the form submission and then send it via your $.ajax submit. That should allow your success callback to execute.
I have a login popup that will pop up on every page of my site. What I want to do is once the user clicks submit, to have a single JS file where the jQuery code for handling that request lives, and makes an AJAX call to validate the parameters in the DB.
I am able to get the pop up box to pop up. And the form loads. I am thinking my jQuery code will live in a separate imported file and look like this:
<script type="text/javascript" >
$(function()
{
$("input[type=submit]").click(function()
{
var some_params= $("#param").val();
var dataString = 'Some url to send to ajax';
if( params validated ok )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "/problems/add_problem.php",
dataType: "json",
data: dataString,
success: function(json)
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
So my question is how do I make this get invoked only when the right form is submitted? The form would have some id="some_name" but I don't really understand how to make this jQuery code get executed only when that form element is called.
And here is the form I am calling to display in the popup:
<?php
echo '<div id="login_div">
<form id="login_form" method="post" action="">
<p>
<label for="name"><span>Your Email:</span></label> <input type="text" name="email" />
</p>
<p>
<label for="name"><span>Your Password:</span></label> <input type="password" name="user_pass">
</p>
<p>
<input type="submit" value="Log In" />
</p>
</form>
</div>
<p>
Create Account | Reset Pass
</p>
';
?>
and here is the problemio.js contents with the jQuery to handle the login form submit:
// javascript library
// login_form
$(function()
{
$("#login_form input[type=submit]").click(function()
{
console.log("test");
alert("1");
// var name = $("#problem_name").val();
// var problem_blurb = $("#problem_blurb").val();
// var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb;
// if(name=='' || problem_blurb == '')
// {
// $('.success').fadeOut(200).hide();
// $('.error').fadeOut(200).show();
/// }
// else
// {
// $.ajax({
// type: "POST",
// url: "/problems/add_problem.php",
// dataType: "json",
// data: dataString,
// success: function(json)
// {
// $('.success').fadeIn(200).show();
// $('.error').fadeOut(200).hide();
//
/// // Here can update the right side of the screen with the newly entered information
// //alert (json);
//
// new_string = "<h2>Most Recently Added Problems</h2>";
// Have to figure out how to make this work with the DOM.
// }
// });
// }
return false;
});
});
Two things. First, when you place the code above into a separate javascript file, be sure to remove the <script ..> and </script> HTML tags.
Next, alter the following line:
$("input[type=submit]").click(function()
To instead say:
$("#loginform input[type=submit]").click(function()
And then set id="loginform" on your <form> tag.
You can use .submit() to attach a handler to the form submit event. First you'll need to select your form via the id:
$("#some_form_id").submit(function() {
// the code you have in the click event above goes here.
});
You can specific the form you want to trigger the jquery. http://api.jquery.com/submit/
If you are not sure, just right-click this webpage and read its html code.
<script type="text/javascript" src="some.js"></script>
And also, binding the the function to form.submit is much better than to the submit button.
$('formid').submit(function(){blablabla;return false;})
If you would like to handle the click event for every submit on the page without using ids, you can always use the this keyword in the click event to find the sender and then find the parent form.