Send simple HTTP request with HTML submit button - javascript

I have added a submit button to the index.html page that resides on my server side
<form method="get" action="/start">
<h5>Start Ad-Placer!</h5>
<input type="submit" value="Start">
</form>
I need the button to simply send a http request to http://127.0.0.1:8484/get/start to start some process. Then once the process is done after a few seconds, I need to simply display an alert message with the response message, acknowledging it is done.
How can I do that with minimum efforts (without using JQuery or other libraries).

If you try something like this you can send a HTTP request and then alert a response. Just change https://google.com to your URL.
<h5>Start Ad-Placer!</h5>
<input type="submit" value="Start" onclick="submit()">
<script type="text/javascript">
function submit() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
alert(xhr.response);
}
}
xhr.open('get', 'https://google.com', true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xhr.send();
}
</script>

Related

Webpage reloading on entering correct values

I've ran into an weird problem. I have created a login page which send data to a PHP page which return some response code like "00000" for ok "404" for not found etc. I have tested my server with Postman tool and found server is working perfectly fine. When my html send data to server server responds with response code. If the response code comes wrong html alert's it. However if I enter correct credentials and when server respond with success , My login page reloads for no reason.
Here's my javascript
function validatelog(){
var user_email_log=document.getElementById("user_email_log").value;
var user_pass_log=document.getElementById("user_pass_log").value;
if (user_email_log&&user_pass_log!=null)
{
var hr = new XMLHttpRequest();
var url = "../logic/login.php";
var vars =
"user_email_log="+user_email_log+"&user_pass_log="+user_pass_log;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-
urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var saman = hr.responseText.trim();
if(saman=="00000"){
alert(saman);
}else if (saman == "404"){
alert("Failed with 404");
}
else{
alert(saman);
}
}
}
hr.send(vars);
}
}
And my html looks like this
<input id="user_email_log"/>
<input id="user_pass_log"/>
<button onclick="validatelog();">Log in</button>
Add type="button" to the button:
<button type="button" onclick="validatelog();">Log in</button>
When it is not specified, it is the same as type="submit", and this will cause your page to reload.
if you use jquery you could do this.
$(document).on('click', 'button', function(e) {
e.preventDefault();
$.get('url')
})
I think the page is reloading because that is the default behavior.

XML HTTP Request not working in event handler functions

