Say I have the following, and that I got the IDs dynamically.
<div class="search_results">
<p>user 1 <a href="phpfile.php?id=3">Add</a></p>
<p>user 1 <a href="phpfile.php?id=4">Add</a></p>
</div>
If I didn't use ajax, I could catch the passed values in phpfile.php
with $_GET['id']
, but how can I use that with jquery?
$.ajax({
type: 'GET',
url: 'phpfile.php', // how to add those values here?
success: function(data) {
// do smth
}
});
You need to add the data parameter:
url: 'phpfile.php',
data: {id: 3}
If you have to take the id from the HTML as displayed:
$('.search_results a').click(function (e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'phpfile.php',
data: {id: $(this).attr('href').match(/id=(\d*)/)[1]},
success: function (data) {
// do something
}
});
});
To facilitate getting the ID easier, put it into a separate attribute so that it can be read directly by JavaScript/jQuery. If this is impossible, then keep your URI the way it is in the href
.
<div class="search_results">
<p>user 3 <a href="phpfile.php" data-user-id="3">Add</a></p>
<p>user 4 <a href="phpfile.php" data-user-id="4">Add</a></p>
</div>
Here, I'm using the data
property of the jQuery ajax object to send the id
parameter. As you can see, the value is grabbed from the data-user-id
attribute of the HTML element.
e.preventDefault()
is to prevent the browser's default action of following the link to the target href
.
$('a[data-user-id]').click(function (e) {
'use strict';
e.preventDefault();
$.ajax({
type: 'GET',
url: $(this).prop('href'),
data: {
id: $(this).attr('data-user-id')
},
success: function (data) {
// do something
}
});
});
Alternatively, you may use a button
element.
url: 'phpfile.php', data: data,
Just retrieve the values from data at your server side code
You can use the below line to get all the data from your form into ajax
var data = $('form').serialize();
The above method can be applied only if you are passing data using html form