Reputation: 1142
I'm creating a system where a Javascript script extracts data from a Sage extract, and stores it in a Javascript object (JSON I guess). I need to then upload the data to an SQL database via PHP.
I had thought of using an Iframe, by changing the src to the PHP pages URL, then pass GET variables to the page via the url. I was wondering if I could actually use tags to do this too? By creating new images and setting the src to the PHP pages URL (again, passing GET variables to it), then the PHP page could do the rest? I know the image wouldn't display anything, it doesn't need to. I just need a way to pass data to the PHP page.
Best practices?
Upvotes: 0
Views: 259
Reputation: 10318
As the two other answer have said, for an HTML page with Javascript to communicate with the server, a PHP page, you would need to use XMLHttpRequest
, aka AJAX. Paul S.'s answer is the best answer with respect to how to directly use XMLHttpRequest
with Javascript.
However, one thing to keep in mind is that if you have to support older browsers, especially Internet Explorer version 9 or below, you'll run into quirks and it's advised to use a library for this. For the all purpose library, which includes not only AJAX methods but also form data handling and manipulating the DOM before, during, and after your request, your best bet is to use jQuery. For example, for an AJAX request to send data from a form:
$.ajax({
url: 'http://www.example.com/data.php',
data: $(form).serialize(),
dataType: 'JSON', // JSON will be returned if possible
type: 'POST'
}).then(function(data) {
...
});
jQuery is great, but it is also a big library and if you only really want or need AJAX requests, it's better to find a smaller library or use a function that's known to work cross browser. It's also important to note that jQuery has strange handling of promises, which is the way a function would say it will return a value but not right away. These promises are necessary if you chain AJAX functions together without making your code contain many nested functions. Two of the most well known promise libraries are rsvp.js and q.
Upvotes: 0
Reputation: 66334
The modern way of using JavaScript to communicate with a server is XMLHttpRequest. By default it is asynchronous and does give you the option to change this, though synchronous requests may be considered bad practice.
Here is a basic example
function sendObject(object, uri, callback) {
var xhr = new XMLHttpRequest(),
data = new FormData();
data.append('object', JSON.stringify(object));
if (callback) xhr.addEventListener('load', callback);
xhr.open('POST', uri);
xhr.send(data);
}
// ex. usage
sendObject(
{foo: "bar"},
"/somepage.php",
function () {console.log('completed with code:', this.status)}
);
Using a FormData saves you a little time, too. If you can't expect it to be available, simply do
postData = encodeURIComponent(key) + '=' + encodeURIComponent(value) + '&' + etc;
Upvotes: 2