0

How can I use JSON-like variable in my function like this?

$.ajax({
      type:"POST",
      -->data:{this_var:this_value}
     });
2
  • Where is your function? Commented Mar 16, 2015 at 12:36
  • No, no, DON'T BEGIN ALL OF YOUR WORDS WITH UPPERCASE!!!!!!!!!!!!!! Commented Mar 16, 2015 at 12:44

3 Answers 3

1

Use JSON.stringify() to create JSON object.

$.ajax({
        type: "POST",
        url: urlAction,
        dataType: "json",
        contentType: "application/json",
        data: JSON.stringify({variable1: value1, variable2: value2})
      });
Sign up to request clarification or add additional context in comments.

Comments

0

Your code:

$.ajax({
      type:"POST",
      -->data:{this_var:this_value}
     });

Then to use the object as you mentioned would be:

var myObj = {this_var:this_value};
myObj.this_var();

That is if this_var is a function. Otherwise the value can be consumed such as:

var myObj = {this_var:this_value};
var myVal = myObj.this_var;

You may also need to pass the data in as a string and then parse it as JSON after getting the string from the ajax call.

var myObj = JSON.parse(data);
var myVal = myObj.this_var(); // if this is a function

Comments

0

Try this

formData = {
    param1: $("#param1").val(),
    param2: $("#param2").val()
}
$.ajax({
    type: "POST",
    url: "http://example.com/create.php",
    data: formData,
    dataType: "json",
    success: function(data) {
        alert("Add success");
    },
    error: function() {
        alert("Add failure");
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.