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!
Related
I am trying to get a response from a local file and display it. However, the response text changes back to the original text. Any help would be appreciated.
<script>
function getMsg(text) {
if (text.length == 0) {
document.getElementById("msg").innerHTML = "";
return;
} else {
document.getElementById("msg").innerHTML = "sending request";
var xhttp = new XMLHttpRequest();
var filepath = "";
if (inputText == "File1") {
filepath = "file1.txt";
} else if (inputText == "File2") {
filepath = "file2.txt";
}
xhttp.open("GET", filepath, true);
xhttp.send();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.response);
document.getElementById("msg").innerHTML = this.responseText;
} else {
document.getElementById("msg").innerHTML = "failed";
}
};
}
}
</script>
<body>
<form onsubmit="getMsg(this.file.value)">
<label for="file">File:</label>
<input type="text" name="file" id="file">
<button type="submit">Get</button>
</form>
</body>
This is because you form submits normally along with your ajax and reload the page. You can prevent the form from submitting by returning false from your onsubmit handler.
<form onsubmit="getMsg(this.file.value); return false">
Welcome to Stackoverflow, by reading your code I noticed you got two main issues.
Avoid using innerHTML, it's a bad practice.
When you use innerHTML, even if your string variable is only text (no HTML tags, etc), the content is parsed by JavaScript which takes time, it might not be significant in a small app like this, but in bigger apps this has a big impact in performance.
Use innerText.
You are not preventing the default behavior of your form.
When using AJAX request, the best approach for this is to set an event listener to the form like this:
Your HTML:
<form id="file_select"><!-- Add an id to identify the form -->
<label for="file">File:</label>
<input type="text" name="file" id="file">
<button type="submit">Get</button>
</form>
<div id="msg"></div>
You can add an event listener in JavaScript like this:
document.querySelector("#file_select").addEventListener("submit",(event)=>{
event.preventDefault();
//Your code
});
The preventDefault() function prevents the window redirection to the action attribute of your form. (Default behavior)
Keeping code clean, reusable and simple.
This is the same function with cleaner code, you should try keeping your code easy to read so when you come back to it you understand everything perfectly.
const message = (text) =>{
document.querySelector("#msg").innerText = text; //The message div
};
document.querySelector("#file_select").addEventListener("submit",(event)=>{
event.preventDefault();
let fileValue = event.target.file.value; //The value of the file
if (fileValue != "") { //If value not empty
var xhttp = new XMLHttpRequest();
var filepath = (fileValue === "File1" ? "file1.txt" : (fileValue === "File2") ? "file2.txt" : "");
message("Filepath is: "+filepath);
xhttp.open("GET", filepath, true);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
message.innerText = this.responseText;
} else {
message.innerText = "failed";
}
xhttp.send();
}
} else { //If input is empty
message("Invalid file.");
}
});
<form id="file_select">
<label for="file">File:</label>
<input type="text" name="file" id="file">
<button type="submit">Get</button>
</form>
<div id="msg"></div>
Note: You can use message("text") to output the result of your AJAX request. It's up to you how to fit this to your expected behavior. Hope this helps you.
I'm using JavaScript keyup() event for a single text box.
If someone types “Windows”, it will send an HTTP request for every keyup:
“W”, “Wi”, “Win”, “Wind”, “Windo”, “Window”, “Windows”
This is the desired behaviour.
When the user clears the text box empty, it gives an error.
This is the undesired behaviour.
Question
How can I stop an HTTP request being sent when the text box is cleared?
You can use AJAX to send information to the server (and get information for that matter):
<?php
if (isset($_POST['search'])) {
echo json_encode($_POST);
die();
}
?>
<form>
<input id="search" type="text" name="search" />
</form>
<script>
document.getElementById("search").addEventListener('keyup', function (e) {
var xhr = new XMLHttpRequest();
xhr.open("POST", "#", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.readyState == 4 && xhr.status == 200) {
object = JSON.parse(xhr.responseText);
console.log(object);
}
}
}
xhr.send("search=" + this.value);
});
</script>
Check the value before making request
function getResult(elem) {
if (elem.value !== '') {
console.log('Have values')
} else {
console.log('No values')
}
}
<input type="text" onkeyup="getResult(this)">
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).
I have an HTML page that takes a login from user and authenticates and redirects to the different page. Now i converted this web-page to an app using phonegap app build function. Now i am trying to call the php thats on my server. What is the proper way to do so? Below is the code.
HTML
<script>
function PostData() {
// 1. Create XHR instance - Start
var xhr;
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");
}
// 1. Create XHR instance - End
// 2. Define what to do when XHR feed you the response from the server - Start
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status == 200 && xhr.status < 300) {
document.getElementById('div1').innerHTML = xhr.responseText;
}
}
}
// 2. Define what to do when XHR feed you the response from the server - Start
var userid = document.getElementById("userid").value;
var pid = document.getElementById("pid").value;
// 3. Specify your action, location and Send to the server - Start
xhr.open('POST', 'www.xyz.com/abc/login.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("userid=" + userid + "&pid=" + pid);
// 3. Specify your action, location and Send to the server - End
}
</script>
</head>
<body>
<form>
<label for="userid">User ID :</label><br/>
<input type="text" name ="userid" id="userid" /><br/>
<label for="pid">Password :</label><br/>
<input type="password" name="password" id="pid" /><br><br/>
<div id="div1">
<input type="button" value ="Login" onClick="PostData()" />
</div>
</form>
Try this jQuery.
function PostData() {
$.ajax({
url: "/ajax/login_check.php",
type: "POST",
data: {userid : $("#userid").val(),pid : $("#pid").val()},
cache: false,
success: function (result) {
if(result.statu){
//Valide Div Screen Show
}
else{
//invalide Div Screen Show
}
}
});
}
check Valide Login use Check file
login_check.php
ur Mysql And Php COde Put in this file.
if { //if valide Use than
$responce['statu'] = "1";
$responce['msg'] = "Login success.";
}
else{
$responce['statu'] = "0";
$responce['msg'] = "Invalide Use name & Pass";
}
echo json_encode ($responce);
Exit;
I am developing a web page and the purpose is to perform an http POST from form input elements, in JSON format. While the JSON element to be sent is formed properly, the request is never performed. Here is the code I have been using.
Form
<form id="input" action="javascript:snifForm()" >
User ID:
<input type="text" name="userId" id="userId" required>
Name:
<input type="text" name="name" id="name" required>
<div class="form-submit"><input type="submit" value="Submit" color="#ffffff" > </div></p>
</form>
Javascript (JSON.js, JSONRequest.js and JSONRequestError.js are imported)
<script type="text/javascript">
var requestNumber;
function snifForm()
{
var a1=document.getElementById("userId").value;
var a2=document.getElementById("name").value;
var toSend= {interactions: {id_user:a1, id_name:a2}};
var jToSend=JSON.stringify(toSend);
requestNumber = JSONRequest.post(
"http://someurl.com",
jToSend,
function (requestNumber, value, exception) {
if (value) {
processResponse(value);
alert(value);
} else {
processError(exception);
}
}
);
alert(requestNumber);
}
</script>
I also tried the more classic form:
var xmlhttp = new XMLHttpRequest();
var out;
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
out = xmlhttp.responseText;
alert(out);
}
else alert('nothing');
}
xmlhttp.open("POST", "the_same_url", true);
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(jToSend);
After checking the server logs, no post is done ever :/
You should be attaching the event to the submit action of the form and you need to make sure to cancel the submit action.
I would not add the events directly to the form, but it is
<form id="input" onsubmit="snifForm(); return false;">