
How to pass dynamic key in jquery ajax?
AJAX is termed as Asynchronous Javascript And XML.Generally, we use following methods in ajax, jquery
- $.post
- $.ajax
In this tutorial, we will learn to pass dynamic key in both ajax method
1. $.post method
In this method, generally we use following code for ajax
$.post(url,{id_key:id_value,action:'add'}, function(data) { console.log(data) })
Here id_value will be considered as variable whereas id_key will be considered as static. If you pass any dynamic value for id_key, it would not be considered.
Solution:
To use id_key as dynamic use it within a square bracket. You can use following code for it
var id_key='id'; var id_value=12; $.post(url,{[id_key]:id_value,action:'add'}, function(data) { console.log(data) })
2. $.ajax
In this method, generally we use following code for ajax
$.ajax({ method: "POST", url: "abc.php", data: {id_key:id_value, action: 'add'}, }) .done(function(data) { console.log(data); })
Here, id_value can be assigned dynamic values but id_key will remain static. To make id_key as dynamic, use it within square bracket. You can use following code for it.
var id_key='id'; var id_value=12; $.ajax({ method: "POST", url: "abc.php", data: {[id_key]:id_value, action: 'add'}, }) .done(function(data) { console.log(data); })
We need your support to operate it properly. We have lots of ideas but less fund, so help us with your funding.
A perfection of means, and confusion of aims, seems to be our main problem
Do you want to sell products online with no extra cost?
Send your details, our executive will contact you