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?

Treat
  • 182
  • 1
  • 6
  • 15
  • Pass it to a server from what? JSON is just a string, you can just pass the string in a single post field. – Explosion Pills Oct 24 '11 at 23:49
  • Do you have user input from a form, or are you creating the data programmatically? – nrabinowitz Oct 24 '11 at 23:50
  • @tandu I need to pass a string like that to http://www.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? – Treat Oct 25 '11 at 00:06

1 Answers1

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).

Anonymous
  • 3,679
  • 6
  • 29
  • 40
  • Why `.load()`? The OP doesn't indicate that they want to load any of the server response into the DOM. – nrabinowitz Oct 24 '11 at 23:57
  • @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? – Treat Oct 25 '11 at 00:06
  • OK, got it so far, but why doesnt this work? `` if there is just script.php it works, if i display other domain, then not – Treat Oct 25 '11 at 01:05
  • thats because jquery doesnt allow cross site scripting. there are a few workaround/hacks for this 'problem' though. for examples look [here](http://jquery-howto.blogspot.com/2009/04/cross-domain-ajax-querying-with-jquery.html) and [there](http://stackoverflow.com/questions/727183/can-jquery-ajax-call-external-webservice) – Anonymous Oct 25 '11 at 02:41
  • @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. – Treat Oct 25 '11 at 13:18
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/4505/discussion-between-treat-and-danontheline) – Treat Oct 25 '11 at 14:37