A simple example of jQuery, PHP, and JSONP?

I ran into a policy issue of the same origin, and while researching this issue, I found that the best way for my specific project would be to use JSONP to execute cross origin requests.

I read this IBM article about JSONP , but I don’t 100% understand what is going on.

All I ask here is a simple jQuery> PHP JSONP request (or whatever the terminology;)) is something like this (obviously this is not true, you can just get an idea of ​​what I'm trying to achieve: )) :

JQuery

$.post('http://MySite.com/MyHandler.php',{firstname:'Jeff'},function(res){ alert('Your name is '+res); }); 

PHP:

 <?php $fname = $_POST['firstname']; if($fname=='Jeff') { echo 'Jeff Hansen'; } ?> 

How would I decide to convert this to the correct JSONP request? And if I were to store HTML in the return result, would that work too?

+52
json jquery jsonp ajax php
Jul 24 '11 at 19:16
source share
7 answers

When you use $ .getJSON in an external domain, it automatically executes a JSONP request, for example, <http://smallcoders.com/javascriptdevenvironment.html to see it in action)

 //JAVASCRIPT $.getJSON('http://www.write-about-property.com/jsonp.php?callback=?','firstname=Jeff',function(res){ alert('Your name is '+res.fullname); }); //SERVER SIDE <?php $fname = $_GET['firstname']; if($fname=='Jeff') { //header("Content-Type: application/json"); echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')'; } ?> 

Pay attention to? callback =? and + res.fullname

+89
Jul 24 '11 at 19:20
source share

First of all, you cannot make a POST request using JSONP.

What basically happens is that a script tag has been dynamically added to load your data. Therefore, only GET requests are possible.

In addition, your data should be wrapped in a callback function, which is called after the request is completed to load the data into a variable.

The whole process is handled by jQuery for you. Just using $ .getJSON in an external domain does not always work. I can talk about personal experiences.

Best to add & callback =? to you url.

On the server side, you need to make sure your data is wrapped in this callback function.

t

 echo $_GET['callback'] . '(' . $data . ')'; 

EDIT:

I don’t have enough reviews to comment on Liam’s answer, so the solution is here.

Replace Liam Line

  echo "{'fullname' : 'Jeff Hansen'}"; 

from

  echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')'; 
+19
Jul 24 '11 at 19:25
source share

More offers

JavaScript:

 $.ajax({ url: "http://FullUrl", dataType: 'jsonp', success: function (data) { //Data from the server in the in the variable "data" //In the form of an array } }); 

PHP CallBack:

 <?php $array = array( '0' => array('fullName' => 'Meni Samet', 'fullAdress' => 'New York, NY'), '1' => array('fullName' => 'Test 2', 'fullAdress' => 'Paris'), ); if(isset ($_GET['callback'])) { header("Content-Type: application/json"); echo $_GET['callback']."(".json_encode($array).")"; } ?> 
+12
Mar 12 '14 at 18:37
source share

For the server to respond with a valid JSONP array, wrap the JSON in brackets () and precede callback :

 echo $_GET['callback']."([{'fullname' : 'Jeff Hansen'}])"; 

Using json_encode () , converts a native PHP array to JSON:

 $array = array( 'fullname' => 'Jeff Hansen', 'address' => 'somewhere no.3' ); echo $_GET['callback']."(".json_encode($array).")"; 
+7
Jul 24 '11 at 19:58
source share
 $.ajax({ type: "GET", url: '<?php echo Base_url("user/your function");?>', data: {name: mail}, dataType: "jsonp", jsonp: 'callback', jsonpCallback: 'chekEmailTaken', success: function(msg){ } }); return true; 

In the controller:

 public function ajax_checkjp(){ $checkType = $_GET['name']; echo $_GET['callback']. '(' . json_encode($result) . ');'; } 
0
02 Sep '14 at 12:57 on
source share

Use this.

  $str = rawurldecode($_SERVER['REQUEST_URI']); $arr = explode("{",$str); $arr1 = explode("}", $arr[1]); $jsS = '{'.$arr1[0].'}'; $data = json_decode($jsS,true); 

Now..

use $data['elemname'] to access the values.

send a jsonp request using a JSON object.

Request format:

 $.ajax({ method : 'POST', url : 'xxx.com', data : JSONDataObj, //Use JSON.stringfy before sending data dataType: 'jsonp', contentType: 'application/json; charset=utf-8', success : function(response){ console.log(response); } }) 
0
Dec 09 '16 at 15:45
source share

A simple example of jQuery, PHP, and JSONP is given below:

 window.onload = function(){ $.ajax({ cache: false, url: "https://jsonplaceholder.typicode.com/users/2", dataType: 'jsonp', type: 'GET', success: function(data){ console.log('data', data) }, error: function(data){ console.log(data); } }); }; 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
0
May 28 '18 at 7:19
source share



All Articles