How to properly connect Ajax/Javascript to the backend - javascript

I have created a PHP class that allows my users to createAccount, updateAccount along with various other functions.
I normally create an 'interface' script that initiates a class and calls the login function and I pass the variables from the front end to this script using JavaScript. However I have to create lots of these 'interface' scripts for each function. Is there any better way to do this?
I end up with an 'interface' folder which scripts such as createAccount.php, updateAccount.php and these scripts are called when the user wants to do any of these functions. Is there a better way to do this?

There are many possibilities for client-server communication. The method and design by which you choose to allow this communication is up to you.
As for your question - you can create a single php endpoint (i.e. endpoint.php) through which to handle all ajax requests. Specific parameters of the request, such as which server side action to perform, can be sent through the query parameters in the url (and accessed in your script with the $_GET variable), or through post data (and accessed with $_POST).
Assuming you are using jQuery, an AJAX request to this endpoint might look like:
$.ajax({
url: 'path/to/endpoint.php',
data: {
_function: 'createAccount',
/* ... */
}
});
And in endpoint.php you may handle the request in such a manner:
<?php
switch ($_GET['_function']){
case 'createAccount':
// handle account creation
// ...
break;
case '...':
// ...
}
?>
This is just one possibility of communication between client and server. No matter how you do it - with a single endpoint which handles all requests, or multiple endpoints - it's your design decision.
You might want to look up on client-server communication protocols over HTTP, such as REST and SOAP.

Related

is it possible to execute any php function using ajax [duplicate]

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.

How to handle URL with parameters in a SAP AJAX Webapp?

I'm writing a Wordpress/AJAX based SAP web application, and I have a question about URL handling.
My application (roughly) looks like this:
There is an index.php file which basically contains a page container and the client-side code to handle ajax calls.
The client-side code is responsible for switching the pages according to user clicks. It does that by calling the registered action, which is mapped to a server-side function that returns the html for that page. (So there is a function named get_about_page() that prints/returns the HTML of the requested page)
The problem with this setup is handling URLs.
The question at hand is how do I handle requests to URLs like http://domain.com/about, for example?
Had I had an about.php page, I could add a rewrite rule to direct all requests there.
I could also, theoretically, parse the URL on the client-side, and decide which ajax call to fire, but that seems like a bad idea.
Use pre define wordpress api, it may help you

How to get data from remote website?

