Simple jQuery, PHP and JSONP example? - php

I am facing the same-origin policy problem, and by researching the subject, I found that the best way for my particular project would be to use JSONP to do cross-origin requests.
I've been reading this article from IBM about JSONP, however I am not 100% clear on what is going on.
All I am asking for here, is a simple jQuery>PHP JSONP request (or whatever the terminology may be ;) ) - something like this (obviously it is incorrect, its just so you can get an idea of what I am 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 go about converting this into a proper JSONP request? And if I were to store HTML in the result to be returned, would that work too?

When you use $.getJSON on an external domain it automatically actions a JSONP request, for example my tweet slider here
If you look at the source code you can see that I am calling the Twitter API using .getJSON.
So your example would be:
THIS IS TESTED AND WORKS (You can go to 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'}" . ')';
}
?>
Note the ?callback=? and +res.fullname

First of all you can't make a POST request using JSONP.
What basically is happening is that dynamically a script tag is inserted to load your data. Therefore only GET requests are possible.
Furthermore your data has to be wrapped in a callback function which is called after the request is finished to load the data in a variable.
This whole process is automated by jQuery for you. Just using $.getJSON on an external domain doesn't always work though. I can tell out of personal experience.
The best thing to do is adding &callback=? to you url.
At the server side you've got to make sure that your data is wrapped in this callback function.
ie.
echo $_GET['callback'] . '(' . $data . ')';
EDIT:
Don't have enough rep yet to comment on Liam's answer so therefore the solution over here.
Replace Liam's line
echo "{'fullname' : 'Jeff Hansen'}";
with
echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')';

More Suggestion
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).")";
}
?>

To make the server respond with a valid JSONP array, wrap the JSON in brackets () and preprend the callback:
echo $_GET['callback']."([{'fullname' : 'Jeff Hansen'}])";
Using json_encode() will convert a native PHP array into JSON:
$array = array(
'fullname' => 'Jeff Hansen',
'address' => 'somewhere no.3'
);
echo $_GET['callback']."(".json_encode($array).")";

Simple jQuery, PHP and JSONP example is 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>

$.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 controller:
public function ajax_checkjp(){
$checkType = $_GET['name'];
echo $_GET['callback']. '(' . json_encode($result) . ');';
}

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 jsonp request with 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);
}
})

Related

Passing a jQuery array to PHP (POST)

I want to send an array to PHP (POST method) using jQuery.
This is my code to send a POST request:
$.post("insert.php", {
// Arrays
customerID: customer,
actionID: action
})
This is my PHP code to read the POST data:
$variable = $_POST['customerID']; // I know this is vulnerable to SQLi
If I try to read the array passed with $.post, I only get the first element.
If I inspect the POST data with Fiddler, I see that the web server answers with "500 status code".
How can I get the complete array in PHP?
Thanks for your help.
To send data from JS to PHP you can use $.ajax :
1/ Use "POST" as type, dataType is what kind of data you want to receive as php response, the url is your php file and in data just send what you want.
JS:
var array = {
'customerID': customer,
'actionID' : action
};
$.ajax({
type: "POST",
dataType: "json",
url: "insert.php",
data:
{
"data" : array
},
success: function (response) {
// Do something if it works
},
error: function(x,e,t){
// Do something if it doesn't works
}
});
PHP:
<?php
$result['message'] = "";
$result['type'] = "";
$array = $_POST['data']; // your array
// Now you can use your array in php, for example : $array['customerID'] is equal to 'customer';
// now do what you want with your array and send back some JSON data in your JS if all is ok, for example :
$result['message'] = "All is ok !";
$result['type'] = "success";
echo json_encode($result);
Is it what you are looking for?

Call a php function in MVC using AJAX?

