简体   繁体   中英

PHP, send data from javascript to PHP using AJAX

Still havent solved this. Can someone help me with my new, updated code. The new code is at the bottom of this post.

Im learning PHP and right now Im trying to learn to pass data from JS to PHP using AJAX.

This is my form:

<form id="login">
            <label><b>Username</b></label>
            <input type="text" name="username" id="username"
                   required>
            <label><b>Password</b></label>
            <input type="password" name="password" id="password"
                   required>
            <button type="button" id="submitLogin">Login</button>
        </form>

First I have a function, something like this:

try {
    if (window.XMLHttpRequest) {
        request = new XMLHttpRequest();
    }else{
      Do stuff }
    }
 catch(error){ alert('"XMLHttpRequest failed!' + error.message); }

After this, Im trying to send my form data to a php-file, using new FormData(), but Im not really sure how to do this. Right now I have a code like this:

if (getElementById('username').value != "" & getElementById('password').value != "") {
    request.addEventListener('readystatechange', Login, false);
    request.open('GET', 'login.php', true);
    request.send(new FormData(getElementById('login')));
}

The login-function is a function to test

if (request.readyState === XMLHttpRequest.DONE && request.status === 200) {

In my PHP-file I have a function looking like this right now:

session_start();
$logins = array('username1' => 'password1','username2' => 'password2');

if(isset($_GET['login'])) {
$Username = isset($_GET['username']) ? $_GET['username'] : '';
$Password = isset($_GET['password']) ? $_GET['password'] : '';

if (isset($logins[$Username]) && $logins[$Username] == $Password){
do stuff
}

What more do I need to pass my form data from the js-file to the php-file, so I can check if the input data is the same as the data I have in the array?

-----------------------------------------------------------------------

New code:

function LoginToSite() {
if (getElementById('username').value != "" && getElementById('password').value != "") {
    request.addEventListener('readystatechange', Login, false);

    var username = encodeURIComponent(document.getElementById("username").value);
    var password = encodeURIComponent(document.getElementById("password").value);


    request.open('GET', 'login.php?username='+username+"&password="+password, true);
    request.send(null);
}

}

function Login() {
if (request.readyState === 4 && request.status === 200) {
    alert("READY");
    var myResponse = JSON.parse(this.responseText);
    getElementById("count").innerHTML = myResponse;
    getElementById('login').style.display = "none";
    if(request.responseText == 1){
        alert("Login is successfull");
    }
    else if(request.responseText == 0){
        alert("Invalid Username or Password");
    }
}
else{
    alert("Error :Something went wrong");
}
request.send();

}

session_start();
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
 if($username != '' and $password != ''){

foreach($user_array as $key=>$value){
    if(($key == $username) && ($value == $password)){
        echo "1";
    }else{
        echo "0";
    }
}

}else{
echo "0";
}

When im trying to login, the site first alert that something went wrong, then the same thing happens again and after that, it alerts "ready". What do I have to change to get this right?

Try running the following code.

HTML :

<form id="login">
        <label><b>Username</b></label>
        <input type="text" name="username" id="username"
               required>
        <label><b>Password</b></label>
        <input type="password" name="password" id="password"
               required>
        <button type="button" id="submitLogin">Login</button>
    </form> 

JavaScript:

function submitLogin{
var username = document.getElementById("username").value;
    var password = document.getElementById("password").value;
    var http = new XMLHttpRequest();
    var url = "login.php";
    var params = "username="+username+"&password="+password;
    http.open("POST", url, true);

    //Send the proper header information along with the request
    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    http.onreadystatechange = function() {//Call a function when the state changes.
        if(http.readyState == 4 && http.status == 200) {
            if(http.responseText == 1){
            alert("Login is successfull");
            }
            else{
            alert("Invalid Username or Password");
            }
        }
        else{
        alert("Error :Something went wrong");
        }
    }
    http.send(params);
}

PHP:

<?php
session_start();
$logins = array('username1' => 'password1','username2' => 'password2');
if(isset($_POST['username']) && isset($_POST['password'])){
$username = trim($_POST['username']);
$password = trim($_POST['password']);
foreach($logins as $key=>$value){
if(($key == $username) && ($value == $password)){
echo "1";
}else{
echo "0";
}
}

}else{
echo "0";
}

?>

I hope this helps you.

Basically you need something like this (JS side)

 // create and open XMLHttpRequest
 var xhr = new XMLHttpRequest;
 xhr.open ('POST', 'login.php'); // don't use GET


 // 'onload' event to handle response
 xhr.addEventListener ('load', function () {
     if (this.responseText == 'success')
         alert ('successfully logged in.');
     else
         alert ('failed to log in.');
 }, false);


 // prepare and send FormData
 var fd = new FormData;
 fd.append ('username', document.getElementById("username").value);
 fd.append ('password', document.getElementById("password").value);
 xhr.send (fd);

PHP code ( login.php ) may look like this.

 # users array
 $logins = array ( 'username1' => 'pwd1', 'username2' => 'pwd2' );

 # validate inputs
 $u = isset ($_POST['username']) ? $_POST['username'] : false;
 $p = isset ($_POST['password']) ? $_POST['password'] : false;

 # check login
 if ($u !== false && $p !== false && isset ($logins[$u]) && $logins[$u] == $p)
     echo "success";
 else
     echo "error";

Course, it's recommended to check do functions XMLHttpRequest and FormData exist first.

 if (window['XMLHttpRequest'] && window['FormData']) {

     /* place your Ajax code here */

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM