Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery $.ajax jsonp

$.ajax({
    type : "GET",
    dataType : "jsonp",
    url : '/',
    data : {}
    success: function(obj){

    }
});

How can i use $.ajax dataType: jsonp cross-domain to post data?

like image 767
Thinking80s Avatar asked Aug 26 '11 09:08

Thinking80s


People also ask

Can JSONP be used with Ajax?

JSONP has nothing to do with Ajax, since it does not use XMLHttpRequest. Instead, it dynamically inserts <script> tag into a webpage.

What is JSONP in Ajax?

JSONP stands for JSON with Padding. Requesting a file from another domain can cause problems, due to cross-domain policy. Requesting an external script from another domain does not have this problem. JSONP uses this advantage, and request files using the script tag instead of the XMLHttpRequest object.

What is difference between JSON and JSONP?

JSONP is essentially, JSON with extra code, like a function call wrapped around the data. It allows the data to be acted on during parsing.

Can I make Ajax requests by jQuery?

jQuery ajax() Method. The jQuery ajax() method provides core functionality of Ajax in jQuery. It sends asynchronous HTTP requests to the server.


2 Answers

To answer your question instead of sending you to another link like above:

The JS:

$.ajax({
     type : "GET",
     dataType : "jsonp",
     url : "http://domainname.com/json.php?callback=?", // ?callback=?
     success: function(data){
           // do stuff with data
     }
});

The PHP could possibly look like this:

<?php
include('connect.php');
$sql = "SELECT id, name, items FROM tablename ORDER BY id ASC"; 
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
    $rows[] = array(
            "id" => $row['id'], 
            "name" => $row['name'], 
            "items" => $row['items']);
}
$json = json_encode($rows);
$callback = $_GET['callback'];
echo $callback.'('. $json . ')';
?>

Setting the dataType to jsonp will allow jQuery to automatically add an extra ?callback=? to the end of your url to specify the callback. If you specify your own like above it will use the callback name you are passing. If you need to specify a json callback name use the jsonpCallback property. Or you can add as a param to the data property. If you need more info, please visit the jQuery API Ajax: http://api.jquery.com/jQuery.ajax/.

Don't forget to add the ; on the result string.

I hope this helps!

like image 58
Jonathan Marzullo Avatar answered Sep 20 '22 19:09

Jonathan Marzullo


It's not possible with simple jsonp. Read this

like image 29
genesis Avatar answered Sep 20 '22 19:09

genesis