Lets say there is a url out there e.g. www.website.com/data.jsp
the link has the following JSON data
{"successful":"true","rows":[{"zip":"65472","user_id":"10843","name":"Rufio"}]}
I just want to be able to extract this data at runtime however I am having a hard time getting it using getJSON
$.getJSON("test2.jsp",function(result){
$("div").append(result.rows[0].user_id + " ");
});
Now if I run it using a local file with the data residing in test2.jsp as shown above it appends the user_id. However when I try to access "www.website.com/data.jsp" instead nothing happens. I don't believe the website is configured to work with JSONP either.
I need a way to figure out how to pull this data from the website at run time. Does anyone have any solutions or workarounds?
p.s. Is this something that might need to be sorted out on the other end? The people who own the website set this scenario up to be like a fake api call like typically you would pass in parameters to get back the specific information that you would need. In the case of this endpoint or url it just returns a single record or the file just contains the data listed above. They would like me to extract the data from their url at runtime.
You can't make a normal ajax call to to this other domain due to same origin policy.
You can use JSONP to load the remote page, but looking at that example output you wouldn't be able to access the data unless the remote site is setup for JSONP (assigning the JSON to a variable, calling a callback function, etc).
You could create a server-side passthrough script of your own. You don't mention what server-side technology you have available, but if you can use PHP, you do a passthrough like this:
<?php
echo file_get_contents("http://www.website.com/data.jsp");
?>
PHP (or any other server-side language) can fetch the remote data, and now you can use ajax to call your own script (which works since you're on the same domain).

How does popular mail websites handle server side scripting?

I was wondering how do popular mail websites handle / call the serverside scripts. How do they do it differently in a way that users are not easily able to decipher which file they are calling to invoke say login authentication.
For eg: from yahoo website i did view source on login page and saw
<form method="post" action="https://login.yahoo.com/config/login?" autocomplete="" name="login_form" onsubmit="return hash2(this)">
usually action is the server side script file which is being called on submit button right? so they are redirecting to some other website on .done (i.e after authentication), but how do we know what file they calling to run the script?.. Where is the username and password. I tried a wireshark capture too, because they are using post, i won't see the username/password in the url but in wireshark i should see right?
Sorry a lame question, but was just curious as to how these big people work.
Are you merely confused about the URL https://login.yahoo.com/config/login??
Consider: A web server does not need to work with files at all. Having a URL like http://example.com/login.php is merely an extremely lazy way to map to a file on disk. Internally, the web server will receive the request as /login.php and will have to look through its configuration if there's a file login.php somewhere in a directory configured for the host example.com, execute that file and send back the results to the user. That's a complicated task.
Instead it could just receive the query for /config/login? and do something completely different with it, like... logging you in.
You're never executing files directly on a remote server. This is important. There's always a program translating URLs to executable programs or actions. This is completely arbitrary and has nothing to do with the file system.
Try searching for "pretty URLs".
The /config/login? in this case is just a entry point into the server at login.yahoo.com. It could be a HTTP handler name, and when that handler gets invoked on that webserver, it just calls into some other server side call (c++ or java or anything else)...
So its kinda hidden from you. They are (possibly) just executing a 'method' or a series of methods on the server side...which on completion return some data back to the browser via the same http handler/entry-point.
These server entry points or HTTP handlers get all the data from the browser when that form is post'ed and is forwarded to the actual handler for this call.
Search for HTTP handler modules.

How to prevent direct access to my JSON service?

I have a JSON web service to return home markers to be displayed on my Google Map.
Essentially, http://example.com calls the web service to find out the location of all map markers to display like so:
http://example.com/json/?zipcode=12345
And it returns a JSON string such as:
{"address": "321 Main St, Mountain View, CA, USA", ...}
So on my index.html page, I take that JSON string and place the map markers.
However, what I don't want to have happen is people calling out to my JSON web service directly.
I only want http://example.com/index.html to be able to call my http://example.com/json/ web service ... and not some random dude calling the /json/ directly.
Quesiton: how do I prevent direct calling/access to my http://example.com/json/ web service?
UPDATE:
To give more clarity, http://example.com/index.html call http://example.com/json/?zipcode=12345 ... and the JSON service
- returns semi-sensitive data,
- returns a JSON array,
- responds to GET requests,
- the browser making the request has JavaScript enabled
Again, what I don't want to have happen is people simply look at my index.html source code and then call the JSON service directly.
There are a few good ways to authenticate clients.
By IP address. In Apache, use the Allow / Deny directives.
By HTTP auth: basic or digest. This is nice and standardized, and uses usernames/passwords to authenticate.
By cookie. You'll have to come up with the cookie.
By a custom HTTP header that you invent.
Edit:
I didn't catch at first that your web service is being called by client-side code. It is literally NOT POSSIBLE to prevent people from calling your web service directly, if you let client-side Javascript do it. Someone could just read the source code.
Some more specific answers here, but I'd like to make the following general point:
Anything done over AJAX is being loaded by the user's browser. You could make a hacker's life hard if you wanted to, but, ultimately, there is no way of stopping me from getting data that you already freely make available to me. Any service that is publicly available is publicly available, plain and simple.
If you are using Apache you can set allow/deny on locations.
http://www.apachesecurity.net/
or here is a link to the apache docs on the Deny directive
http://httpd.apache.org/docs/2.0/mod/mod_access.html#deny
EDITS (responding to the new info).
The Deny directive also works with environment variables. You can restrict access based on browser string (not really secure, but discourages casual browsing) which would still allow XHR calls.
I would suggest the best way to accomplish this is to have a token of some kind that validates the request is a 'good' request. You can do that with a cookie, a session store of some kind, or a parameter (or some combination).
What I would suggest for something like this is to generate a unique url for the service that expires after a short period of time. You could do something like this pretty easily with Memcache. This strategy could also be used to obfuscate the service url (which would not provide any actual security, but would raise the bar for someone wanting to make direct calls).
Lastly, you could also use public key crypto to do this, but that would be very heavy. You would need to generate a new pub/priv key pair for each request and return the pubkey to the js client (here is a link to an implementation in javascript) http://www.cs.pitt.edu/~kirk/cs1501/notes/rsademo/
You can add a random number as a flag to determine whether the request are coming from the page just sent:
1) When generates index.html, add a random number to the JSON request URL:
Old: http://example.com/json/?zipcode=12345
New: http://example.com/json/?zipcode=12345&f=234234234234234234
Add this number to the Session Context as well.
2) The client browser renders the index.html and request JSON data by the new URL.
3) Your server gets the json request and checks the flag number with Session Context. If matched, response data. Otherwise, return an error message.
4) Clear Session Context by the end of response, or timeout triggered.
Accept only POST requests to the JSON-yielding URL. That won't prevent determined people from getting to it, but it will prevent casual browsing.
I know this is old but for anyone getting here later this is the easiest way to do this. You need to protect the AJAX subpage with a password that you can set on the container page before calling the include.
The easiest way to do this is to require HTTPS on the AJAX call and pass a POST variable. HTTPS + POST ensures the password is always encrypted.
So on the AJAX/sub-page do something like
if ($_POST["access"] == "makeupapassword")
{
...
}
else
{
echo "You can't access this directly";
}
When you call the AJAX make sure to include the POST variable and password in your payload. Since it is in POST it will be encrypted, and since it is random (hopefully) nobody will be able to guess it.
If you want to include or require the PHP directly on another page, just set the POST variable to the password before including it.
$_POST["access"] = "makeupapassword";
require("path/to/the/ajax/file.php");
This is a lot better than maintaining a global variable, session variable, or cookie because some of those are persistent across page loads so you have to make sure to reset the state after checking so users can't get accidental access.
Also I think it is better than page headers because it can't be sniffed since it is secured by HHTPS.
You'll probably have to have some kind of cookie-based authentication. In addition, Ignacio has a good point about using POST. This can help prevent JSON hijacking if you have untrusted scripts running on your domain. However, I don't think using POST is strictly necessary unless the outermost JSON type is an array. In your example it is an object.

Categories

Resources