I am using plain javascript for Ajax request. when sending data by post method php throwing an error.
index.php
<html>
<header>
<script>
function submit(){
var userName = document.getElementById("username").value;
var passWord = document.getElementById("password").value;
var data = "username=" + userName + "&password=" + passWord;
//send ajax request
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
console.log(xmlHttp.responseText);
}
}
xmlHttp.open("post", "validateuser.php");
xmlHttp.send(data);
}
</script>
</header>
<body>
<label>User Name : </label>
<input type="text" name="username" id="username"/>
<label>Password : </label>
<input type="text" name="password" id="password"/>
<button onClick="submit()"> Login</button>
</body>
</html>
validateuser.php
<?php
$userName = $_POST["username"];
$password = $_POST["password"];
echo $userName . $password;
In Javascript ajax for post you need to add following line in your code:
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
You can check documentation and example W3schools and developer mozilla
And for more reliable code just add following line to your php code
if(isset($_POST['username']) && isset($_POST['password'])){
//your code
}
You need to set the headers on your xmlHttp object. Add the following line before xmlHttp.send(data); line :
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
Related
Completely flummoxed after going over and over this problem for hours. Have tried a large number of approaches, without success.
Intent is to send login form data to PHP and have PHP return the result of an API call.
My latest approach is to have form onSubmit in login.html call myFunction() which performs POST call to n_authorise.php for some server side processing. In future the PHP will return API secrets. For my testing I stripped back the PHP to echo back the user input extracted from the $_POST global.
No matter what combinations of form ACTION / SUBMIT or XMLHttpRequest structures I try, I can't seem to pass the $_POST from the HTML to the PHP. I repeatedly get "Undefined index" from the PHP suggesting the $_POST is not populated.
I have tried action="n_authorise.php" directly in the form (avoiding myFunction() ) but this either fails or when it does work loads the PHP file to the browser NOT just returning the result.
I am so frustrated as it has to be possible and I can see from other postings that they have had (and resolved) similar problems... I just can't crack it, so asking the experts! Thanks in advance.
My HTML in file login.html :
<html>
<head>
<script>
function myFunction() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
};
xmlhttp.open("post", "n_authorise.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
</script>
</head>
<body>
<form name="loginform" onsubmit="myFunction()" method="post">
<input type="text" name="t_username" id="t_username" placeholder="Username" required autofocus>
<input type="password" name="t_password" id="t_password" placeholder="Password" required>
<input name ="submit" type="submit" value="submit">
</form>
</body>
</html>
My minimal PHP in file n_authorise.php
<?php
$email = $_POST["t_username"];
$password = $_POST["t_password"];
echo $email . " " . $password;
?>
Expected result is for alert box to display entered email & password (this would be replaced in final version).
Note: I have tried with and without xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");. In fact, I think I've tried nearly every possible combination of code without success... yet.
This is a most simple answer:
you are not adding any parameters to your request, you could do it with native js like this:
var form = document.querySelector('form'); // <-- extend this to select your form, maybe add an id to select
var data = new FormData(form);
var req = new XMLHttpRequest();
req.send(data); // <----- this way the form data is appended
Based on the above - sharing working code with humble thanks. FYI only:
<html>
<head>
<script>
function myFunction() {
var form = document.querySelector('form.loginform'); // <-------- extended to select new class ID for form
var data = new FormData(form); // <-------- 'data' extracts form content
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
};
xmlhttp.open("post", "n_authorise.php", true);
xmlhttp.send(data); // <-------- 'data' sent to PHP!
}
</script>
</head>
<body>
<form name="loginform" class="loginform" onsubmit="myFunction()" method="post">. // <-------- new class added
<input type="text" name="t_username" id="t_username" placeholder="Username" required autofocus>
<input type="password" name="t_password" id="t_password" placeholder="Password" required>
<input name ="submit" type="submit" value="submit">
</form>
</body>
</html>
I am trying to create a page whereby you can submit some text and then retrieve it on button press, I have managed to get it to submit to my server, however on retrieval I keep getting the error "unexpected end of JSON input" and have no idea what to do about it, my knowledge of PHP/JSON is very limited, any criticism / pointers are greatly appreciated.
JS:
function writeDoc() {
var xhttp = new XMLHttpRequest();
var url = "gethint.php";
var input = document.getElementById("text").value;
var clicker = document.getElementById("submit");
xhttp.open("POST", "gethint.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
alert("DataSubmitted");
}
}
xhttp.send("input= " + input);
}
function readDoc() {
var xxhttp = new XMLHttpRequest();
xxhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
var data = JSON.parse(this.responseText);
alert(data);
}
}
xxhttp.open("GET", "gethint2.php", true);
xxhttp.send();
}
PHP/HTML:
<php? session_start(); ?>
<html>
<script type="text/javascript" src="main.js"></script>
<head>
</head>
<body>
<label>Text Input To Save: </label>
<br></br>
<textarea rows="6" cols="20" id="text" name="textInput"></textarea>
<input type="submit" id="submit" onclick="writeDoc()">
<br></br>
<label>Retrieve Text :</label> <input type="button" id="getText"
onclick="readDoc()">
</body>
</html>
Sending Data:
<?
$_SESSION["input_data"] = $_POST;
echo $_POST["input"];
?>
Retrieving Data:
<?php
$_SESSION["input_data"] = json_encode($_POST);
?>
I want to post login email and password to a PHP page using AJAX
<form onsubmit="authenticate()">
<input type="text" placeholder="E-mail" name="email" id="email" />
<input type="password" placeholder="Password" name="password" id="password" />
<input type="submit" value="Login"/>
</form>
AJAX:
function authenticate() {
var email = document.getElementById("email").value;
var pass = document.getElementById("password").value;
var params = 'email=' + email + '&pass=' + pass;
var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "http://127.0.0.1/login/login.php";
httpc.open("POST", url, true); // sending as POST
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.setRequestHeader("Content-Length", params.length); // POST request MUST have a Content-Length header (as per HTTP/1.1)
httpc.onreadystatechange = function() { //Call a function when the state changes.
if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
if(httpc.responseText == "success") {
window.location.replace("files.html");
}
else if (httpc.responseText == "fail")
alert("Invalid details");
}
httpc.send(params);
}
}
If the select query returns a row after authentication, it echoes "success, else it echoes "fail"
I think your problem is that you're sending your params from inside the function onreadystatechange, it probably doesn't work at all right now, because the "state" will change once you send something, but your code doesn't send anything until the "state" has changed... This should fix it:
function authenticate() {
var email = document.getElementById("email").value;
var pass = document.getElementById("password").value;
var params = 'email=' + email + '&pass=' + pass;
var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "http://127.0.0.1/login/login.php";
httpc.open("POST", url, true); // sending as POST
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.setRequestHeader("Content-Length", params.length); // POST request MUST have a Content-Length header (as per HTTP/1.1)
httpc.onreadystatechange = function() { //Call a function when the state changes.
if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
if(httpc.responseText == "success") {
window.location.replace("files.html");
}
else if (httpc.responseText == "fail")
alert("Invalid details");
else
alert(httpc.responseText);
}
// Your httpc.send was here
}
httpc.send(params); // <-- should be here
}
You must also change your HTML to add a return false; after the call to the authenticate function, in order to prevent the form from doing its "default" action (submitting to itself, in "GET" mode).
<form onsubmit="authenticate(); return false;">
<input type="text" placeholder="E-mail" name="email" id="email" />
<input type="password" placeholder="Password" name="password" id="password" />
<input type="submit" value="Login"/>
</form>
<html>
<head>
<script language="JavaScript" type="text/javascript">
function ajax_post(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "index2.php";
var fn = document.getElementById("first_name").value;
var ln = document.getElementById("last_name").value;
var vars = "firstname="+fn+"&lastname="+ln;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
<h2>Ajax Post to PHP and Get Return Data</h2>
Your First Name: <input id="first_name" name="first_name" type="text" />
<br /><br />
Your Last Name: <input id="last_name" name="last_name" type="text" />
<br /><br />
<input name="myBtn" type="submit" value="Submit Data" onClick="javascript:ajax_post();">
<br /><br />
<div id="status"></div>
</body>
</html>
<?php
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
?>
The code above works and submits the data and gets the result, along with the result it renders the form again. Image --> http://oi47.tinypic.com/1bt02.jpg
How to fix it?
Thanks in advance.
Don't include the form in the response you send to the Ajax request.
So I'm new to AJAX (not as new to PHP), and I'm trying to create a login using AJAX to query the PHP file. So, this is the code I'm trying to use.
I have three files. The first one is login_form.php. It contains the login form...
<html>
<head>
<title>Log In</title>
<script language="javascript" src="loginsender.js" />
</head>
<body>
<form method="post" name="loginfrm" onsubmit="formValidator()">
<p id="hint"></p>
<label for="username">Username:</label><input type="text" name="username" id="username" />
<label for="password">Password:</label><input type="password" name="password" id="password" />
<input type="submit" name="submit" value="Log In" />
</form>
</body>
</html>
The next loginsender.js. This is the JavaScript/AJAX file I'm using to send to the PHP script...
function formValidator()
{
if (document.loginfrm.username.value.length < 3 || loginfrm.password.value.length < 3)
{
msg = "Please enter a valid username/password."
document.getElementById("hint").innerHTML=msg;
}
else
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("hint").innerHTML = xmlhttp.responseText;
}
}
}
var params = "username=" + document.loginfrm.username.value + "&password=" + document.loginfrm.password.value;
xmlhttp.open("post", "login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
The last one is login.php, which is what I'm using to handle the actual logging in...
<?php
session_start();
require_once("includes/mysql.inc.php");
require_once("includes/functions.inc.php");
$username = sanitize($_POST['username'], true);
$password = sanitize($_POST['password'], true);
$query = "SELECT * FROM users WHERE username = '$username'";
$result = mysql_query($query);
if (mysql_num_rows($result) != 1) // no such user exists
{
echo 'Sorry, no such user exists';
logout();
die();
}
$userData = mysql_fetch_assoc($result);
$hash = hash('sha256', $userData['salt'] . hash('sha256', $password));
if ($hash == $userData['password'] && $username == $userData['username']) // successful log in
{
validateUser($userData['username']); // set session data
echo '<meta http-equiv="refresh" content="2; url=index.php" />';
}
else
{
echo 'Sorry, but you entered an incorrect username/password.';
logout();
die();
}
?>
All in all, the goal is to have the user enter their username and password combination in login_form.php and submit it, triggering loginsender.js (and the formValidator() method). This then will query the PHP login script, which will test for a valid user/pass combo, then set it up in the session (or not, if the log in failed). The issue is, no matter what combination I enter, nothing happens, the page refreshes upon clicking submit, but that's it.
**UPDATE 1:
I have edited my login_form page, I've simply put the formValidator function into the script to start with, that way its easier for me to look at rather than flipping between documents.
I also implemented some of the suggestions that were made.
Here it is:
<html>
<head>
<title>Log In</title>
<script type="text/javascript" language="javascript">
function formValidator()
{
if (document.loginfrm.username.value.length < 3 || loginfrm.password.value.length < 3)
{
msg = "Please enter a valid username/password."
document.getElementById("hint").innerHTML=msg;
}
else
{
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("hint").innerHTML = xmlhttp.responseText;
}
}
}
var params = "username=" + document.loginfrm.username.value + "&password=" + document.loginfrm.password.value;
xmlhttp.open("post", "login.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}
</script>
</head>
<body>
<p id="hint"></p>
<form method="post" name="loginfrm" onsubmit="formValidator(); return false;">
<label for="username">Username:</label><input type="text" name="username" id="username" />
<label for="password">Password:</label><input type="password" name="password" id="password" />
<input type="submit" name="submit" value="Log In" />
</form>
</body>
</html>
It doesn't look like you're preventing the default 'submit' action from happening, which since you haven't defined a action for the form is to just POST back to the current page.
Change your form html line to:
<form method="post" name="loginfrm" onsubmit="formValidator(); return false;">
The return false; tells it to NOT do whatever it was going to do for that action.
If you don't want the Form-submit-action to refresh the page, return false from your onsubmit script. Otherwise, the browser will do exactly what you tell him in the <form>: a HTTP POST.
I think the OnSubmit() function is executed and also the form is really submitted! So you get a blank page which is the output of php script.
Don't make it a html-form and it should work fine.
You need to write this to prevent form refresh..
<form method="post" name="loginfrm" onsubmit="formValidator(); return false;">
other than this, your code is fine..
try this
<input type="submit" name="submit" value="Log In" onclick="formValidator(); return false;"/>