I am currently migrating an already built web application to MVC, and I'm figuring out that I'm too newbie to do some kind of changes. There are some ajax calls that are freaking me out. I'll try to be as clear as possible, but due to my inexperience I'm not sure if I won't let some important information by the way.
The point is in the old application, things go this way:
In the php code:
if ($action_user == 'show_alerts') {
$list = array();
$query = "SELECT alert_type FROM alert_contact WHERE NOT
deleted AND user_email=" . typeFormat($email);
$result = mysqli_query($db, $query) or die('Error in query "'.$query . '": ' . mysqli_error($db));
while ($db_field = mysqli_fetch_assoc($result)) {
$list[] = $db_field['alert_type'];
}
echo json_encode($list);
In the jquery code:
$.ajax({
type: 'POST',
url: 'userpost.php',
data: $('#userForm').serialize(),
cache: false,
dataType: 'json'
Here comes my problem, and since I don't have an userpost.php file anymore, I have to send it to the index.php and call my users component by a get petition, which I don't like, but I coudn't find another way to do it. And, what is even worse, I don't know at all how ajax is getting the variables that it needs. It must be a pretty basic mistake, but I recognize my skills at this point are't so good. That's what I'm doing in my version:
In the php code:
if ($action_user == 'show_alerts') {
$list = ModelUser::getAlertContact($act_email);
echo json_encode($list);//I predict that ajax don't reach this line, but not sure
}
In the jquery code:
$.ajax({
type: 'POST',
url: 'index.php?option=users',
data: $('#userForm').serialize(),
cache: false,
dataType: 'json',
success: function(data) {
alert ('gotcha');
$.each(alertsarray, function(index, value) {
if ($.inArray(value, data) === -1) {
$("#sub" + value).prop("checked", false);
$('#alert' + value).removeClass("list_alert_sub");
}
else {
$("#sub" + value).prop("checked", true);
$('#alert' + value).addClass("list_alert_sub");
}
});
},
error: function(data) {
alert("¡Error (ajax)!");
}
});
Any help would be appreciated, and if there's some more information I've missed, please let me know. Thanks in advance.
UPDATE:
I've been making some progress but don't seem to find a real solution. Now I know that the url has to be the controller, so I'm using 'components/userpost/controller.php' as it, and it reaches the ajax call, cause the success alert is showing up. The problem is the MVC way, because I send ajax to the controller, but since I don't have a reload in the page, all the includes are failing so they are obviously not being loaded, and I'm getting errors like this:
PHP Warning: include(components/userpost/model.php): failed to open
stream: No such file or directory in
/var/www/html/viewer_mvc/components/userpost/controller.php on line 3,
referer: http://localhost/viewer_mvc/index.php
Really hope you guys can show me where am I failing, and if there's a special way to do these thing in MVC.
For the JQuery call it makes a POST request to index.php?option=users with JSON data. The form with the ID userForm is serialized using the Jquery serialize method.
The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls
$.ajax({
type: 'POST',
url: 'index.php?option=users',
data: $('#userForm').serialize(),
cache: false,
dataType: 'json'
Now for your PHP sample
if ($action_user == 'show_alerts') {
$list = ModelUser::getAlertContact($act_email);
echo json_encode($list);//I predict that ajax don't reach this line, but not sure
}
This code will be looking for variables that probably don't exist anymore if it is a different file i.e. is there an $action_user variable?
To start reimplementing it you will need to add the logic so that it checks the POST variable if your not using the framework code. So if you have a form element with the name 'name' then that will be available in your PHP script POST variable
$_POST['name']
[How to call a PHP function in MVC using AJAX]
$.ajax({
type: 'POST',
url: 'save-user.php',
data: { fname: "manish", email: "manishkp#com", role:"admin"},
success: function(data) {
console.log(data);
if(data == 'error')
{
$('#Register_error').text('Must Be filled...');
$('#Register_error').show();
}
else {
$('#Register_error').hide();
$('#Register_success').text('Successfully submit');
$('#Register_success').show();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
$fname = $_POST['fname'];
$email = $_POST['email'];
$role = $_POST['role'];
if(!empty($fname) && !empty($email) && !empty($role))
{
#MYSQL CONNECTION QUERY #
echo"success";
}
else{
echo "error";
}
?>

JSON PHP decode not working

I have seen many examples, but for whatever reason, none seem to work for me.
I have the following sent from a app, via ajax, to a php file. This is how it looks when its sent:
obj:{"ClientData":
[{
"firstName":"Master",
"lastName":"Tester",
"email":"me#me.com",
"dob":"1973-01-22",
"age":"51",
}],
"HealthData":
[
"condition : Prone to Fainting / Dizziness",
"condition : Allergic Response to Plasters",
],
"someData":
[{
"firstName":"Male",
"lastName":"checking",
}]
}
Code as is:
{"ClientData":[{"firstName":"Master","lastName":"Tester","email":"me#me.com","dob":"1973-01-22","age":"51","pierceType":"Vici","street":"number of house","city":"here","county":"there","postcode":"everywhere"}],"HealthData":[["condtion : Prone to Fainting / Dizziness","condtion : Allergic Response to Plasters","condtion : Prone to Fainting / Dizziness"]],"PiercerData":[{"firstName":"Male","lastName":"checking","pierceDate":"2013-02-25","jewelleryType":"Vici","jewelleryDesign":"Vidi","jewellerySize":"Vici","idChecked":null,"medicalChecked":null,"notes":"This is for more info"}]}
This comes in one long line into a php file, here is the code:
<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
//var_dump($_POST['obj']);
$Ojb = json_decode($_POST['obj'],true);
$clientData = $Ojb['ClientData'];
$healthData = $Ojb->HealthData;
$someData = $Ojb->someData;
print_r($clientData['firstName']);
?>
No matter what I have tried, I am unable to see any of the information, I don't even get an error, just blank! Please can someone point me in the right direction.
Thank you :)
UPDATE
Here is the code that creates the object:
ClientObject = {
ClientData : [
{
firstName : localStorage.getItem('cfn'),
lastName : localStorage.getItem('cln'),
email : localStorage.getItem('cem'),
dob : localStorage.getItem('cdo'),
age : localStorage.getItem('cag'),
pierceType : localStorage.getItem('cpt'),
street : localStorage.getItem('cst'),
city : localStorage.getItem('cci'),
county : localStorage.getItem('cco'),
postcode : localStorage.getItem('cpc')
}
],
HealthData : health,
PiercerData : [
{
firstName : localStorage.getItem('pfn'),
lastName : localStorage.getItem('pln'),
pierceDate : localStorage.getItem('pda'),
jewelleryType : localStorage.getItem('pjt'),
jewelleryDesign : localStorage.getItem('pjd'),
jewellerySize : localStorage.getItem('pjs'),
idChecked: localStorage.getItem('pid'),
medicalChecked: localStorage.getItem('pmh'),
notes: localStorage.getItem('poi')
}
]
};
And here is how its sent:
function senddata() {
$.ajax({
url: 'http://domain.com/app.php',
type: 'POST',
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: 'jsonp',
data: 'obj='+JSON.stringify(ClientObject),
success : function(res) {
console.log(res);
},
error: function(err) {
}
});
}
There are a few things that will cause problems:
why dataType: 'jsonp'? If you don't intend to utilize jsonp, don't instruct jQuery to do this. See the docs: https://api.jquery.com/jQuery.ajax/
"jsonp": Loads in a JSON block using JSONP. Adds an extra
"?callback=?" to the end of your URL to specify the callback. Disables
caching by appending a query string parameter, "_=[TIMESTAMP]", to the
URL unless the cache option is set to true.
'obj='+JSON.stringify(ClientObject), this will guarantee invalid json.
For reference, have a look at this question: jQuery ajax, how to send JSON instead of QueryString on how to send json with jquery.
That said, try the following:
function senddata() {
$.ajax({
url: 'app.php',
type: 'POST',
crossDomain: true,
contentType: 'application/json; charset=utf-8"',
data: JSON.stringify(ClientObject),
success : function(res) {
console.log(res);
},
error: function(err) {
}
});
}
And in app.php use
$input = json_decode(file_get_contents('php://input'));
to get the data. Use it like:
var_dump($input->ClientData[0]->firstName); // => string(6) "Master"
$Ojb = json_decode($_POST['obj'],true);
makes it array so u need to get them using array index instead of object
UPDATE1
With your update here how it could be done
$str ='{"ClientData":[{"firstName":"Master","lastName":"Tester","email":"me#me.com","‌​dob":"1973-01-22","age":"51","pierceType":"Vici","street":"number of house","city":"here","county":"there","postcode":"everywhere"}],"HealthData":[["‌​condtion : Prone to Fainting / Dizziness","condtion : Allergic Response to Plasters","condtion : Prone to Fainting / Dizziness"]],"PiercerData":[{"firstName":"Male","lastName":"checking","pierceDat‌​e":"2013-02-25","jewelleryType":"Vici","jewelleryDesign":"Vidi","jewellerySize":"‌​Vici","idChecked":null,"medicalChecked":null,"notes":"This is for more info"}]}' ;
$obj = json_decode($str,true);
echo $obj["ClientData"][0]["firstName"];
You can get other elements as above
UPDATE2
You are sending the data as JSONP and this will make the request as
?callback=jQuery17108448240196903967_1396448041102&{"ClientData"
Now you are also adding data: 'obj=' which is not correct.
You can simply send as json not jsonp
and on the php file you can do as
$Ojb = json_decode(file_get_contents('php://input'),true);

how can i get html generated by a php script from another domain(cross-domain)

i am wondering how can get the HTML code which is generated by a cross-domain php script?
Normally if i'm on the same domain , i would use Ajax as follows:
$.ajax({
type: 'GET',
url: 'user.php',
data: 'user_id=user_id', //assuming user_id value was already set.
success: function(html)
{
$('#info').empty().html(html);
}
});
But i am now working on a different domain than my server domain. Which means i use JSON to send data back and to my server php scripts.
However , i know that JSON only send data but not a complete HTML CODE(or am i missing out some point here?)
So , how can i get the html code generated by a cross-domain php script(server) to my web page(another domain).
using javascript you can do the same as if it was JSON, it's called JSONP the P is with padding.
Or you can call it JSON with callback:
// Request Page
myCallback("Some string or Object to parse to your site");
// Your Page
window["myCallback"] = function(string_or_object) {
// Here you can do everything with the parsed data
}
Create a script-tag and include the request page. Make sure to define your callback before including the script-tag
or you can use jQuery's ajax method with dataType set to jsonp:
$.ajax({
"url": "requst_page.php",
"dataType": "jsonp",
"success": function(string_or_object) {
// Here you can do everything with the parsed data
}
})
Look at http://remysharp.com/2007/10/08/what-is-jsonp/
EDIT TO COMMENT:
JSON is right an object normally starts with braces {}.
Demo JSON:
{
"myString": "myValue",
"myOtherString": ["My", "Other", "Value", "This", "Is", "An", "Array"]
}
But using the same method as JSONP you can parse an string instead of the weird looking thing starting and ending with {}.
as myCallback in my example 1: myCallback("HERE I PASS A STRING INSTEAD OF AN OBJECT"). See the "". "STRING GOES IN HERE"
if it was JSON and taken usage of my DEMO JSON it would look like this:
myCallback({
"myString": "myValue",
"myOtherString": ["My", "Other", "Value", "This", "Is", "An", "Array"]
})
JS:
$.ajax({
type: 'GET',
url: 'curl.php',
data: 'user_id=user_id', //assuming user_id value was already set.
success: function(html)
{
$('#info').empty().html(html);
}
});
curl.php;
function get_data($url){
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$user_id = $_GET['user_id'];
$url= "http://www.example.com/user.php?user_id=".$user_id;
echo get_data($url);
You can set up a proxy on your domain and use CURL to get the json from other domain. You then send request to this proxy.
Alternately you would need to set up the other domain to process request as jsonp in order to be able to access directly with ajax
You have to use JSONP or tell the website owner of the other site to add a Access-Control-Allow-Origin header.
I also get same problem when access cross domain using ajax. Then I solve it by make the ajax call to same domain. Then on that php script I apply following code block. This will get the content from cros domain and out put the same to ajax call.
$content = file_get_contents('http://crossdomain.com');
echo $content;
This can be done through jsonp. Following is an example.
$.ajax({
url: "example.com/respond.php",
data: {id: id},
dataType: "jsonp",
jsonp : "callback",
jsonpCallback: "jsonpcallback"
});
respond.php
<?php
header("content-type: application/json");
if (isset($_GET['id'])) $rtnjsonobj->id = $_GET['id'];
$rtnjsonobj->message = "This is the message from cross domain";
echo $_GET['callback']. '('. json_encode($rtnjsonobj) . ')';
?>

Xml reply from PHP to post of jquery Ajax

i have a javascript code that requests a php page to provide it with list of names that are currently online and update a Table, but i have a problem sending it back in form of an array, someone told me that this is usually done using XML, but i dont know how to start.
javascript Post method:-
$.post( "updateTable.php", POSTdata,
function( data ) {
$("#mytable").last().append('<tr><td>'+data+'</td></tr>');
}
);
the php file:-
include("connect.php");
$query1 = "SELECT * FROM formtable";
$result_id = mysql_query($query1, $global_dbh)
or die ("display_db_query:" . mysql_error());
while ($table_array = mysql_fetch_object ($result_id))
{
$rows[] = $table_array;
}
foreach ($rows as $temp ) {
if ($temp->isOnline==1)
$newRow[] = $temp->name;
}
echo "$newRow";
mysql_close($global_dbh);
Please excuse any syntax or semantics in my code, i am a beginner.
How can i populate my table using ajax callback function, and in what form the data will arrive there, and how can i use xml to help me.
Many thanks in advance.
A quick example of json:
var table = $("#mytable").last();
$.ajax({
type: 'post',
url: "updateTable.php",
dataType: 'json',
data: POSTdata,
success: function(data){
jQuery.each(data, function(i, row){
//console.log(row);
table.append('<tr><td>'+row.name+'</td></tr>');
});
}
});
and in php file, instead of :
echo "$newRow";
replace with:
echo json_encode($newRow);
That's it!

Categories