Why to use ajax to send a PostgreSQL query to a server? - php

I have a web application where I actually use JQuery and Ajax in order to send a query to my database.
My script is something as simple as this:
$(document).ready(function(){
var datastr = id; // get the value inserted in text
var ajaxurl = 'run.php', // script to run
data = {datastr:datastr}; // data to pass
$.post(ajaxurl, data, function (response){...//do something
Making some improvements in my script it crossed my mind this: do I really need to make an Ajax request to send this query to the database or I can just use something as simple as the PHP function for PostgreSQL to do that?
Ofcource I know that Ajax is all about asynchronous communication but I want to know what would be the best practice in a situation like this. Is using Ajax in this case an overkill?

do I really need to make an Ajax request to send this query to the
database or I can just use something as simple as the PHP function for
PostgreSQL to do that
Well actually it does not have the same goal. As you may know, Ajax is client-side meanwhile PHP is server-side. If you want to send your request without refreshing your webpage, then you would need asynchroneous request like Ajax does. Else, PHP fit your need.

Related

jQuery AJAX - Get data from php during the request

I'm using AJAX to insert data in MySQL database. During the AJAX request, there is a PHP function that loops inside a JSON array in order to get data and to insert it inside the DB. Everything works fine.
But, I would like to know if there is a way to pass, during the AJAX request a PHP var to jQuery in order to append it in HTML or to retrieve the data with console.log. I can get these info on AJAX complete but is it possible to get info during AJAX request?
I think you can just echo the php var on the page?
E.g. echo "<label>".$phpVarToAppend."</label>";
Nope. HTTP is stateless. You make a request and you get a result.
You must use different techniques to check the request's processing advancements from server.
Given that you store a record of the progression during the processing somewhere (db, cache or whatever), the simpler trick is using another AJAX call to a simple function that returns the last processing record.
This is a traditional polling mechanism.
A more advanced solution could be using a different connection upgraded to websockets. This will be a true realtime channel.
On top of these there's a world of possibilities. It only depends on what you need to manage with your POST request and how long does it take the processing.
For big payloads it's usually better to return immediately and start processing in a different task. (and thus a pooling mechanism to check progression)

PHP Object & JQUERY AJAX Calls

I have a HTML input that a user will type into. After every key a JQUERY event will grab the text written so far and make an AJAX call that will be picked up by PHP.
I have done this before and its easy to have a PHP script that is called that will then deal with the data passed - eg: db calls and return what is required.
Question - Is it possible to do this using a PHP object? (I'm writting OOP PHP for the first time). Is there some way to combine an AJAX call with a PHP Object or should the PHP end just be a standard function?
thank you
* More info: this function is searching for a location against a database with 6million suburbs/postcodes. Each key a user types a jquery event it trigger that creates an ajax call with the letters typed so far. PHP is called and a SQL query run to return possible locations.
You can combine a PHP object with an AJAX call, but you'd have to explain what you're trying to do in greater detail for me to determine whether or not it would help you.
It sounds like you just want an AJAX call that is invoked after say, 500ms of a user not giving input to the text box or whatever. That seems like a standard PHP update function.
Based on what you've stated so far, I would suggest you just go with the AJAX; have it proc off an onKeyUp, onKeyPress, or whatever you want, and then run some PHP.
Recall that you can create a timer in many fashions; just search around here. You probably don't want to use AJAX for each key stroke.
OnKeyUp JavaScript Time Delay?
Hope that helps.
Use javascript (read jQuery) to submit a post message to your server when the client has paused input for a period of time.
If you are trying to submit an entire form of data, there is a useful function in jquery that will serialize it for you:
var formData = $("#form").serializeObject();
$.post('phpPageURL.php', formData, function(data){
//analyze success or failure
});
Then, write some php which will convert that post data into a model (class) which is how the rest of your application interacts with that data. Then, depending on what you want to do with that data call the necessary controller, passing it that object.
Something like:
$foo = new Foo();
$foo->name = $_POST['formField_name'];
ManipulateData::doawesomeness($foo);

Can I wait for a js process within PHP before continuing?

I have a PHP script I use to register users but during that process I'm trying to call a Google GEOCoding javascript method to return the client lat/lng and record it to a DB before continuing with my PHP registration process.
Can this be done or is there a better way?
My current code looks something like this:
private function process() {
$this->validate();
$this->register();
// execute javascript here to record lat/lng coordinates to the DB.
$this->goHome();
}
You don't need javascript. The Google Geocoding API is a web service. In PHP, just do a file_get_contents() and issue the request using the proper url format as described here. You'll then need to run the result through PHP's json_decode().
You can't just run JavaScript in a PHP script. PHP is executed on the server, and JavaScript is executed in the client's browser. You should modify your registration form so that the JavaScript is called before the form is submitted, and you should pass the user's lat/lon as extra data for registration. Then, when your PHP registration runs, you'll have access to this data.
A better idea would be to find a PHP library to do geocoding.
See Johnathan M's answer.
Javascript is a clientsided script language
Php is serversided
This makes it impossible the way you imagion to do it.
Take a look into GeoIP
http://php.net/manual/en/book.geoip.php
You generally handle only one request in script and what you asking about would require at least two: in first user would ask for some response from your server and you'll be able to send your JS to him and in second request he'd submit results of running that JS.
You can save "state of waiting for response" in some way and process geo response when it comes.
I think the easiest way to solve your issue would be to use 2 AJAX calls and a function:
- the first calls a PHP script to do your validation/ registration
- when this completes run a clientside JS script to do the geocoding
- have another AJAX call to update the DB with the result of geocoding
You should be able to solve your problem this way. If you use a library like jQuery its easy to do the AJAX calls and you can even make use of deferred objects, which I think could help you chain your calls http://api.jquery.com/category/deferred-object/
Do the GeoIP lookup in PHP using a web API instead on the server side.
For example:
http://www.maxmind.com/en/web_services
They have a PHP example here (I wouldn't call the webservice that way, but it works):
http://dev.maxmind.com/geoip/web-services#PHP-11
private function process() {
$this->validate();
// Do a call to the webservice here with PHP, update user data with the response.
$this->register();
$this->goHome();
}
There are a couple of ways to go about it.
The best appoach would be to make the geocaching call within your PHP, not using javascript all. PHP has several ways of making HTTP requests from code, that will return results you can use in your script. I personally favor cURL: http://php.net/manual/en/book.curl.php. See also Jonathan M's earlier reply, same idea but using file_get_contents().
Another (far hackier) approach would be to make the javascript call to the Google Geocoding API synchronous (async=false in jquery.ajax()), and have it execute your request to your registration php page through a callback on the ajax call. (The "success" property on the ajax.) This means that your registration page will not be called until the geocoding lookup is completed. It's a valid question whether you want to make success/failure of your registration dependent upon completion of the ajax request, but if you do, this would work. Check here for info on synchronous ajax requests in jquery: http://api.jquery.com/jQuery.ajax/. This really isn't the best way to go about it though. The geocoding lookup really is part of the registration, and the last thing you want to do is make your php registration dependent on unreliable frontend behaviors.

How can I connect to a server through JavaScript where my PHP program is housed?

I am writing an Android App, and already have a working program written in HTML and PHP. Using the two, they contact an API with a user customized lookup on the html page, which then sends to the PHP page, contacts the API with the customized search, gets a result, and the php outputs to a html page again.
I know PHP cannot work on Android, but I plan on using PhoneGap. With PhoneGap, I can run JavaScript, HTML, and CSS supposedly. I have also read that a solution with Android being unable to understand PHP is to connect to a server (my computer) which can run the php for me, and then output it in a way the phone can understand.
My plan is to use JavaScript, which PhoneGap can understand, to connect to my computer, and have it run the PHP and output the page in HTML which again, PhoneGap can understand.
If this is absurd, please let me know... Otherwise I'd greatly appreciate it if someone could push me in the right direction in a JavaScript function that would allow me to authenticate myself, connect to my computer, and tell it I'd like to use a certain PHP file.
We had the exact same problem when developing our application for Android as well as for iOS. Like Austin told you already you have to make use of AJAX.
W3schools - AJAX
I recommend you however not to use jquery if it's only needed for a few simple things because it's fairly heavy because of the big script it has to load. So if you can reduce the amount of code, please do so by learning the real JavaScript instead of jQuery.
Also, what we did is writing our own APIRequest.js object. When calling this object like so:
var result = new APIRequest('functionname', {param1:value, param2:value})
This is a fairly easy approach to connect to your php which will run off course on your server somewhere in a foreign country or your pc.
As you can see we insert a functionname, we have developed our API as a fairly simple OOP php thingy that allows us to put a functionname.php in a certain folder and it will be read by de script and then select that function. Database connections and stuff like that will be aranged in the index of the api. With this approach you can make special functions, server-side, for every unique handling.
I am telling you this because you are making use of JavaScript. I'd like you to understand that it is not safe! It as as safe as a JavaScript application on your computer. It is possible for a hacker to download the .apk to his computer, run it in the simulator on his pc and make edits through his console. And thus meaning, he can change your whole code (at least, the JavaScript part). So make sure you try to make this as safe a possible, with keys and stuff like that. Also, try to do as much logic as possible on your server, so the logic can't be changed. Only the input parameters to your API.
I hope this helped you!
Here you would need to use AJAX. jQuery has a great wrapper function called $.ajax that makes most of the process pretty simple and straightforward.
AJAX will send an asynchronous request to any file (in your case a php file) and fire a callback function with the data it receives.
(synchronous is also possible, but not recommended as it will make your application hang until the request is complete. More on why this is not recommended)
Some good reads on the subjects covered here:
http://www.sitepoint.com/ajax-jquery/
http://www.impressivewebs.com/callback-functions-javascript/
The basic technology you want to use is AJAX, which is the term for making server calls over HTTP from Javascript. You pass data to and from the server in XML (the X in AJAX) or perhaps in another encoding, such as JSON.
You'll need a dedicated PHP file on the server that will understand the data you send in the AJAX post and instead of generating HTML generates the XML/other format your Javascript will consume.
Your best bet would probably be to create a browser app that communicates with your server via AJAX, and when that is working port it to PhoneGap.
It's very easy. Just do a GET request to the PHP page and parse the result. Create a function to make it easier:
function httpGet(theUrl){
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
Then, you can call it and obtain the resultant HTML code.
var url = 'http://yourpage/index.php?a=something&b=otherthing';
var page = httpGet(url);

Grabbing data from MySQL using PHP realtime?

I am wondering how I would get data from a MySQL database and display it in real time using PHP. Without having to refresh the page. Thanks!
Use AJAX (I suggest using the jQuery library for this), and have your AJAX script (written in PHP) query the MySQL database.
You can use Socket.Io for more Speed ,efficiency and performance for Your Server
http://socket.io/
But you need Node.Js for that
You will have to use javascript. You can use setInterval(function, n) to fire your update calls every n milliseconds, and a library like jQuery to handle the ajax call and updating your page.
Download jQuery or link to a CDN hosted version of jQuery in your page. Then put something like this on your page:
setInterval(function(){
// inside here, set any data that you need to send to the server
var some_serialized_data = jQuery('form.my_form').serialize();
// then fire off an ajax call
jQuery.ajax({
url: '/yourPhpScriptForUpdatingData.php',
success: function(response){
// put some javascript here to do something with the
// data that is returned with a successful ajax response,
// as available in the 'response' param available,
// inside this function, for example:
$('#my_html_element').html(response);
},
data: some_serialized_data
});
}, 1000);
// the '1000' above is the number of milliseconds to wait before running
// the callback again: thus this script will call your server and update
// the page every second.
Read the jquery docs under 'ajax' to understand the jQuery.ajax() call, and read about 'selection' and 'manipulation' if you don't understand how to update the html page with the results from your ajax call.
The other way to continuously update your page is to use a persistent connection, like web sockets (not currently supported across all the common browser platforms) or a comet-style server-push setup. Try googling comet and/or web sockets for more info, but I think the above method is going to be much easier to implement.

Categories