Retrieve JSON GET data with Javascript/JQuery

12,242

Solution 1

It seems that this service is not correctly wrapping the JSON object in parentheses so it doesn't work as JSONP.

See: http://www.entertainmentcocktail.com/cp/index.php?area=AB12&jsoncallback=TEST

It returns:

TEST[{"id":"5","name":"The Red Lion", ... ,"confirmed":"0"}]

while it should return:

TEST([{"id":"5","name":"The Red Lion", ... ,"confirmed":"0"}]);

You won't be able to use it because it is not valid JSONP.

UPDATE:

Answering more info from the comment - if you control the server-side script then try changing:

while($row = mysql_fetch_assoc($result)) { $records[] = $row; }
echo $_GET['jsoncallback'] . json_encode($records);

to:

while($row = mysql_fetch_assoc($result)) { $records[] = $row; }
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';

and see if that works.

UPDATE 2:

Answering another comment. Do you actually initialize the output variable? For example with something like this at the beginning:

var output = $('#place').append('<div/>');

Do you actually call your results function? It must be called with:

results();

or registered somewhere as an event handler, using the jQuery way:

$('form').submit(results);

but then add:

return false;

to the end of the results function to prevent the page from being reloaded.

See this demo: http://jsbin.com/uziyek/1/edit - it seems to work.

Another problem:

There seems to be another problem with your code, that the area=AB12 parameter is hardcoded into your URL. What you should do instead is get the value from the form and send that.

Solution 2

You implemented JSONP incorrectly. You need to generate a function call, i.e. the response should be foo(<json here>); not foo<json here>.

It is trivial to fix:

echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';

Another problem is that you are not preventing the form submission, i.e. when you submit the form, the page refreshes. You have to prevent that. Better bind the event handler with jQuery and don't use inline event handlers:

<form id="myForm">

and

$(function() {
    $('#myForm').submit(function(event) {
        event.preventDefault(); // <-- prevent form submission
        // Ajax call here
    });
});

DEMO

Share:
12,242
Ben
Author by

Ben

Web developer and designer, working in HTML5, PHP and CSS3.

Updated on June 25, 2022

Comments

  • Ben
    Ben almost 2 years

    What I am trying to do is retrieve JSON data from an online web service that searches and finds a certain string in a MySQL database and display it using Javascript on an HTML page.

    What I am struggling with is actually displaying the resulting data.

    The relevant areas of my HTML page looks like this:

    <form onSubmit="results()">
        <fieldset>
            <label for="area">First digits of postal code:</label>
            <input name="area" type="text" maxlength="4" placeholder="AB12" required />
            <input type="submit" value="Search" name="search" />
        </fieldset>
    </form>
    
    
    
    <script type="text/javascript" src="jquery/jquery.min.js"></script>
    <script type="text/javascript" src="cordova-2.3.0.js"></script>
    <script type="text/javascript" src="js/index.js"></script>
    <script type="text/javascript">
    
    function results(){
        $.ajax({
            url: 'http://www.foobar.com/cp/index.php?area=AB12',
            dataType: 'jsonp',
            jsonp: 'jsoncallback',
            timeout: 5000,
            success: function(data, status){
                $.each(data, function(i,item){
                    var place = '<h1>'+item.location+'</h1>'
                    + '<p>'+item.id+'</br>';
    
                    output.append(place);
                });
            },
            error: function(){
                output.text('There was an error loading the data.');
            }
        });
    };
    </script>
    
    <div id="place">
    <h3>Places near your location</h3>
    </div>
    

    The page for the GET data is http://www.foobar.com/cp/index.php with the search variable 'area'. Test sample is ?area=AB12.

  • Ben
    Ben about 11 years
    How can this be done? The code on the web service is: while($row = mysql_fetch_assoc($result)) { $records[] = $row; } echo $_GET['jsoncallback'] . json_encode($records); - is there something here that can be changed?
  • Ben
    Ben about 11 years
    Yes this is what I have done, character for character (see here). However, my client code still isn't presenting anything whatsoever.
  • Ben
    Ben about 11 years
    Okay this is complete but there is no change at all - there is nothing being displayed on my HTML page, still.
  • Ben
    Ben about 11 years
    Thanks so much for your help. I'm trying to get that to work but is there a syntax error on the line that says $('#search').submit(event){?
  • Felix Kling
    Felix Kling about 11 years
    @Ben: Fixed and added a DEMO: jsfiddle.net/fkling/AKEPX. If you are not very familiar with jQuery, I really recommend to read the tutorial first: docs.jquery.com/Tutorials:Getting_Started_with_jQuery.
  • Ben
    Ben about 11 years
    Thanks again for being so patient. I have updated the code and pasted it here but there is still no update to the page whatsoever.
  • Felix Kling
    Felix Kling about 11 years
    Probably because you did not define output. Have a look at my demo, try to understand it. It works, so it contains all you need to know.
  • Ben
    Ben about 11 years
    Thanks for all your help!!