Jump to content

Passing form information through ajax to PHP with vanilla JavaScript


ArgusPMC

Recommended Posts

Ok, so first I have to explain what it is that I'm doing. This is my first web development project, it's also the first time I use JavaScript and PHP, and in addition to that, I'm required to utilize Oracle 11g as my database, since the website has a great number of things to store as persistent data. We're learning about the database part in college, but everything else, meaning Client Side scripting and Server Side scripting is not being taught, meaning I have to find out what the heck is it that everything does and what not. As far as I'm concerned the way this project works in particular is through MVC, with the SQL tables being the model, PHP handling the controller and JavaScript/HTML handling the view. So far it hasn't been easy to get this done, however here's my idea so far, and what I've really coded as of now, which I hope will function for every other part of the website, as far as inserting data into table is concerned.

 

So I've got a form with a bunch of inputs, I get those inputs from the form into an array, then I get stringify it through JSON, and finally send it to PHP to be decoded and used for parameters to be inserted in the different tables. However, they tell me that I should just do a "POST" on the html and forget about all that and let PHP handle it, I thought this wasn't exactly a good idea, and prefer to do this offsite with JavaScript, which brought me to my next discovery which was unobtrusive JavaScript, which I thought was a pretty swell thing. I also thought, but I'm not sure about this, that if I deconstructed the form through JavaScript, and just sent whatever was on its inputs, then I wouldn't have to do that on PHP, that is unless, PHP does that on its own. Then there was also the idea that these things would be stored in memory, however as far as I'm aware this is stored in a computer's RAM and as soon as the page is finished using it the garbage collector, or whatever JavaScript uses to clean up memory. Well, then I thought it would be a good idea to encrypt that, however I found out that it would only complicate things if I encrypted data to send to PHP. Then I heard that the client-server communication is usually encrypted to prevent anyone from snooping around to find out passwords and other information.

 

So here's my relevant HTML form:

<form id= "form_info" class="registration" method="POST"><ul class="registration"><li><label>Nombre de Usuario:</label></li><li><input type="text" name="username" title="Nombre de Usuario"/></li><li><label>Contraseña:</label></li><li><input type="text" name="password" title="Contraseña"/></li><li><label>Correo Electrónico:</label></li><li><input type="text" name="email" title="Correo Electrónico"/></li><li><label>Nombre:</label></li><li><input type="text" name="name" title="Nombre"/></li><li><label>Primer Apellido:</label></li><li><input type="text" name="first last name" title="Primer Apellido"/></li><li><label>Segundo Apellido:</label></li><li><input type="text" name="second last name" title="Segundo Apellido"/></li><li><input type="button" name="create user" class="send_info" title="Crear Usuario" value="Crear Usuario"></input></li></ul></form>

Some stuff is in spanish though, however I'm sure its understandable. Now here's my code, which I was wondering if someone could clarify how is it exactly is it that I send this stuff to PHP, whether its an array, a form or just any sort of data.

window.onload = function findSubmitButton() {    var button = document.querySelector(".send_info").addEventListener("click", serverInteraction);} function serverInteraction() {  var xmlhttp;  var inputArray;  var finalArray = [];  var JSONArray;  if (window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest();  } else if (window.ActiveXObject) { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");  } else { throw new Error("Your browser is not compatible XMLHTTP"); return false;  }  inputArray = document.querySelectorAll("input[type=text]")  for(var i = 0; i < inputArray.length; i++){ finalArray[i] = inputArray[i].value;  }console.log(finalArray);JSONArray = JSON.stringify({finalArray: finalArray}); xmlhttp.open("POST","php/sendUserInfo.php", true);xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");xmlhttp.send(JSONArray); }

Finally, and sorry for the long post, is this okay? Should I get rid of it and just send stuff straight from the HTML? Oh and the reason I mention vanilla JavaScript is because I don't want to use JQuery, I know it is easier and it makes code smallr but I want to learn pure JavaScript first, maybe then in the future I'll use JQuery. Any help is appreciated.

