0
var itemsObj = new Object();
itemsObj.data = "Something";
$.post("somewhere.php", itemsObj, function(data) {}, "html");

Normally, as stated in the API, I'd use { data: "something" } where itemsObj is, but since my object is dynamic and requires a for-loop, I didn't want to get too 'dirty' with a for loop within the data: ... part...

Anyways, the code I wrote above doesn't work. I think maybe I should've apply the JSON.stringify() function on it, correct if I'm wrong?

2
  • 2
    What does the server want? A JSON-string? URL-encoded key-value pairs? Commented Jul 9, 2012 at 12:13
  • Can you clarify 'doesnt work'? What do you see in the network requests section of your dev tools? How about on your backend? Commented Jul 9, 2012 at 12:13

2 Answers 2

3

Add data to itemsObj like this...

var itemsObj = {};

itemsObj['Firstdata'] = "Something";
itemsObj['Seconddata'] = "Something else";

etc... You can use looping to do that...

Then post using $.post("somewhere.php", itemsObj, function(data) {}, "html"); and it should work...

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks. Seems like obj.['something'] doesn't work so I had to change it to obj['data'], then I tried sending the object to the other page, but that didn't work either. Normally I'd send it as { data: "something" } and access it like that $_POST['data'], what's different now?
Thanks. How'd I send/receive the object though? I tried looking at @Engineer's answer, look's reliable thought I do I access data for example? :P
@xTCx the above thing will do exactly that when you post itemsObj above it will post something like {"Firstdata":"Something","Seconddata":"Something else"} which is a valid JSON object and you can access it via $_POST["Firstdata"]
@xTCx you send using $.post("somewhere.php",itemsObj, function(data){},"html"); :)
ah! okay yeah there was actually a typo in my code ;) Thank you!! :D
|
1

You can use JSON:

$.post("somewhere.php", "param="+JSON.stringify(itemsObj), function(data) {}, "html");

Then in server side:

$obj = json_decode($_POST["param"]);

5 Comments

You're assuming that he's using PHP for his backend.
Yes, I am assuming that, look at the question.There is "somewhere.php" mentioned as post's URL.
@MisterJack I am assuming also, that your downvote is irrelevant.
+1 @Engineer : Dont worry about downvoting,Anonymous downvoting has became like a virus in SO
@user1042031 It is not anonymous in this case:)

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.