2

I am trying to get some data from a remote location by a JQuery post. It works great when I hardcode the data to post, but doesn't work when I put the JSON in a javascript variable, and then pass it in. As far as I understand, a JSON is just a string, so I'm not sure what the difference is.

so, this works:

$.post( PostURL, {var:"somevalue"}, function( data ) {
  // do something with data
}

but this doesn't:

jsonstring = '{var:"somevalue"}';

$.post( PostURL, jsonstring, function( data ) {
  // do something with data
}

obviously, I'm going to need to send different variables to get the stuff I need, so it can't be hard-coded. What am I doing wrong?

2
  • First example is an object, second is a string. You're not just putting it in a variable, you are changing its type. Commented Aug 19, 2015 at 3:48
  • @spenibus Thanks, didn't realize I had left quotes off the top one, changing the type and accidentally making it work. XD Commented Aug 19, 2015 at 4:10

2 Answers 2

2

Data in post() doesn't take JSON as an argument but an object, which is why the first code works. Your second code is using JSON, which is a string representation of an object rather than an actual object, therefore invalid.

jQuery.post( url [, data ] [, success ] [, dataType ] )

url
Type: String
A string containing the URL to which the request is sent.

data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.

http://api.jquery.com/jquery.post/

Note that while it says that data can take a string, it is of the form key=value&key=value.

You don't need JSON, simply store the object in your variable rather than converting it to a string.

var myData = {var:"somevalue"};
$.post(PostURL, myData, function(data) {
    // do something with data
});
Sign up to request clarification or add additional context in comments.

1 Comment

This answer helped me make the cleanest code (no juggling between string and JSON object), and it works. Thanks.
0
jsonstring =  JSON.parse('{var:"somevalue"}');

$.post( PostURL, jsonstring, function( data ) {
  // do something with data
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.