Can I test XMLHttpRequest() in SDK with localhost? - javascript

The following code does not seem to work because when I try to get the "chooser" in Google App Engine (Python) it is undefined:
chooser = self.request.get("chooser")
self.response.out.write("chooser: %s " % chooser)
#returns "chooser:" without any value
Is this valid javascript?
var formData = new FormData();
formData.append("chooser", user);
var xhr = new XMLHttpRequest();
//is it ok to test this with localhost?
xhr.open("POST", "http://localhost:8086/g/choicehandler", true);
xhr.onreadystatechange = function (aEvt) {
if (xhr.readyState == 4 && xhr.status == 200){
console.log("request 200-OK");
}
else {
console.log("connection error");
}
};
xhr.send(formData);
Is the problem with the XHR call or with the App?
UPDATE
I am including the code in /choice to clarify what "chooser" is as per Daniel Roseman's comment:
In /choice handler I have writeToStorage() which assigns a username in the form user1, user2 and so on, and writes that to localStorage.
After writing user name to localStorage I also need to write it to database in the app, and I use xhr to send it to /g/choicehandler handler.
So, "chooser", I believe is a string, made of
var user = "user" + count;
I copy /choice handler below:
class Choice(webapp.RequestHandler):
def get(self):
self.response.out.write("""
<html>
<head>
<script type="text/javascript">
var count = 0;
function writeToStorage()
{
var user = "user" + count;
count++;
localStorage.setItem("chooser", user);
var formData = new FormData();
formData.append("chooser", user);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://localhost:8086/g/choicehandler", true);
xhr.onreadystatechange = function (aEvt) {
if (xhr.readyState == 4 && xhr.status == 200){
console.log("request 200-OK");
}
else {
console.log("connection error");
}
};
xhr.send(formData);
};
</script>
</head>
<body>
<form name="choice_form" id="choice_form" action="/g/choicehandler" method="post" onsubmit="writeToStorage()">
<textarea name="choice" rows="7" cols="50"></textarea><br />
<input type="submit" value="submit your choice">
</form>
</body>
</html>""")
UPDATE 2
I noticed in the logs that the text from textarea which is "choice" and "chooser" which is sent with xhr are not shown together, one of them is always without a value:
INFO ... chooser: user0 choice:
INFO ... chooser: choice: abcd
INFO ... chooser: user0 choice:
INFO ... chooser: choice: efgh
This is the code for the above log:
chooser = self.request.get("chooser")
choice = self.request.get("choice")
logging.info("chooser: %s choice: %s" % tuple([chooser, choice]))
new_choice = User(
choice = choice,
owner = chooser)
new_choice.put()
so in the datastore i see "chooser" and "choice" written in 2 different rows. What am I doing wrong?

Actually you're submitting the form twice. Once in writeToStorage via AJAX and also with the normal way with the the form. You will have to change two things.
writeToStorage has to return false as the last action
Change your onsubmit to onsubmit="return writeToStorage()"
This way you will prevent the default submission of your form, as it will be done via AJAX in writeToStorage

Related

Ajax Vanilla JS - ajax async continuing without waiting for readyState 4, status 200

