Ajax call php script

Hi

Im making a price calculating tool where i need to
have a php script run in the “background” no refresh.

I have a dynamic page with Add links that call up the list.php and pass two variables

<a href="list.php?action=add&id=23">Add</a>
<a href="list.php?action=add&id=13">Add</a>
<a href="list.php?action=add&id=3">Add</a>
<a href="list.php?action=add&id=65">Add</a>
etc...

Been googling and this is the closest I’ve gotten, it works, but
only with a form button, and i can’t get it to get the id from the button

<script type="text/javascript">
$(document).ready(function() {
$('#AddMe').on('click', function () {
$.ajax({ url: 'cart.php?id=6',
         data: {action: 'add'},
         type: 'get',
         success: function(output) {
                      //alert(output);
                  }
});
    });
});</script>

does anyone have an idea how to solve this, and preferably using “a href” style button/link?

thx

br

Silverviper

Hi silverviper,

If I understood correctly, this should do what you want:


<a class="calcAdd" href="list.php?action=add&id=23">Add</a>
<a class="calcAdd" href="list.php?action=add&id=13">Add</a>
<a class="calcAdd" href="list.php?action=add&id=3">Add</a>
<a class="calcAdd" href="list.php?action=add&id=65">Add</a>

<script type="text/javascript">
    $('.calcAdd').on('click', function(e){
        $.get(this.href, function(data){
            console.log(data);
        })
    });
</script>

Hi

Thx for the reply,

its not quite what i needed,
I need the list.php to be call as a background task so that the “main.php”
doesn’t have to reload.

the list.php is sort of a shopping cart embedded in the top section of main.php

<script type="text/javascript">
$(document).ready(function() {
   $('#list').load('list.php', function() {
   });
});
</script>
<div id="list"></div>

Silverviper

Ah, sorry, I misunderstood… so there would only be one link like this on the page:

<a href="list.php?action=add&id=23">Add</a>

and clicking the link will load the contents of list.php into <div id="list"></div> on the main page, is that correct?

hi

sorry for the confusion .)

the <div id=“list”></div> on the main.php will display all added items

main.php is dynamic and the number of links will vary

have a look here to get the idea http://silverviper.org/calc/calcs.php

Chris

OK, so this should do it:

$('.calcAdd').on('click', function(e) {
    e.preventDefault();
    $('#list').load(this.href);
});
$('.calcAdd').on('click', function(e) {
    e.preventDefault();
    $('#list').load(this.href);
});
<a class=\\"calcAdd\\" href=\\"cart.php?action=add&id=".$id."\\">Add</a>

this still redirects to the cart/list script

Chris

this solved my problem

<script type="text/javascript">
$(document).ready(function() {
$('.calcAdd').on('click', function(e) {
    e.preventDefault();
    $('#cart').load(this.href);
	   });
});
</script>

thx fretburner :slight_smile: