Javascript Dynamically Communicate with PHP - javascript

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?

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;

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.

Related

How to permanantly and dynamically save data in an html file?

Ok so I am trying to make a program that allows teachers to edit/design a test and for students to take it. I made dropdown menues to select type of question and the category (history, english, etc.) and have textboxes to receive the question text. My question though is how to save this text and selections permanently. My initial thought was to change the contents of a js file variable, but javascript is client side. What is the easiest option as I need this quickly? Please just plain javascript/html, no jquery or jfiddle. Please explain in simple words :). I am no pro. PHP is ok but I do not know it so I will need it to be clear. If you could help, that would be fantastic as I and another guy have not found a simple solution ( at least to our minds).
If your users only use modern browsers (very unlikely), you can use local storage:
// Store
localStorage.setItem("lastname", "Smith");
// Retrieve
document.getElementById("result").innerHTML=localStorage.getItem("lastname");
Otherwise learn AJAX. It allows to save/read data from a server async. That means you don't have to change the page and you can save your data on every selection change.
And if you want to have it easy, use a Framework. Because this is a ajax request without a framework:
var xhr=new XMLHttpRequest(); // Initialize the Ajax request
xhr.open('get', 'send-ajax-data.php');
xhr.onreadystatechange=function(){ // Track the state changes of the request
if(xhr.readyState === 4){ // Ready state 4 means the request is done
if(xhr.status === 200){ // 200 is a successful return
}
}
}
xhr.send(null); // Send the request to send-ajax-data.php
And this is a ajax request with a framework (jquery):
$.get( "send-ajax-data.php", function( data ) {
});
You can use the above answer, and send your data using ajax call.
or
you can save your data in xml file in client side.
var newXml = "text to be saved"; // your data is here (form the xml).
//Sets the data in a hyperlink for download.
$('#DownloadLink')
.attr('href', 'data:text/xml;base64,' + btoa(newXml))
.attr('download', 'autounattended.xml');
or you can save the data in json too.
//creates javascript object
var sampledata = {'PkId' : 123, 'Name':'sudhansu' };
//Converts the object to json string.
var dataTobeSaved = JSON.stringify(sampledata);
then you can save this data to a file using the above method.
No matter how you slice it, there are a few things that you will need to learn in order to make this work. So instead of handing you code that you might not understand or be able to implement, I think you would be better served by some references and a simple explanation.
First, you will need to implement a CGI (common gateway interface). CGI can be implemented via Perl, PHP, Python, JavaScript (with nodejs). There are other languages that can be used, but these are the most common.
After you have a CGI script setup on your server, your client-side application can submit data to the server via a AJAX request or via a HTML Form submit. Most people use AJAX, but both options work.
Once the data is sent from the client and handled by the CGI script, you will want to be able to interface with the data. CRUD is an acronym for interfacing with data, it stands for Create, Read, Update, Delete. While it is possible to implement this by storing the data in a raw text file, it is generally considered a bad practice. Thus I would recommend that you look into using some type of SQL database, MySQL, PostgreSQL, SQLite are a few that are relatively easy to implement (SQLite being the easiest of the three imo).

What is the right way for Searching functions in a Website with Javascript?

Its known that interactions between Javascript and SQL-Databases are not very secure. But most Websites use it cause the Webside doesent reload to show matches in a search.
With PHP it isn't possible to change Page-Contents without a completely Page-Refreshing.
Witch is the right way to get Data from SQL with Javascript without security-neglects.
Aspeccialy for a Searching function with directly matches in a list.
You can use 2 way to get data from db by using js;
1. Ajax:
function refresh() {
$.ajax({
url:"your url",
method: "GET",
data: your_params,
success: function(response) {
$("#specific_div_id").html(response);
}
});
}
You can do this within an interval like;
setInterval(refresh, 5000);
in order to get content in every 5 sec.
2. Websockets
In AJAX, you are requesting in every 5 secs to get updated content from server. Think that, you are not getting content server pushes updated content to you. In other words, server notifies you on any updated data. You can have a look at Socket.io for an example implementation of websockets. When server notifies you, you can take data and put it related html area
As mention in the commentaries, the best way is to use AJAX, which is an acronym that stands for Asynchronous Javascript and XML.
The last part, XML, is a bit misleading. It kept that name because that's what is was first use for. But AJAX can now be use to make HTTP request and interface with any language, including PHP.
Depending on the technology you are built on, there are several implementation available. Chances are you have jQuery installed already. In that case, jQuery Ajax, and particularly jQuery.get() would address your concerns.
If you are using a router on the backend, you can simply call a route, specifying it as the url, first argument of the function. Otherwise, you can directly call a file by using the relative path from the html page the javascript is embedded in.
jQuery.get will return anything you echo within you server script. In other words, anything that is directly rendered on the page. You can use a callback catch the data returned and process it.
Example :
$.get('/path/to/file.php', function (data) {
console.log('Here is the data received from the server!', data)
// Process data here
});

