Displaying search result from the form using jquery and ajax

I have simple form and script which takes input data and calls rotten tomatoes API and displays results. If I don't use $('#submitid').click(function() and var query is hard coded results are displayed fine. If I just use $('#submitid').click(function() {}) in conjunction with alert, form data is displayed. However in current state nothing is displayed. Any help is appreciated.

<form action="">
    <input  type="text" id='myid' />
    <input value="Search" type="submit" id="submitid" />
</form>

<script>
    $('#submitid').click(function () {
        var query = $('#myid').val();
        var apikey = "my_api_key_sample";
        var baseUrl = "http://api.rottentomatoes.com/api/public/v1.0";

        // construct the uri with our apikey
        var moviesSearchUrl = baseUrl + '/movies.json?apikey=' + apikey;

        $(document).ready(function () {
            // send off the query
            $.ajax({
                url: moviesSearchUrl + '&q=' + encodeURI(query),
                dataType: "jsonp",
                success: searchCallback
            });
        });

        // callback for when we get back the results
        function searchCallback(data) {
            $(document.body).append(
                'Found ' + data.total + ' results for ' + query
            );
            var movies = data.movies;
            $.each(movies, function (index, movie) {
                var mydata += //code for appending my data 
            });

            //displaying mydata on div with id result
            $('#result').html(mydata);
        }
    })
    })
</script>

Upvotes: 0

Views: 2905

Answers (2)

darshanags
darshanags

Reputation: 2519

Try:

HTML:

<form action="" id="someform">
    <input  type="text" id='myid'>
    <input value="Search" type="submit" id="submitid">
</form>

jQuery:

$(document).ready(function() {

    $("#someform").submit(function(){
        $.ajax({
            url: moviesSearchUrl + '&q=' + encodeURI(query),
            dataType: "jsonp",
            success: searchCallback
        });
        return false;
    });

});

Upvotes: 1

James Coyle
James Coyle

Reputation: 10398

var mydata += //code for appending my data

You need to actually finish this line or comment it out completely. Also, at the end you have } }) }) which should be } });.

Upvotes: 0

Related Questions