Zac
Zac

Reputation: 12836

Set variable as property in a JSON request with jQuery

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>

Upvotes: 0

Views: 325

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038820

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.

Upvotes: 1

Related Questions