Reputation: 3652
I am using the jQuery Ajaxy plugin: http://balupton.com/projects/jquery-ajaxy
Is there a way to add POST parameters to each Ajaxy request?
Upvotes: 6
Views: 28322
Reputation: 500
I know it was 10 years ago but i must write this to here.
The only solution that worked for me is to add the param(s) to the ajax url. I did it like this:
let param = "abc";
$.ajax({
type: 'POST',
url: `/test?myParam=${param}`,
data: { abc: 123 },
success: function(resp) { }
});
If you want to add multiple params you can separate with the end mark like this:
let param = "abc";
let param_2 = "cba";
$.ajax({
type: 'POST',
url: `/test?myParam=${param}&myParam_2=${param_2}`,
data: { abc: 123 },
success: function(resp) { }
});
Here is an array version for multiple params:
let params = ["asd","foo","bar","etc.."];
let url = "/test?";
for (const [index, param] of params.entries()) {
url += `myParam_${index}=${param}&`;
}
// Remove last & char from the url
url = url.substring(0, url.length - 1);
$.ajax({
type: 'POST',
url: url,
data: { abc: 123 },
success: function(resp) { }
});
// Output for the url: "/test?myParam_0=asd&myParam_1=foo&myParam_2=bar&myParam_3=etc.."
Upvotes: 0
Reputation: 3948
According http://visualjquery.com you can also go this way:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Upvotes: 3
Reputation: 22395
One of the best ways is to use $.param()
-- for a simple example -- using a voting system to vote up/down a comment;
<div class="comment_container">
<div class="vote_container" comment_id="321">
<a href="javascript:" class="vote vote_up">Up +1</a>
<a href="javascript:" class="vote vote_down">Down -1</a>
</div>
<p>Hello, this a comment!</p>
</div>
<script type="text/javascript">
$('.vote').click(function() {
var voteUpOrDown = $(this).hasClass('vote_up') ? 1 : 0;
var id = $(this).parent().attr('comment_id');
$.ajax('/form/rating', {
type: 'post',
data: $.param({ vote: voteUpOrDown, id: id }),
success: function(data) { }
});
});
</script>
Upvotes: 1
Reputation: 318508
You can use $.ajaxSetup()
to set default options - including (GET/POST) data.
$.ajaxSetup({
data: { foo: 'bar' }
});
These data will be merged with your data specified in the $.ajax()
call.
$.ajax({
type: 'POST',
url: '/test',
data: { abc: 123 },
success: function(resp) { }
});
This will send both foo
and abc
.
You can also move other options like type: 'POST'
into your defaults so you don't have to specify it everytime.
Upvotes: 12