I am trying to load weather data using a simple http request. The actual request is set up properly, as it works perfectly when not called, but rather when the program just runs it upon loading. However, when I place the code in a function called from an onclick or onsubmit event, the readyStatus foes directly to 4, and the status code stays at 0, and that is it. The request does not get executed. Is there something I do not know about setting up an http request in an event handler function? Or is there a mistake in this work that I have not realized. The relevant code is directly below:
<form class="form-inline">
<div class="form-group">
<label for="city">City: </label>
<input type="city" class="form-control" id="city" placeholder="Enter City">
</div>
<div class="form-group">
<label for="state">State: </label>
<input type="state" class="form-control" id="state" placeholder="Enter State">
</div>
<button type="submit" class="btn btn-lg btn-info" id="submit" onclick="get_data()">Submit</button>
</form>
And the get_data function, where the http request is set up, is below:
function get_data(){
request = new XMLHttpRequest();
request.open("GET", "http://api.wunderground.com/api/31c6aa45ad6072ac/conditions/q/MA/Boston.json", true);
request.onreadystatechange = function(){
alert(request.readyState);
alert(request.status);
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
request.send();
}
Mixed content warning with the current code. Changing the url from http to https solves it. Check this snippet, the http button and the https button change the url from/to https. The problem exhibited from http match your reported issue.
function get_data(s){
request = new XMLHttpRequest();
url = "http://api.wunderground.com/api/31c6aa45ad6072ac/conditions/q/MA/Boston.json";
if (s) url = "https://api.wunderground.com/api/31c6aa45ad6072ac/conditions/q/MA/Boston.json";
request.open("GET", url, true);
request.onreadystatechange = function(){
alert(request.readyState);
alert(request.status);
if (request.readyState == 4 && request.status == 200) {
console.log(request.responseText);
}
}
request.send();
}
<button onclick='get_data()'>http</button>
<button onclick='get_data(1)'>https</button>
I simplified the button, and changed the alerts to console.log(s) on jsbin, and it's working properly (IMO):
function get_data() {
console.log('running');
request = new XMLHttpRequest();
request.open("GET", "http://api.wunderground.com/api/31c6aa45ad6072ac/conditions/q/MA/Boston.json", true);
request.onreadystatechange = function () {
console.log(request.readyState);
console.log(request.status);
request.readyState == 4 &&
request.status == 200 &&
console.log(request.responseText);
}
request.send();
}
<button onclick="get_data()">Submit</button>
http://jsbin.com/cegifi/edit?html,js,console,output
Figured it out, it was the fact that the button was of type submit and not button, so that it would resubmit the page with false information. Thanks for everyone's help!!

function works but don't alert and reload

I wrote a small form to log-in into my website :
<form id="log_form" onsubmit='return loginjs()' method="post">
<input type='text' placeholder="login" size='30' name='login' class='test'/>
<input type='password' placeholder="password" name='password' size='30'/>
<input type='submit' value='Connect' id='signin' />
</form>
and I wrote this Javascript function to send the form's data to a php page which going to check if everything is ok and make the session up.
function loginjs() {
'use strict';
var form = document.getElementById('log_form');
var btn = document.getElementById('signin');
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if(request.readyState === XMLHttpRequest.DONE) {
if(request.status === 200) {
if (request.responseText != 'ok')
alert(request.responseText);
}
}
}
var post = "login=" + form.login.value + "&password=" + form.password.value;
request.open('POST', 'functions/func_login.php');
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(post);
location.reload();
};
My function is perfectly called each time I press ENTER or click on Submit, but sometimes the alert doesn't show up and the location.reload(); aren't called.
I don't have any error in my console... and if I manually reload the page, i'm logged so my ajax was sent.
I'm looking for 2 days to find the bug, and doesn't succeed to find. Could someone help me?
I can't use jQuery or another library I've to use JS Vanilla :)
Thank you
Try moving the location.reload(); code in the success block of the ajax, i.e. reload the page after the ajax response is received (if no error is received).

Ajax acting as GET method even though is POST method

Hello I have encountered a problem while coding in Javascript and PHP (Ajax non jquery). I am trying to upload a file over Ajax, and handle it in PHP.
This is my code:
index.html
<html>
<head>
<title>PHP AJAX Upload</title>
<script type="text/javascript">
function upload() {
// 1. Create XHR instance - Start
var dat= "bla";
document.getElementById("div2").innerHTML = "working";
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
var rad = document.getElementById('fajl');
var filee = rad.files[0];
var formData = new FormData();
formData.append('rad',filee)
formData.append('var',dat)
xhr.open('POST', 'upload.php');
xhr.send(formData);
xhr.onload = function () {
if (xhr.readyState === 4 && xhr.status == 200) {
document.getElementById("div2").innerHTML = xhr.responseText;
//alert(xhr.readyState);
//alert(xhr.status);
}
}
}
</script>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
<label>Upload File:</label><br/>
<input name="rad" id="fajl" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" onclick="upload()" />
<div id="div2">
</div>
</form>
</body>
</html>
upload.php
<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['rad']['tmp_name'])) {
$sourcePath = $_FILES['rad']['tmp_name'];
$targetPath = "images/".$_FILES['rad']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
echo ("uspjeh<br>");
}}
}
$podatak=$_POST['var'];
echo "$podatak"
?>
Problem is that I dont see PHP script response in my div2 element. Ajax behaves wierd and it puzzles me. I have put JavaScript alert command under xhr.readyState condition (now commented). When I do that then I see the output, but when I close alert dialog, the browser automaticly reloads page and makes the URL like i'm using GET method (i'm using POST) and then server output dissapears. (rad in ?rad=... is the name of my input element)
When I'm not using alert command then I don't see output at all, because page redirects really fast. What am I misiing?
It's because you are using a submit button and that's submitting the form. By default form methods are GET requests. Change to just a button instead:
<input type="button" value="Submit" class="btnSubmit" onclick="upload()" />
The default form action (submitting) is being carried out.
To stop this add return false to your click handler:
onclick="upload(); return false;"