TLDR: I would like to wait for the 1st request to be done, before continuing to the 2cnd etc.
Hello,
I am currently working on a HotSpot page. The user needs to input his email, and Voila! he gets internet access.
The thing that is SUPPOSED to happen in the background, is that when the user inserts his email and presses send;
an AJAX async POST is made to the router, with username and password,
then the js/html page waits for the readyState === 4 (DONE) response from the router,
an AJAX async POST is made to a server on a different network (which requires the user to have internet connection), which sends the users email,
then the js/html page waits for the DONE response
the user is redirected.
Thats basically what should happen. What is actually happening, is that the JS does not wait for the readyState === 4 and Status === 200. Once the user clicks Submit, he is redirected right away.
I can't use JQuery, as the router (Mikrotik) is using $ for it's own purpose.
After inspecting the network with the F12 tool, I can see that the POST to router has a status of 200, and is carrying the correct Parameters (username=HSuser&password=SimpleUserPassword) and I can see that the POST to the server has a status of 200 and also has the correct Parameters (email address ie: Email=Ba%40loo.ns).
I guess my JS code is somehow wrong, as it does not wait.
Also, for some reson after fiddling with the code, no more emails are inserted into the Database (they were before, don't know what the is problem now.)
Below is the current code. I'll also post a previous version (which also didn't work) in case someone can spot the problem there.
In case anyone requires any additional information, let me know.
Thank you.
Edit 3.:
I continued to read Stack Overflow and I've stumbled onto this piece of information...
The server is responsible for providing the status, while the user agent provides the readyState.
Is this done server side automatically, or do I need to implement it somehow?
Edit 1.:
I tried console log here
if (xhr.readyState === DONE){
console.log("XHR1" + xhr.readyState);
console.log("XHR1" + xhr.status);
if (xhr.status === OK){
and here
if (xhr2.readyState === DONE){
console.log("XHR2" + xhr2.readyState);
console.log("XHR2" + xhr2.status);
if (xhr2.status === OK){
and I only got XHR1 (XHR14 and XHR1200), I didn't get anything from XHR2.
Edit 2.:
Tried replacing onreadystatechange with onload, still does the same thing.
Current HTML code:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html" />
<meta charset="utf-8" />
<title>HotSpot</title>
</head>
<body>
<!-- Email form which is saved into the DB -->
<form accept-charset="utf-8" name="mail" onsubmit="return false;" method="post" id="mail">
<h1>Hotspot</h1>
<h2>To gain internet access, enter your email.</h2>
<br />
<input type="text" id="email" name="email" autofocus="autofocus" />
<br />
<input type="submit" value="Submit" id="submit_ok" name="submit_ok" /> <br />
</form>
<script type="text/javascript">
document.getElementById("submit_ok").addEventListener("click", SendAjax);
function SendAjax() {
var email = document.getElementById("email").value;
console.log(email);
// Check if fields are empty
if (email=="") {
alert("Please enter your email.");
}
// AJAX code to submit form
else{
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://router/login', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded", "Access-Control-Allow-Origin: *");
xhr.onreadystatechange = function () {
var DONE = 4;
var OK = 200;
if (xhr.readyState === DONE){
if (xhr.status === OK){
var xhr2 = new XMLHttpRequest();
xhr2.open('POST', 'http://server/insertDB.php', true);
xhr2.setRequestHeader("Content-type", "application/x-www-form-urlencoded", "Access-Control-Allow-Origin: *");
var useremail = document.getElementById("email").value;
xhr2.onreadystatechange = function () {
if (xhr2.readyState === DONE){
if (xhr2.status === OK){
location.href = "http://server/redirected.html";
}
}
}
}
xhr2.send("Email="+encodeURIComponent(useremail));
}
}
xhr.send("username=HSuser&password=SimpleUserPassword");
}
};
</script>
</body>
</html>
Current PHP code:
<?php
require ('connect.php');
$clean_email = "";
$cleaner_email = "";
if(isset($_POST['email']) && !empty($_POST['email'])){
//sanitize with filter
$clean_email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
//sanitize with test_input
$cleaner_email = test_input($clean_email);
//validate with filter
if (filter_var($cleaner_email,FILTER_VALIDATE_EMAIL)){
// email is valid and ready for use
echo "Email is valid";
//Email is a column in the DB
$stmt = $DB->prepare("INSERT INTO addresses (Email) VALUES (?)");
$stmt->bind_param("s", $cleaner_email);
$stmt->execute();
$stmt->close();
} else {
// email is invalid and should be rejected
echo "Invalid email, try again";
}
} else {
echo "Please enter an email";
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$DB->close();
?>
Previous HTML/JS code:
function SendAjax() {
var email = document.getElementById("email").value;
console.log(email);
// Check if fields are empty
if (email=="") {
alert("Please enter your email.");
}
// AJAX code to submit form
else{
var xhr = new XMLHttpRequest();
xhr.open('POST', 'http://router/login', true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded", "Access-Control-Allow-Origin: *");
xhr.onreadystatechange = function () {
var DONE = this.DONE || 4;
if (xhr.readyState === XMLHttpRequest.DONE){
var xhr2 = new XMLHttpRequest();
xhr2.open('POST', 'http://server/insertDB.php', true);
xhr2.setRequestHeader("Content-type", "application/x-www-form-urlencoded", "Access-Control-Allow-Origin: *");
var useremail = document.getElementById("email").value;
xhr2.onreadystatechange = function () {
var DONE = this.DONE || 4;
if (xhr2.readyState === XMLHttpRequest.DONE) {
location.href = "http://server/redirected.html";
}
};
xhr2.send("Email="+encodeURIComponent(useremail));
}
}
xhr.send("popup=true&username=HSuser&password=SimpleUserPassword");
}
}
If it makes your life easier (and it WILL), you can put jQuery into no conflict mode.
<!-- Putting jQuery into no-conflict mode. -->
<script src="prototype.js"></script>
<script src="jquery.js"></script>
<script>
var $j = jQuery.noConflict();
// $j is now an alias to the jQuery function; creating the new alias is optional.
$j(document).ready(function() {
$j( "div" ).hide();
});
// The $ variable now has the prototype meaning, which is a shortcut for
// document.getElementById(). mainDiv below is a DOM element, not a jQuery object.
window.onload = function() {
var mainDiv = $( "main" );
}
</script>
https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/
Then you can make your AJAX call, and the stuff that should wait can go in the success function:
$j.ajax({
url: '/your-form-processing-page-url-here',
type: 'POST',
data: yourVariables,
mimeType: 'multipart/form-data',
success: function(data, status, jqXHR){
alert('Hooray! All is well.');
console.log(data);
console.log(status);
console.log(jqXHR);
},
error: function(jqXHR,status,error){
// Hopefully we should never reach here
console.log(jqXHR);
console.log(status);
console.log(error);
}
});

Maintaining authentication using API and xhr

I'm getting to grips with using an API to display the data on a page refresh. SO the first part is to authenticate using form based authentication. So I have this:
<html>
<head>
<script type="text/javascript">
function CallWebAPI()
{
var request = new XMLHttpRequest(), data = 'username=admin&password=admin';
request.open('POST', 'https://localIP:8443/api/users/_login', true)
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
request.setRequestHeader("Accept", "application/xml")
request.onreadystatechange = function()
{
// D some business logics here if you receive return
//if(request.readyState === 4 && request.status === 200) {
console.log(request.responseText);
//}
}
request.send(data);
}
</script>
</head>
<body>
<div>
<div id="response">
</div>
<input type="button" class="btn btn-primary" value="Call Web API" onclick="javascript:CallWebAPI();" />
</body>
</html>
So from the above, in the console browser I return a proper authentication message as thus:
SUCCESS
So I want to run another function to retrieve data now I'm logged in but it seems to reset back to 'unauthorised. All I did was create another function exactly the same except it was a GET rather than POST and added another button to test it. But it just kept returning 401: unauthorised. Am I doing it in the incorrect order or something?
I insert a second function like this:
function getChannelStats()
{
var stats = new XMLHttpRequest();
stats.open('GET', 'https://localIP:8443/api/channels/statistics?channelId=f237ae66-6c5b-4ffa-9396-0721eb575184', true)
stats.setRequestHeader("Accept", "application/xml")
stats.onreadystatechange = function()
{
// D some business logics here if you receive return
//if(request.readyState === 4 && request.status === 200) {
console.log(stats.responseText);
//}
}
stats.send();
}
request.send(data);
}
And add another button that class that function to get the responseText. I'm expecting an xml message with various numbers in it. But when I try to run it, it asks for me to authenticate - like it's not retaining it?

Send PHP POST using Javascript AJAX

My data is not inserting into database, I get a blank response from the console log and network. I'm kinda lost my javascript source code is mix with other stack overflow answers as well as my PHP code.
<form id="requestForm">
<input type="text" name="fName" id="name">
<input type="text" name="fAddress" id="address">
<input type="text" name="fComment" id="comment">
<input type="submit" value="Submit" name="nameSubmit">
</form>
<script>
document.querySelector('#requestForm').addEventListener('submit', postRequest);
function postRequest(e){
e.preventDefault();
const params = {
fName: document.querySelector('#name').value,
fAddress: document.querySelector('#address').value,
fComment: document.querySelector('#comment').value,
};
var xhr = new XMLHttpRequest();
xhr.open('POST', 'addRequest.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.onload = function(){
console.log(this.responseText);
}
xhr.send(params);
}
</script>
</body>
Here's the PHP code:
require_once 'Database.php';
var_dump($_POST); // returns `array(0) {}`
if (isset($_POST['nameSubmit'])) {
var_dump($_POST); // shows no response
$r = $_POST['fName'];
$o = $_POST['fAddress'];
$p = $_POST['fComment'];
$query = "INSERT INTO user_request(name, address, comment) VALUES(?,?,?)";
$stmt = $db->prepare($query);
$insert = $stmt->execute([$r, $o, $p]);
if($insert){
echo 'Success';
}else{
echo 'Error';
}
}
I believe the post parameter nameSubmit does not exsist.
Use the var_dump() function for dump all $_POST
From my prespective, the only parameter given was
fName
fAddress
fComment
Why not check for request method instead?
This is better than checking if a variable exsisted or not.
You can do the checks for required parameter later after you're sure this is a POST request.
if($_SERVER['REQUEST_METHOD'] === 'POST'){
// Do whatever you want when POST request came in
}
UPDATE :
Here is the answer you wanted!
<form id="requestForm">
<input type="text" name="fName" id="name">
<input type="text" name="fAddress" id="address">
<input type="text" name="fComment" id="comment">
<button onclick="sendData();" type="button">Submit</button>
</form>
<div id="testdiv"></div>
<script>
function sendData(){
var data = new FormData();
data.append('fName', document.getElementById("name").value);
data.append('fAddress', document.getElementById("address").value);
data.append('fComment', document.getElementById("comment").value);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'test.php', true);
xhr.onload = function () {
if(xhr.status !== 200){
// Server does not return HTTP 200 (OK) response.
// Whatever you wanted to do when server responded with another code than 200 (OK)
return; // return is important because the code below is NOT executed if the response is other than HTTP 200 (OK)
}
// Whatever you wanted to do when server responded with HTTP 200 (OK)
// I've added a DIV with id of testdiv to show the result there
document.getElementById("testdiv").innerHTML = this.responseText;
};
xhr.send(data);
}
</script>
</body>
The PHP code :
<?php
if($_SERVER['REQUEST_METHOD'] === 'POST'){
var_dump($_POST);
}else{
header('HTTP/1.0 403 Forbidden');
}
?>
To add another field, add another data.append function below data var.
The submit button MUST BE CLICKED. To allow the use of enter, add an event listener for it!.
What it looks like on my end : https://image.ibb.co/gfSHZK/image.png
Hope this is the answer you wanted.
Two issues:
1.) Params not sent properly/at all because lack of serialization. When you use form content-type your params object need to be in a particular format name=value&name2=value2. So to facilitate that you need to transform your ojbect using something like:
function getReadyToSend(object) {
var objList = [];
for (var prop in object) {
if (object.hasOwnProperty(prop)) {
objList.push(encodeURI(prop + '=' + object[prop]));
}
}
return objList.join("&");
}
So your sending becomes: xhr.send(getReadyToSend(params));
2) Your php is expecting the submit button to be sent. if (isset($_POST['nameSubmit'])) {
You don't have a variable being sent called nameSubmit you can fix this by either including it or check that each variable is set instead. I would suggest the latter that way you can error handle should 1 or more are not passed.
Suggestion: Update your onload to check status:
if (xhr.status === 200)
{
console.log(xhr.responseText);
}
else if(xhr.status !== 200)
{
console.log('Request failed. Returned status of ', xhr.status);
}
Example fiddle: http://jsfiddle.net/qofrhemp/1/, open network tab and inspect the call you will now see the params in form data for the call that fires when submit clicked.

Form fields gets cleared on POST data with knockout binding

I'm working with PHP on backend with Slim microframework, in case it be relevant.
Well, the problem is that the form gets cleared after submit. The server return an error code, in case of error, ofcourse, and the error message is showed to the user, but the fields are clean.
I must mention that I'm using the jquery-validation plugin.
HTML
<form action="{{ path_for('save_data') }}" method="POST" id="myForm" name="myForm" data-bind="submit: sendForm">
<input type="text" name="foo" data-bind="value: foo" required>
<button type="submit">Save data</button>
</form>
Javascript/Knockout JS
function MyView($) {
var self = this;
self.foo = ko.observable();
/* ... code ... */
self.sendForm = function(theForm) {
if (!$(theForm).valid()) {
return;
}
$.post(theForm.action, ko.toJS(self.foo), function(response) {
alert(response);
})
.fail(function(failResponse) {
alert(failResponse);
});
};
}
ko.applyBindigs(new MyView(jQuery));
Just for better understanding, the server code is something like this:
public function postSaveData($request, $response) {
if (TRUE) { // Some validations here
return $response->withJson("Error message", 400);
}
// save
return $response->withJson("OK", 200);
}
UPDATE
After some tests, occurs to me to test with pure javascript code, with no jQuery. Like as follows:
self.sendForm = function(theForm) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log("Response text: ", xhttp.responseText);
}
else if (this.status == 400) {
console.log("Response text: ", xhttp.responseText);
}
};
xhttp.open("POST", formElement.action, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(ko.toJS(self.imovel));
};
And voilá! Form perfect filled, as before send data. Somehow jQuery post is clearing the form.

call js function from form action then call php from js

We can call php directly from form action in html:
<form name='x' action = "filename.php">
in this case, php will receive all inputs in the form even we don't pass them.
Can we call js function from form action in html?
<form name='x' action = "javascript:jsFunction();">
Then, call the php from the js function?
jsFunction()
{ var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("result").innerHTML = xhttp.responseText;}
};
xhttp.open("POST", filename.php, true);
xhttp.send();
}
Hint
I cannot use onsubmit because it log me out from the platform. in other words, it reload the platform from the beginning of the login page.
I am working on integration and I don't have a clear idea about the platform.
Edit 1:
Now, in the HTML file:
<form enctype='multipart/form-data' id = "myform">
<input type='submit' value='Basic search' onclick = "i2b2.BLAST.jsFunction();">
JS file:
i2b2.BLAST.jsFunction = function ()
{
var myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function(event)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
document.getElementById("result").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", blastresult.php, true);
xhttp.send();
event.preventDefault();
});
}
it reloads the platform from the beginning of the login page!
Edit2:
I put some alert to see if the button call the javascript.
i2b2.BLAST.jsFunction = function ()
{
alert('hi');
this.yuiTabs = new YAHOO.widget.TabView("BLAST-TABS", {activeIndex:1});//this two lines navigate to second tab
this.yuiTabs.set('activeIndex', 1);
alert('hi');
myForm.addEventListener('submit', function()
{
alert('hi');
preventDefault();
The button call the js and display first 'hi' then navigate to second tab then reload the page. It stop at the second 'hi'.
Any help is highly appreciated.
Thanks.
Yes you can, First give your FORM an id
<form id="myForm"></form>
then in javascript try this:
var myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function(e)
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
document.getElementById("result").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", filename.php, true);
xhttp.send();
e.preventDefault();
});
Instead of:
<form name='x' action = "javascript:jsFunction();">
Use:
<form name='x' onsubmit="jsFunction();">
You can POST via AJAX as you have shown in your code:
function jsFunction(event) {
// prevent default event from taking place (submitting form to file)
event.preventDefault();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("result").innerHTML = xhttp.responseText;}
};
xhttp.open("POST", filename.php, true);
xhttp.send();
}
Though you will need to serialize your data and pass it to xhttp.send(), it will need to be form url encoded like: key1=value1&key2=value2. You are probably better off using jQuery in the manner #mmm suggests.

Categories

Resources