How to create in php a search.json twitter-like - php

I've made on my website a search.php file that produce a JSON string, helping me to use real-time ajax for my apps.
But now, I'd like to open it as an API to others, but I discovered that $.get $.getJSON $.ajax doesn't allow to use my search.php file from other servers/domains.
How can I do to transform my php search into a search.json, exactly like Twitter, passing parameters to it.
Thx

getJSON is limited by your browser's security restrictions that lock down non-origin domains. In order to do cross-domain, you have to use JSONP, which requires you wrap the data in a function that is defined by the callback variable (e.g. $_GET['jsonp_callback']). e.g.
Search.php
<?php
echo $_GET['jsonp_callback'] . '(' . json_encode($data). ');'
// prints: jsonp123({"search" : "value", etc. });
?>
jQuery
$.ajax({
dataType: 'jsonp',
data: 'search=value',
jsonp: 'jsonp_callback',
url: 'http://yourserver.com/search.php',
success: function () {
// do stuff
},
});
Just make sure that the callback variable that you define in your php script matches the jsonp value that you call through the .ajax query (or it defaults to "callback").

Twitter uses two mechanisms to allow cross-domain access to the search.twitter.com domain: crossdomain.xml (for Flash) and JSONP (for JavaScript).
With JSONP, the calling JavaScript includes a callback=? parameter in the URL, where ? is the name of a callback function. The server-side script wraps the encoded JSON as:
?(<JSON here>)
This allows the query parameters to be encoded as the src URL of a script tag, allowing cross-domain access that XMLHttpRequest does not allow. When the data arrives, it is executed as a script. The JavaScript interpreter decodes the JSON since it is a valid subset of JavaScript and then calls the callback function with the decoded JSON as an argument. It shouldn't take more than a few lines of code to implement JSONP in your PHP script.

Related

Cross Origin Resource Sharing using AJAX methods and PHP

I just started to work on calls to a php file which is present in a different server. I am aware of CORS which is essential for cross domain requests. I have been trying to call this file through ajax methods refering to other websites and tutorials and I have seen discussions to find a solution but they are not working for me. Please help.
here is my calling method:
$.ajax({
type: "GET",
url: "http://cs-server.usc.edu:27952/ResponseProg.php?callback=?", //Relative or absolute path to response.php file
datatype: "jsonp",
data: dataInput,
jsonp:'jsoncallback',
crossDomain:true,
success: function(data)
{
JSONObj = jQuery.parseJSON(data);
contentProvider("#rtrn");
if(JSONObj.ack != "No results found")
{
var paginate=setPager(0);
$("#pgn").html(paginate);
}
},
error: function() {
$("#rtrn").html("Data not retrieved successfully");
}
});
Here is my PHP code snippet:
<?php
#code for data processing...
$rsltjson = json_encode($result,JSON_UNESCAPED_SLASHES);
echo $_GET['jsoncallback']."(".$rsltjson.");";
?>
I am trying to accomplish this by using JSONP. Should I have any headers?
Are there any errors in my code?....How can I accomplish this? dataInput is the serialized form of form data
The CORS way
You need to put the appropriate header in your php script and output only the JSON:
<?php
header('Access-Control-Allow-Origin: *');
// rest of the code
// output JSON only
echo $rsltjson;
?>
Then using a XMLHttpRequest/ajax call should retrieve the data just fine as JSON without resorting to JSONP.
Mozilla has plenty to read about it
The JSONP way
Since the whole point of JSONP is to bypass cross-domain restrictions, calling a JSONP resource with XMLHttpRequest/ajax, a method in which cross-domain security is fully applied (presumably), is completely useless.
JSONP works by injecting code directly into your page, calling a function that you defined, which is why a JSONP url takes an argument. Therefore, the correct way to call your JSONP url is this:
<script>
function myDataFunc(data) {
JSONObj = jQuery.parseJSON(data);
contentProvider("#rtrn");
if(JSONObj.ack != "No results found") {
var paginate=setPager(0);
$("#pgn").html(paginate);
}
}
</script>
<script src="http://cs-server.usc.edu:27952/ResponseProg.php?jsoncallback=myDataFunc"></script>
The JSONP url will return something that looks like this:
myDataFunc({"a":"fhsfg","b":"qfdgers","c":"difgij"});
Since it is included as a script, it will be executed directly in your page, calling the function myDataFunc() that you defined earlier.
Also note that your php file use the GET parameter jsoncallback while your javascript calls the url with the parameter callback, which would not work.
Finally, you use jQuery.parseJSON(), which produces this error from your code:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
The reason can be found in the jQuery docs:
jQuery.parseJSON( json )
Description: Takes a well-formed JSON string and returns the resulting JavaScript value.
Passing in a malformed JSON string results in a JavaScript exception being thrown.
Your php script feeds your callback with a JSON object
{"a":"fhsfg","b":"qfdgers","c":"difgij"}
rather than a string representing a JSON object
'{"a":"fhsfg","b":"qfdgers","c":"difgij"}'
Note the surrounding quotes, which makes this data a string. We fix this in php by adding the quotes around the data:
echo $_GET['jsoncallback']."('".$rsltjson."');";
Obviously if your JSON data contains single quotes, you will have to escape them.

