Question

my php create each product by echo on the end is

<form name="addToCartForm">
<input type="hidden" id="inputid" value="'.$id.'"/>
<input type="submit" id="submitbutton" value="Add to cart"/>
</form>

on the website usually is created 10 products dynamicly

So I have 10 buttons with same class or id for each product displayed by php

any idea for a function to send data to cart.php file by post (jquery) without refreshing website. I must send proper id of product in $_POST so cart.php know what have been added.

AND WHY when I added

$(document).ready(function(e) {
    $('#submitbutton').click(function(e) {
        var pos = $('#inputid').val();
        alert(pos);
        return false;
    });
});

it is working to alert just first button ADD to CART not all

I am new to jquery:)please help

Was it helpful?

Solution

It sounds like you're looking for AJAX functionality. Luckily, jQuery has a function for AJAX calls, described at http://api.jquery.com/jQuery.ajax/.

You can then write some code as follows:

$(document).ready(function() {
    $('#submitbutton').click(function() {
        var pos = $('#inputid').val();
        $.ajax({
            url: "cart.php",
            type: "POST",
            data: {itemID: pos},
            success: function(data) {
                // Do stuff when the AJAX call returns
            }
        });
    });
});

However, there is a flaw with this. If you're going to have multiple submit buttons on the same page, you cannot use the same ID for all of them. It is better to give all of the fields a class as follows:

<form name="addToCartForm">
    <input type="hidden" class="inputid" value="'.$id.'"/>
    <input type="submit" class="submitbutton" value="Add to cart"/>
 </form>

Your final Javascript code will look like this:

$(document).ready(function() {
    $('.submitbutton').click(function() {
        var pos = $(this).parent().find('.inputid').val();
        $.ajax({
            url: "cart.php",
            type: "POST",
            data: {itemID: pos},
            success: function(data) {
                // Do stuff when the AJAX call returns
            }
        });
    });
});

OTHER TIPS

You can't have more than one element with same id. Try adding a class something like this,

<form name="addToCartForm">
  <input type="hidden" id="inputid_1" class="inputid" value="'.$id.'"/>
  <input type="submit" id="submitbutton_1" class="submitbutton" value="Add to cart"/>
</form>

JS code should be,

$(document).ready(function(e) {
   $('.submitbutton').click(function(e) {
    var pos = $(this).parent().find('.inputid').val();
    alert(pos);
    //Do your AJAX call here to send data to server.
    return false;
  });​
});

Demo: http://jsfiddle.net/meqY5/1/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top