0

I need to make a json request with the url structure like : site.com/page?id=123

How do I pass the variable through the request and then return the results to the page?

    <input type='text' id='theInput'>
    <input onclick='getIt(); return false;'  />
    <div id="results"></div>
    <script>
        function getIt(){
        var x = ($j('#theInput').val() );
        $j.getJSON("http://site.com/page?id=", 
          {
        //how do i append x to request?
          },
        );
        }
    </script>
2
  • Is http://site.com/page your site or a third party site? If the latter you will run into same-origin-policy issues. Commented Nov 23, 2010 at 9:27
  • I am hoping to run two processes like this... one is same site, the other is a sub domain of the site. Would I have to use JSONP ? Commented Nov 23, 2010 at 16:15

1 Answer 1

1

Try like this:

var id = $j('#theInput').val();
$j.getJSON('http://site.com/page', { id: id }, function(result) {
    // success
});

Also I would recommend you using unobtrusive javascript:

<input type="text" id="theInput" />
<input type="button" id="btn" value="Click me" />
<div id="results"></div>

And then in a separate javascript file:

$(function() {
    $('#btn').click(function() {
        var id = $j('#theInput').val();
        $j.getJSON('http://site.com/page', { id: id }, function(result) {
            // manipulate the results
        });
        return false;
    });
});

Also you should make sure that you respect the same origin policy or your AJAX request might not work. Verify that http://site.com/page is the same domain as the one that hosts the page sending the AJAX request. If this is not the case you could configure your server to send a JSONP response.

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

3 Comments

Thanks Darin! Would I have to use JSONP if I am sending it to a subdomain?
Look at the table in the same origin policy article. In which case are you?
Sweet this works! I can see it in the get request. Can you please explain to me a bit more how I manipulate the results to show in the #results div?

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.