2

I need to pass JSON data to a server. Data looks like this:

{"method":"like","data":{"type":1,"id":123}}

I need it to be done automaticaly, if I would use a form it can be done like this:

<script>
jQuery(document).ready(function(){
jQuery("#form").submit();
});
</script>

But I need to pass data using $_POST in that exact format. How can this be done?

3
  • Pass it to a server from what? JSON is just a string, you can just pass the string in a single post field. Commented Oct 24, 2011 at 23:49
  • Do you have user input from a form, or are you creating the data programmatically? Commented Oct 24, 2011 at 23:50
  • @tandu I need to pass a string like that to domain.com/script.php so I could know user has the page loaded. Also I need to do this automatically, can you tell me how to do that? Commented Oct 25, 2011 at 0:06

1 Answer 1

2

see jquery's load() or better (post() if you don't need to load anything to the page you're working on) to pass the json object with POST

If you don't know how to convert a string/array to json, use phps json_encode

Example:

$(document).ready(function(){
    $.post("script.php", { <?php echo $string; ?> },
       function() {
         alert("Your test.php page received the string!);
       });
});

That way the $string gets loaded automatically when the page is loaded (if user has javascript turned on).

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

6 Comments

Why .load()? The OP doesn't indicate that they want to load any of the server response into the DOM.
@nrabinowitz I need to pass a string like that to domain.com/script.php so I could know user has the page loaded. Also I need to do this automatically, can you tell me how to do that?
OK, got it so far, but why doesnt this work? <script>$(document).ready(function(){ $.post("http://www.domain.com/app.php", {"method":"like","data":{"type":1,"id":233725822}}, function(data) { alert("Data Loaded: " + data); }); }); </script> if there is just script.php it works, if i display other domain, then not
thats because jquery doesnt allow cross site scripting. there are a few workaround/hacks for this 'problem' though. for examples look here and there
@danontheline can you give me an example how can I make a JSONP call? Just like the one you posted earlier just for another domain.
|

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.