So far when creating AJAX requests I have been posting to a separate PHP file. Is it possible to create a jQuery AJAX request that calls a PHP function rather than posts to a separate page?
If you could send me any examples or documentation would be great.
I believe there's a fundamental misunderstanding of how the technology works here.
AJAX (Javascript), Flash, or any client-sided technology cannot directly call PHP functions (or other languages running on the server).
This is true for going the other way around as well (eg: PHP can't call JS functions).
Client and server codes reside on different machines, and they communicate through the HTTP protocol (or what have you). HTTP works roughly like this:
Client (eg: browser) sends a REQUEST -> Server processes request and sends a RESPONSE -> Client gets and displays and/or processes the response
You have to see these requests and responses as messages. Messages cannot call functions on a server-side language directly 1, but can furnish enough information for them to do so and get a meaningful message back from the server.
So you could have a handler that processes and dispatches these requests, like so:
// ajax_handler.php
switch ($_POST['action']) {
case 'post_comment':
post_comment($_POST['content']);
break;
case '....':
some_function();
break;
default:
output_error('invalid request');
break;
}
Then just have your client post requests to this centralized handler with the correct parameters. Then the handler decides what functions to call on the server side, and finally it sends a response back to the client.
1 Technically there are remote procedure calls (RPCs), but these can get messy.
AJAX requests call a URL (make a HTTP request), not a file, in most cases the URL is translated by the server to point at a file (or a php script in your case), but everything that happens from the HTTP request to the response that is received is up to you (on your server).
There are many PHP frameworks that map URL's to specific php functions, AJAX is just an asynchronous way to access a URL and receive a response.
Said URL CAN trigger the server to call a specific function and send back a response. But it is up to you to structure your URL's and server side code as such.
If you're asking whether you can call any arbitrary PHP function with AJAX the answer is no*, for obvious security reasons (in addition to the technical reasons). You could make a PHP script that does different things depending on what parameter it's given (for example, execute a single function) if you don't want to create multiple separate files.
*Although you could make a script that would execute any arbitrary PHP command coming from the client, but that would be very, very, very unwise.
Short answer is "no" but the real answer is that you can fake it. NullUserException's answer is good. You create a server that will take the function name and its parameters. Then the server executes the function, and returns the value.
This was done a while back via a protocol called XML-RPC. There was also an effort called JSON-RPC that used some JS techniques.
One things that's cool about JS is that you can do things like this:
var base64_decode = create_remote_call('base64_decode');
function create_remote_call(name) {
return function(x) {
jQuery.getJSON('url/server.php',
{func:name,arg:x},
function(d){return d;});
}
}
A call to base64_decode('sarefdsfsaes') will make a ajax request and return the value.
That code probably won't work because it hasn't been tested, but it's a function that produces a function that will call the server, and then return the value. Handling more than one argument requires more work.
All that said... in my experience, it's usually good to make all network communications explicit instead of disguising it as a regular function.
you may achieve the same result using a bridge, like my phery library http://phery-php-ajax.net you can call PHP functions directly from Javascript and deal with the value. The AJAX is bound to DOM elements, so you can manipulate the calling DOM or just use jQuery from the PHP side. An example would be:
Phery::instance()->set(array(
'phpfunction' => function(){
return PheryResponse::factory()->jquery('body')->addClass('whoops');
}
))->process();
and in the javascript side (or HTML)
phery.remote('phpfunction');
the equivalent to the https://stackoverflow.com/a/7016986/647380 from John Kawakami answer, using phery is:
function base64($data){
return !empty($data['encode']) ? base64_encode($data['content']) : base64_decode($data['content']);
}
Phery::instance()->set(array(
'base64' => 'base64'
))->process();
function base64(content, decode, output){
phery.remote('base64', {'content': content, 'encode': decode ? 1 : 0}, {'type':'text'}).done(output);
}
base64('asdf', false, function(data){
console.log(data); // or assign to some variable
});
since AJAX is asynchronous and you can't just return a value from the AJAX call, you need a callback, but this would suffice.
Related
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.
Whats the best way to do a RPC (Remote Procedure Call) from a webpage or from JavaScript code? I want to keep it in JavaScript if possible so that I can do live updates to the webpage without having to do anything in PHP in case my server goes down I still want the JavaScript to handle page updates... possibly even sending a request to a python shell script running locally... Is this legal from JavaScript?
I prefer having remote machines handling the requests. I see a lot of talk about how XMLRPC or JSONRPC can do this however, I haven't seen any good examples. I guess Microsoft suggests using their XMLhttprequest however, I haven't seen anything that doesn't use their ActiveX call or require special code for Internet Explorer... I just want some simple way of passing a command to some python/ruby/c++ code from a webpage.
Python Server Code (Waiting for a RPC Request):
import xmlrpclib
from SimpleXMLRPCServer import SimpleXMLRPCServer
def my_awesome_remote_function(str):
return str + "awesome"
server = SimpleXMLRPCServer(("localhost", 8000))
print "Listening on port 8000..."
server.register_function(is_even, "is_even")
server.serve_forever()
EXAMPLE JavaScript Code:
var client = rpc.server("http://localhost:8000/");
var my_local_variable = client.my_awesome_remote_function(param);
Is there a good JSON/JavaScript example someone can point me to that sends a request to a server and gets some data back from that server?
Thanks!
Hardly it will work this way: client.my_awesome_remote_function. There's no magic in js like __call in php. Also remote calls are done in js mostly asynchronously using idea of callback - function which is called after finishing of some task.
var client = rpc.server("http://localhost:8000/");
var my_local_variable;
client.rpc('my_awesome_remote_function', [param], function(result) {
my_local_variable = result;
});
You can easily find tutorials about that calls. Just google "ajax tutorials".
E.g.: http://www.w3schools.com/ajax/ajax_intro.asp (event though w3schools isn't the best site and have errors in some details, it is still good for beginners).
All ajax implementations use both modern both XMLHttpRequest and ActiveX control for older IE.
It is possible to run those requests synchronously, but is considered very bad from the point of user experience. Also, you'll need to deal with concept of callbacks anyway.
I am trying to write some information into my database when I activate a javascript function.
I use PHP and MySQL. How can I open the .php file, execute it and return to .js file in order the function to continue its operation?
Thanks in advance.
I think you may be a bit confused. Javascript runs in the browser, on the client's computer. Php/MySQL runs on the server, responds to HTTP requests, and creates the content for the browser to display/run.
In order to get the two to communicate dynamically, you need to look at how to send/receive HTTP requests from javascript on the client to your php script on the server. You'll also need to be able to process responses in javascript. This practice is known as AJAX. The simplest way to do this is in my experience to use JSON and jQuery, http://api.jquery.com/jQuery.getJSON/
First of all, it is not possible to call PHP functions directly from JavaScript, or vice versa. This is because PHP is a server-side script, running on the server, and JavaScript is a client-side script, running on the browser.
But there is a solution, however, using a technique called "AJAX" (Asynchronous JavaScript and XML), which can be used to send a request to a server from JavaScript.
For instance, using a "user" page that the user sees, and a "request" page that is called from the JavaScript code, I could write the following code:
userpage.php:
<!-- JavaScript code -->
<script type="text/javascript">
function sendRequestToServer()
{
// The XMLHttpRequest object is used to make AJAX requests
var ajax = new XMLHttpRequest();
// The onreadystatechange function will be called when the request state changes
ajax.onreadystatechange = function()
{
// If ajax.readyState is 4, then the connection was successful
// If ajax.status (the HTTP return code) is 200, the request was successful
if(ajax.readyState == 4 && ajax.status == 200)
{
// Use ajax.responseText to get the raw response from the server
alert(ajax.responeText);
}
}
// Open the connection with the open() method
// (the third parameter is for "asynchronous" requests, meaning that
// JavaScript won't pause while the request is processing).
ajax.open('get', 'requestpage.php', true);
// Send the request using the send() method
ajax.send();
}
</script>
<!-- HTML code -->
<button onclick="sendRequestToServer();">Send request!</button>
requestpage.php (the output of this page will be returned to your JavaScript code):
<?php
echo "Hello World!";
?>
This example would, when the button is pressed, send a HTTP request to the server requesting requestpage.php, where the server would execute some server-side code and echo the result. The browser would then take the data it received from the server and use it in the script - in this case, alert() it.
Some resources:
AJAX wikipedia page
AJAX tutorials on Mozilla Developer Center and w3schools.com.
You might also want to check out JSON encoding, which is very common method of sending objects and arrays between clients and servers (especially when using AJAX):
JSON tutorial on MDC
json_encode() and json_decoder() PHP functions
(Sorry for such a long answer, hope it helped though)
You will need AJAX, there http://www.ajaxf1.com/tutorial/ajax-php.html a simple tutorial for AJAX using PHP server
look up AJAX... also think about using jQuery it has a simple and easy to use ajax() function.
If you're not already using an AJAX enabled framework (e.g. jQuery), you could just use a really lightweight XHR implementation to make a HTTP request. This request could have any PHP resource (performing the desired DB updates) as destination.
The smallest code I know of is found here: http://dengodekode.dk/artikler/ajax/xmlhttprequest_wrapper.php (Danish, sorry)
<script type="text/JavaScript">(function(){if(window.XMLHttpRequest)return;var o=null,s,
a=["MSXML2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0","Msxml2.XMLHTTP","Microsoft.XMLHTTP"];
for(var i=0,j=a.length;i<j;s=a[i],i++){try{if(o=new ActiveXObject(s))break}
catch(e){}}window.XMLHttpRequest=o?function(){return new ActiveXObject(s)}:null;o=null})()</script>
And the request:
var oHttp = new XMLHttpRequest();
oHttp.open("post", "http://www.domain.dk/page.php", true);
oHttp.onreadystatechange = function(){ myCallBack(oHttp) };
oHttp.send("id=123&noget=andet");
I'm using PHP to pull the events from a FullCalendar as a JSON feed but I need to support multiple domains. I need a querystring variable to specify which calendar to pull events from... is this causing a problem? Here's the FullCalendar init code:
$('#full-calendar".$id."').fullCalendar({
editable: false,
events:'http://www.mydomain.com/resources/include/calendar-events.php?cal=".$id."',
loading: function(bool) {
if (bool) $('#loading').show();
else $('#loading').hide();
}
});
The documentation says "If you need to access a feed that is in a different domain, you can use JSONP with a ? in your URL (see the JSONP discussion in $.ajax)."
But I'm not exactly sure how to do that.
Thanks for your help in advance.
Well at a high level, JSONP lets you specify the name of a callback function that you want called when the AJAX request returns with data. HTTP GET operations can happen across different domains, (when you embed an image from a different host, you are creating an HTTP GET). POST (and PUT, DELETE etc) are limited to the same domain as the document (this is called the Same Origin Policy). JSONP, adds an extra parameter (usually 'callback') with the value of a JavaScript function in your document (the callback function). The sever sending the JSON needs to know to extract the value for that parameter. Your request might look like this:
GET http://ical.example.com/cal.json?callback=_calDraw
The cal.json servlet will return this
_calDraw({event:{date:'12/25/2010',title:'Jason\'s birthday'}});
Now this bit of JavaScript references the callback function you passed into it, but without a corresponding
function _calDraw(data) {
//render stuff
}
The returned data will just fail. It's important that you have some level of trust with any server you are making a JSONP call to, because you are giving them permission to execute JavaScript in your document (they don't have to return something valid).
Hope this helps!
I have a PHP page that needs to make a call to a external web service. This Web service call takes a bunch of sensitive data from a html form on the PHP page, e.g. SSN, and returns info related to that person.
The problem is that the web service call should be made as soon as the customer fills in the SSN field and the field loses focus, so the page cannot be reloaded in any way. I was thinking about using jQuery to make a call to the web service, but AJAX unfortunately requires that you are on the same domain as the requested resource. So I'm thinking about creating an local PHP page that makes the call to the web service and then use JQuery to call this new page.
Questions:
How do I use JQuery to call the local PHP script that makes the call to the web service?
Because the JQuery code will take sensitive data from a html form and send it to the PHP script, how can I encrypt the data?
To call your PHP file:
var url = "http://localhost/data.php";
var params = {
"SSN" : theSSN
};
$.get(url, params, function (){
// Do whatever you need here, once the data arrives.
});
To call the external webservice from PHP, I'd suggest using cURL.
To encrypt, I'd suggest using the HTTPS protocol instead of encrypting manually from JavaScript.
1) $.get("myscript.php", function(response) { alert(response) });
2) I wouldn't encrypt using jQuery, it would be slow and easy to decrypt. Enabling SSL on the server would be a better solution.
1: Ajax request example:
$.ajax(
{
type: "GET",
url: "http://yourdomain.com/yourpage.php",
success: function (msg) { //does something }
});
More details here
2: php XOR is a pretty good encryption algorithm, I use it myself for a project with sensitive data. you can find the function here.
Enjoy! :)
This probably won't help you in particular, but some webservices support something called JSONP, which adds a callback name to a normal JSON request.
However, chances are you will need to make some sort of local proxy, as not many JSONP services exist yet.
The way to go is enabling SSL on your domain, and doing the xmlHTTPRequest to the https of the remote service