Problems with XMLHttpRequest and PHP

I'm fairly new to both JavaScript and PHP, so I hope this problem isn't as complex as it seems to me. I'm trying to send data from a form to a PHP file using XMLHttpRequest, and then display the output of the PHP as an alert. Here's the HTML and JavaScript:
<form onSubmit="password_Check()">
<input type="password" size="40" name="password" id="pass">
<input type="submit" value="Go">
</form>
<script type="text/javascript">
function password_Check() {
var url = "test.php";
var pass = $("#pass").val();
var xhr = new XMLHttpRequest();
xhr.open("GET", url+"?pass="+pass, true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
}
</script>
And here's the PHP:
<?php
$pass = $_GET["pass"];
echo "The password is $pass! We've done it!";
?>
I've tried all sorts of ways to do this, like $.post, $.get, $.ajax, and an xhr using POST. But I can't seem to get this to work. Now it just appends "?password=(whatever I put)" onto the end of the current url, which does nothing, but it shows it's doing something.
In your code you are missing the send part where you actually trigger the request. If you are not triggering the request then there is no point of the event listeners which listen for the state changes.
do it like
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send();
Also in your question you are mentioning about jquery ajax, with $.get your code could be as simple as
$("#form1").on("submit",function(e){
e.preventDefault();
var url = "test.php?pass=" + $("#pass").val();
$.get(url,function(data){
//handle data here
});
});
You forgot to execute the request. xhr.send():
Also note that since you're having an XMLHTTPRequest, you need to prevent the default behavior (which is the form is going to be submitted) by using .preventDefault();
<form id="form1">
<input type="password" size="40" name="password" id="pass">
<input type="submit" value="Go">
</form>
<script type="text/javascript">
// handle the submission event
document.getElementById('form1').addEventListener('submit', function(e){
e.preventDefault(); // prevent from submitting
var url = "test.php";
var pass = document.getElementById('pass').value; // be faithful!, just use plain javascript
var xhr = new XMLHttpRequest();
var params = '?pass='+pass;
xhr.open("GET", url+params, true);
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(); // send it
});
</script>
If you are using jQuery then better use jQuery's ajax functions instead of xhr by yourself!
Also if you are submitting the password, better not submit it using GET request as it will be visible in the URL. Instead always use POST when handling Passwords!
Client side:
<form action="/index.php" id="myform" method="post">
<input type="password" size="40" name="password" id="pass">
<input type="submit" value="Go">
</form>
<script type="text/javascript">
$('#myform').on('submit', function() {
$.ajax({
type: $(this).attr('method'), //Taking for the form attribute
url: $(this).attr('action'),
data: $(this).serialize(), //Takes care of all input fields in the form! No need to pass one by one!
success: function(response) {
if(response == 'success') {
window.location.href = '/url-to-goto'; //Set your redirect url here
}
else {
//Handle invalid password here
alert(response);
}
}
});
return false;
});
</script>
Server side:
<?php
//If you are handling password, better to put it in the post body instead of url for security reasons
if($_SERVER['REQUEST_METHOD'] == 'POST') {
//Check password here
if(isset($_POST['password']) && $_POST['password'] == '123') {
die('success'); //successful! redirect user!
}
die('Invalid password!');
}
?>
Hope that helps you better understand!

Categories