Edited by ArgusPMC
Link to comment
Share on other sites

There is a school of thought that says you should write your page so that simple submits will provide the required functionality even if Javascript is disabled. In this scenario the first thing that Javascript does when the page initializes is modify the form to disable this "dumb" mode of operation. In either case the Php receives the data, does the secure validations, communicates with the database, and then responds appropriately.

 

There are some implementations of client encryption but generally only SSL connections are considered secure.

Link to comment
Share on other sites

So, I should use the simple method then? Just place an

action="doSomething.php"

along with the POST? I still need the server to send the information back to the user, to indicate that his details have been entered into the database, I was thinking I would handle that with an alert that would have an "ok" button which once pressed would redirect said user to the main page.

 

About the encryption, now this is only college project, not a full fledged website for a business or anything of the sort so I doubt that it really matters if communications between the client,server and database are encrypted or not. Regardless, I am curious about it, and I would like to know if there are any tutorials on implementing this SSL thing I keep hearing about. That is unless it is way beyond my level to implement right now.

Edited by ArgusPMC
Link to comment
Share on other sites

Using simple form submittals is now a rather obsolete approach. You should continue learning about the AJAX approach. The difference is of course that the Php code needs to respond differently. In the one case it needs to respond with a complete page and in the other case it only needs to respond with the requested data.

 

See...

 

http://en.wikipedia.org/wiki/Single-page_application

 

SSL is independent of your code, as long as your code follows certain rules.

Link to comment
Share on other sites

Ah, I see, thanks. Right now, even if I didn't want to I have to do it that way since, the page doesn't actually get redirected, it needs to stay there until the user hits "OK" or whatever in the alert that is supposed to carry the "success" response from the server. As of right now, I've managed to get the JavaScript function to send the Array to PHP succesfully, as well as making the connection with the Oracle Database. However, I'm having a little trouble decoding the JSON object in PHP. Either there's an error and my array is being sent out empty, but I don't think so because I checked it in JavaScript or I'm simply not decoding it properly.

 

I don't know if I'm treating it wrong or what, I do it like if it was one of the elements of the form with the $_POST["name"]. I've tried to find tutorials on the subject but I can't seem to find anything.

 

For instance this is my JavaScript JSON:

 

 

JSONArray = JSON.stringify({finalArray: finalArray}); 

 

which should then be opened at PHP like this:

 

 

$finalArray = json_decode($_POST['finalArray'],true);

 

but then when I echo that, it shows nothing.

Link to comment
Share on other sites

Using simple form submittals is now a rather obsolete approach. You should continue learning about the AJAX approach. The difference is of course that the Php code needs to respond differently. In the one case it needs to respond with a complete page and in the other case it only needs to respond with the requested data.

 

See...

 

http://en.wikipedia.org/wiki/Single-page_application

 

SSL is independent of your code, as long as your code follows certain rules.

 

Ordinary form submission will never be obsolete. It is part of the core of HTML. However, it is really popular to use AJAX as more comfortable alternative on browsers that support Javascript.

Link to comment
Share on other sites

There must be a trick to using a "pure json" send.

 

This seems to work...

xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");xmlhttp.send("json="+JSONArray);
Link to comment
Share on other sites

Well I checked chrome's developer tool's response log and it shows my JSON when I echo it through PHP, I was opening the page manually to check if it had been done properly. Apparently this is asynchronous, I'm not sure what that means, but they told me that it will show nothing if I open up the page. I suppose that means it is working, although whenever I console.log my responseText it shows up empty.

Link to comment
Share on other sites

Yes, I know, I found out a little while ago. I've checked with XDebug on eclipse to see if it is getting sent and it, the browser output shows the array and its contents. Thank you for your help, I think I'm done with this particular problem, hopefully the other stuff from the website will behave similarly at least.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...