Objective-C: json response from jquery callback

I'm building and iOS application and
trying to get the json data from a url similar to:
example.com/ajax/u.php?callback=jQuery84054761566_1389381628746
Is anyone familiar with these types of callbacks?
Typical HTTP requests in obj-c return 200 status and a null response object with this url.
That's a JSONP callback used for...well, JSONP. JSONP is used on webpages to avoid the 'same origin' restriction. That is, a webpage loaded from a certain domain (say abc.com) cannot call/access resources on a separate domain (say xyz.com).
The way they (web front-end developers) get around this is by using the <script> tag which is exempt from this restriction. However the return of a <script> tag would just be parsed - to cause it to execute something, you tell it a function name that exists in your JavaScript code, in this case, jQuery84054761566_1389381628746.
So instead of returning a regular JavaScript object, say
{key : 'value'}
the server then returns a function invocation
jQuery84054761566_1389381628746({key : 'value'})
and you have, in your webpage JavaScript, the function definition for jQuery84054761566_1389381628746 that does something:
jQuery84054761566_1389381628746 = function(data){
alert(data.key);
};
iOS does not have this same-origin/cross-site restriction so you don't need JSONP - you can call whatever server you want.

Confused: ajax sending request to a json file

Just now I found some code in a webpage which confuses me a lot:
$.ajax({
url: "/foo/bar/save.json",
data: {
key: value
},
type: "POST",
success: function(a) {
//some code
},
error: function(a) {
//some code
},
dataType: "json"
})
I know that it sends data to url using HTTP method POST, if the url is like /foo/bar/save.php or /foo/bar/save then there's no problem, but it ends with .json...
What kind of server-side languages can handle requests sent to a path ended with json?
Does json have any special meanings or is it just the same as .action .do which I can rename as whatever I like?
Thanks!
What kind of server-side languages can handle requests sent to a path ended with json?
Any. There is no need for a server to use file extensions to map URLs onto programs (or files).
Does json have any special meanings
Using it in a URL hints (without even having to make the request) at the data type being returned (instead of how the software used to produce it was written). This is much more useful to people using clients to fetch the data.
What kind of server-side languages can handle requests sent to a path ended with json?
Any kind.
This is just an url, the way it is handled, redirected or rewritten by the server is not shown to the client.
As an example, using a standard apache / php setup, you can have a rewrite rule on the server :
^(.*)\.json $1.php?json=true
and have your content dynamically generated by a php script.

Sending php variables to Javascript variables