overwriting PUT requests

I'm using a library (rightjs) to make xhr requests to a server which only accepts PUT requests for a certain api call. Looking at the code, the library seems to overwrite the method to be POST and appends the method in a querystring parameter:
if (method == 'put' || method == 'delete') {
add_params._method = method;
method = 'post';
}
(the query string is formed calling .map() on add_params later on)
I'm not familiar with the reason for this, but I'm guessing it intends to support servers which do not have WebDAV functionality. I'd like to contribute to the library but don't want to outright delete this code since it seems like there must be a good reason for it.
Why does this library do this, and what methods can I use to figure out if its needed?
(a) This has nothing to do with WebDAV. (b) There used to be libs and intermediaries not supporting PUT, and this was a workaround (which of course requires the server to support it).

Check if a javascript has loaded and then call another javascript

I have a javascript which gets JSON data from URL and loads the data on to the page, then I want to call another javascript to add the slide effects.
There is a simpler solution, i.e using setTimeout. But this solution is not complete because getting data from a URL does not have a fixed amount of time. It varies on every call.
Hence I want to check if my first javascript has loaded and then I want to call the second javascript.
JavaScript is an asynchronous language, or at least, its HTTP API is (mostly) asynchronous.
You shouldn't use settimeout, but you should use asynchronous chaining instead for building a list of causal events. There's a big bunch of libraries out there to assist this, like http://www.infoq.com/articles/surviving-asynchronous-programming-in-javascript
If you're loading content from your own site, then there'll be an onsuccess/oncomplete event when the JSON finally gets loaded, you can assign a callback to it. How it is actually called depends on your javascript framework if you use one.
If you're using data from a remote site in a format called JSONP, you're to define a callback to it, it should be a public function name, like onMyDataArrived. You should add your callback code there. Some frameworks hide this detail from you, they generate a random function which they remove when the data has arrived, and provide an API similar to onSuccess / onComplete instead.
Nowadays, the most popular javascript framework is jQuery, where you can do such things, like:
$.ajax({
url: 'give_me_my_json.php',
dataType: 'json',
success: function(data){
//call your second javascript
},
error: function(){
//WHOOOPSIE... data could not be loaded
}
});

How to hide details in jquery ajax from browser page source

I am using jquery for all my ajax thing, I don't know if that is fine but I use that for now.
I have one text input when user type characters in it I call server side get some values and add them on the view.
Code that I use bellow works fine but I want to improve it a little.
How can I make this ajax call so that users that want to investigate my page source code can't see what I call here?
So basically I want to hide from page source what url, what type and data send I use here, is it possible?
$(function () {
$("#txtSearch").keyup(function (evt) {
$.ajax({
url: "/Prethors/Users/SearchUsers",
type: "POST",
data: "text=" + this.value,
success: function (result) {
$("#searchResult").prepend("<p>" + result + "</p>");
}
});
});
});
No, a user will always be able to figure out what calls you are making if you include it in javascript.
You can compress and minify the javascript, but a determined person will always be able to find your url calls.
Here's a js compression site, for example.
http://jscompress.com/
overall, you shouldn't worry about this. there is no way I'm aware of to hide your ajax calls, but you shouldn't need to.
-you could encrypt the info.
-you could use comet to stream the data on a persistent connection. (super complicated).
-follow good server security practices and not worry about it.
source: here
If you are really worried about this, you could set up kind of an anonymous URL, which will then redirect to where you really want to go based on some variable which is arbitrary.
for example, instead of going to "/Prethors/Users/SearchUsers"
go to "/AnonymousCall?code=5"
from which you could execute the code you want for searchusers
You can't hide client-side code. You can disguise it with minification but sensitive data should always be stored and processed on the server-side.
Use console.clear(); after you ajax calls :P
It just clears the reqs from the console but you still cannot hide client side calls.

Categories

Resources