kristen
kristen

Reputation: 488

How do I set post variables dynamically?

I am making a post call and want to set the paramaters I send dynamically through some if/else statements. The following simplified version doesn't work but if I change '{postvars}' to '{n: n}' then it does, even though they're equivalent, right?

<html>
<head>
<title></title>
<script type="text/javascript" src="jquery-1.7.1.js"></script>
<script type="text/javascript">
   $(document).ready(function () {

   $("#clicky").click(function () {
     var postvars; var mydata;
     var n = 'dave';
     postvars = 'n: ' + n;

      $.post("test.php", 
     {postvars}, 
      function(data){
          }, 
        "text"
        );  

$("#test").text(postvars);

  });
   });
</script>
</head>
<body>

<div id='clicky'>click here</div>
<div id='test'></div>

</body>


</html>

Upvotes: 1

Views: 9452

Answers (3)

jlledom
jlledom

Reputation: 650

If you are getting the variables for a form, you can use the serialize() function, in order to get a parameter string. http://api.jquery.com/serialize/

If you want to get the parameter string from an object, you must use the $.param() function: http://api.jquery.com/jQuery.param/

Like this:

function someFunc() {
    var obj=new Object();
    obj.n=1;
    obj.str="Hello!";

    var dataStr=$.param(obj);
   //dataStr is now "n=1&str=Hello!"
}

Upvotes: 0

Patrick Evans
Patrick Evans

Reputation: 42736

{postvars} and {n: n} are not equivelent,

{postvars} will be seen to javascript as an object initalizer, and will error out as postvars just a string which can not set the attributes/values of an object by itself.

{n: n}, however is a proper object initalizer as it gives name and value

jquery ajax functions take either a name value pair string,

  $.post("test.php", 
         "data=somedata&moredata=thisdata", 
         function(data){
         }, 
         "text"
  );  

or a json object,

var newData = "Some new data";
var data = {
     "dataname":"datavalue";
};

//add dynamic variables to object
data["newData"] = newData;

$.post("test.php", 
       data, 
       function(data){
       }, 
       "text"
 );  

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1038890

Try like this:

// define an empty object
var data = { };

var variableName = 'n';
var variableValue = 'dave';

// assign properties of the data object dynamically
data[variableName] = variableValue;
...

and then post this data variable that you have built dynamically:

$.post("test.php", data, function(result) {
    alert(result);
}, "text");

Upvotes: 2

Related Questions