Is there any way to do it without doing this:
send javaScript variable to php variable
OR can I do that, and "cover up" my url to the original one, without refreshing the page(still keep the php variables)?
I believe you are incorrect - you actually DO get the 'javascript' variable to PHP - using the jQuery code snippet below by #MikeD (jQuery is a javascript library containing many and many functions that you can then use in your code - making things little easier to do) above you can pass the javascript variable to PHP page.
On the php page you can assign this variable (originating on client side - browser) to PHP variable using something as simple as this:
$variable = $_REQUEST['javascriptVariable'];
A nice and easy way to do this is like this:
PHP
<div id="something" data-info="<?php echo $info ?>"></div>
Jquery
var info = $("#something").data("info");
EXPLANATION
Put the variable as a data attribute in some div using PHP, and then grab the data attribute from the DOM using JQuery.
There's two points that you can use PHP to create javascript vars, the first being when the "page" is created on the server, the second point is during the operation of the javascript application (once the page is loaded). The second point will require some sort of client side request (ajax, websocket, etc).
The best way to do it (in my experience) is using PHP's json extension which allows you to encode a PHP object/array into a json serialized string that can be unserialized/decoded within the browser into equivalent javascript types.
To do this during page generation can be done similarly as follows:
echo "jsvar = eval('('+".json_encode($phpvar)."+')')";
Note that the eval occurs on client side within browser and is common in every major js library.
Requesting an object during the normal operation of your javascript app will vary depending on how the data is requested, but each way will involve an asynchronous javascript request, a PHP script to handle the request (on the server side), and then a javascript side handler/callback that is called when data is received within javascript as a response to the request.
I typically use PHP to echo a json_encode()'ed string as plain text, then code the javascript side response callback to decode the response and fire an event. For a basic example:
PHP side:
<?php echo json_encode($responce_object); // DONE ?>
javascript side:
on_responce(responce)
{
var res_obj = eval('('+responce+')');
fire_event(res_obj);
}
The example above is very simple and generic to show how it works, but not much more is required for a fully functional solution. The real magic for a specific solution will happen within the "fire_event()" method - this is where the object can be handled via jquery or whatever.
You would want to wrap a lot of security around this code before putting it anywhere you care about, but it illustrates the principles without putting too much mud in the water:
<head>
<script>
function loadDiv(url)
{
$('#YourDivID').load(url);
}
</script>
<body>
<?php
$thisID = 1; //set here for demonstrative purposes. In the code this was stolen from, a MS SQL database provides the data
$thisGroup = "MyGroup";
$thisMembers = "TheMembers";
$thisName = "Just a example";
echo "<button onclick=loadDiv('http://siteonyourdomain.com/yourpage.php?ID=$thisID&group=$thisGroup&members=$thisMembers');>$thisName</button>";
//note this only works for sites on the same domain. You cannot load google.com into a div from yoursite.tv
//yourpage.php would have some code like this
// if(isset($_GET['thisID'])) {$myID = $_GET['thisID']} else {$myID = NULL}
?>
<div id="YourDivID">
Before
</div>
<?php
//I tested this code before posting, then replaced the domain and page name for security's sake
If you use $.ajax to make the submission to php you won't need to refresh the page. The code for the example on that page would look like this
var javascriptVariable = "John";
$.ajax({
url: '/myphpfile.php',
type: "GET",
dataType: "json",
data: {
name: javascriptVariable,
},
success: function( data ) {
// do success function here
},
error:function( xhr, ajaxOptions, thrownError ) {
// handle errors here
}
}, "json");

call a php function from jquery

I'm trying to figure out the best way to do this...I am using JQuery to submit data to a PHP function, which sends back data from the DB as JSON, which is working. The thing is, on success, I want the JQuery to execute a PHP function...and I'd rather not have to make yet another AJAX call on top of the first AJAX success - especially since the php function is something I've already used elsewhere on my page. This is my code:
JQUERY:
$.ajax({
type: "POST",
url: post_url,
success: function(group) //we're calling the response json array 'tree'
{
//WANT TO CALL THE PHP FUNCTION HERE
} //end success
}); //end AJAX
PHP:
<?php
foreach($groups as $group){
echo '<option value="' . $group->id . '">' . $group->group_name . '</option>';
}
?>
In your php script that builds your response, just add an extra property to your object that is the html string you want to put into your page and then have javascript put it where it needs to go. You have no choice but to run php functions on the server.
If you want to call a php function from your javascript you will have to execute an AJAX request to the function, in its own file, on the server. This is because javascript executes client side and PHP executes server side. Therefore, javascript does not have direct access to PHP functions.
You can use your PHP to write JavaScript, or you can call a php file from a javascript via AJAX.
Can you replicate the functionality of the PHP function with a JavaScript function?
Would this, or something similar, work for you:
$.ajax({
type: "POST",
url: post_url,
success: function(groups) //we're calling the response json array 'tree'
{
for(group in groups){
document.writeln("<option value='"+groups[group].id+"'>"+groups[group].group_name+"</option>";
}
}
}); //end AJAX
Alternatives:
Change the PHP that backs the original AJAX call so that, instead of sending back JSON, it sends back HTML exactly as you want it.
Chain a second AJAX call "inside" the success of the first, so that a second round-trip to the server is done for the JSON->HTML conversion.
Accept that sometimes you need to "duplicate" presentation-rules when you are working with multiple languages, and use something like EJS to do the same <option> stuff that PHP does elsewhere.
You have to be aware that you're dealing with two paradigms here, the first one is server-side logic (PHP) and the second one is client-side logic (JavaScript).
Unfortunately there is no way to call PHP from JS from the client without performing an AJAX call and rendering the content you want to show. However, you could prepare the result and set the body of the AJAX response with your requested HTML string.
If this is not possible, I suggest to look at the diverse number of JS frameworks that will provide helpers to generate options for select fields.

Categories