Jump to content

ArgusPMC

Members
  • Posts

    10
  • Joined

  • Last visited

ArgusPMC's Achievements

Newbie

Newbie (1/7)

0

Reputation

  1. I've run into something I've no knowledge about, even if I've already used it implicitly and this is callbacks, which as far as I'm concerned sound a little confusing. If I understood this correctly, callbacks is something like calling functions within functions and it is used a lot within asynchronous operations. Here's my issue, I have a file, I need to encode into base64 because I need to pass it to PHP to have it inserted into a database. I generally don't like inserting images or files into databases, first because there's a possibility that they might get damaged if they are not stored correctly and second because they take up a lot of space and I can see how that might be a problem when a database gets 1000 to store or some nonsense of that sort. I'd rather just store a URL path or something of that sort, but this is not an option here. I did figure out how to make all of this work, but not in a way I like and it looks to me like something that would cause trouble if I had to use many asynchronous operations. So here's what I have: window.addEventListener("load", function findImageUploadButton (){ var button = document.getElementById("upload image").addEventListener("click", sendImage);});function clearInputs(){ document.getElementById("image").value = ""; document.getElementById("name").value = ""; document.getElementById("location").value = "";}function sendImage(){ var imageName; var imageLocation; var image; var species; var imageData = []; var encodedImage; var Json; var regex = /.(?:jpe?g|png|gif)$/; var XMLHttp = new XMLHttpRequest(); var code; var serverResponse; var reader = new FileReader(); image = document.getElementById("image"); imageFile = document.getElementById("image").files[0]; imageName = document.getElementById("name").value; imageLocation = document.getElementById("location").value; if(image.value == "" || imageName == "" || imageLocation == "" || !regex.test(image.value)){ alert("You must upload a .gif, .jpg or .png file and you must specify its name and the location, please do so before continuing"); clearInputs(); return false; } reader.onload = function(){ var text = reader.result; imageFile = text; console.log(imageFile); imageData[0] = imageFile; imageData[1] = imageName; imageData[2] = imageLocation; Json = JSON.stringify({imageData: imageData}); console.log(Json); XMLHttp.onreadystatechange = function() { if (XMLHttp.readyState == 4 && XMLHttp.status == 200) { serverResponse = XMLHttp.responseText } } XMLHttp.open("POST", "PHP/insertImage.php", true); XMLHttp.setRequestHeader("Content-type","application/json;charset=UTF-8"); XMLHttp.send(Json); } reader.readAsDataURL(imageFile);} So here's the issue: I've got my AJAX request being done within the file reader's operation to encode the file. I tried to do it differently, but so far all it has amounted to is to a whole lot of nothing, so I did it this way and it worked, but I don't like it, because if I had 5 asynchronous operations, they'd all be nested within and that is the sort of thing that looks to me like it could lead to messy code. So is there a way to get the file reader's result through a callback or something and then send the AJAX request? I'd appreciate it, I've tried to do my own callbacks but nothing has been working. It'd be nice to do things that way.
  2. Sorry that I didn't answer this sooner, but I figured it out a while a go. Apparently it wasn't even that difficult to begin with. Whether it is correct or not I don't know, but it saves me a lot of extra buttons that I may have had to put into the html. I don't know if what I'm doing is preferable than to what is done normally. By this I mean, I try to keep PHP and JavaScript off my HTML as much as it is possible. So far it has been way more organized and clean than just combining all three into the same thing. I don't really know if that is the correct way to do it, but that's how I do it. However, thank you for the advice, I shall take it into consideration with my next project.
  3. I have a dilemma here. I'm using AJAX to send and retrieve data from PHP. My login scripts function this way, they extract some data from a couple of inputs, send it to PHP to check with the database and then send it back to JavaScript to display some information based on those results. What I would do is that I would hide or unhide, elements if the returned information indicated that the login process was succesful. But then this doesn't work with other pages, it just resets everything. I found some ways to check, but I don't necessarily like them, the first one was to do something like this: var session = '<?php echo $_SESSION['name']?>' This doesn't work for me because it doesn't adhere to MVC, it also means I need to change the extension file to get the contents, It's just not right to do something like that. Otherwise, I could just embed PHP into my HTML and display the information like that, but I'd like to remain consistent in how I collect information and I already chose to use AJAX and not the usual form method. I could always just create a small script to check, hide and unhide whatever's necessary but then the PHP file to get that would be a waste of space and time, especially if all its going to do is to send $_SESSION contents. I've already got my login script in JavaScript, I'd like to think I could handle it from there. Then they also tell me I could just handle it from cookies, but what if the user disables them? In any case this is what my javascript code looks like: /* Code to extract login details from main page. An event listener is added to the button used to submit a user's details. AFter that, said information is sent to an external php file which is used to check if a user exists and start a session*/window.onload = function findLoginButton() { var button = document.getElementById("start_session").addEventListener("click", sendUserDetails); /*Unobtrusive javascript listener, added to button */ }function sendUserDetails(){ var xmlhttp; var username; var password; var joinButton; var loginButton; var logoutButton; var dataToSend = []; var JSONdataToSend; if (window.XMLHttpRequest){ xmlhttp = new XMLHttpRequest(); /* Used for IE7+,FireFox, Opera, Chrome, Safari */ } else if (window.ActiveXObject) { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); /* Compatibility for IE6 browsers */ } else { throw new Error("Your browser is not compatible with XMLHTTP"); return false; } loginButton = document.getElementById("login"); joinButton = document.getElementById("join"); logoutButton = document.getElementById("logout"); username = document.getElementById("login_username"); password = document.getElementById("login_password"); console.log(loginButton); console.log(joinButton); if (username.value == "" || password.value == "" ){ alert("Please, fill out all fields before submitting"); return false; } dataToSend[0] = username.value; dataToSend[1] = password.value; JSONdataToSend = JSON.stringify({dataToSend: dataToSend}); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200){ serverResponse = xmlhttp.responseText console.log(serverResponse); var code = parseInt(serverResponse); console.log(code); if(code == 2){ alert("Admin login succesful.") username.value = ""; loginButton.style.display = "none"; joinButton.style.display = "none"; logoutButton.style.display = "block"; window.location = "register.php"; } else if(code == 1) { username.value = ""; loginButton.style.display = "none"; joinButton.style.display = "none"; logoutButton.style.display = "block"; alert("Login succesful."); window.location = "register.php"; } else { alert("The username or password that you have entered is invalid or it doesn't exist. Please try again, or create an account."); username.value = ""; password.value = ""; return false; } } } xmlhttp.open("POST","php/checkUserExistence.php", true); xmlhttp.setRequestHeader("Content-type","application/json;charset=UTF-8"); xmlhttp.send(JSONdataToSend);} If anyone can help me it'd be great, if there is no other way but to embed PHP to html, then I guess I will do that, but I don't exactly like it either, since that is the sort of thing that also doesn't adhere to MVC.
  4. 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.
  5. 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.
  6. Ok, I tried that, but it didn't do much. It did say for the first time, that my variable wasn't empty, as for var_dump(), it returns an empty array of length 0.
  7. 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.
  8. 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.
  9. I'm sorry what? I'm not sure I understand what you're saying, aside from "read the tutorial" which I've done already. Specifically the MDN tutorial on getting started wtih AJAX and all the other stuff with W3Schools.
  10. 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.
×
×
  • Create New...