简体   繁体   中英

Sending AJAX POST to PHP is not working?

I swear this was working properly earlier, but now it's not so I clearly messed something up.

I'm making a form where the inputted info gets AJAX posted to my PHP file, which just outputs the username and password. Right now I even hardcoded the data being sent to just a string and the php file just printing that for testing purposes. However, when I click submit, it doesn't go to my loginProcess.php page, but it just stays on the page and prints to the console "hello","success", and "test", which indicates it went through the full Process() function.

My url is correct and in the same directory as the index.html file. I've tried different things such as using $.post() or making the submit button a type="input" . If you see the form line I commented out before the non-commented one, that's me trying to send the data directly without going through ajax and it works fine and outputs the loginProcess.php (however my project requires going through ajax). Anyone know what's going on?

Here's my html file:

<!DOCTYPE html>
<html>
<head>
   <!-- <script src="frontEnd.js"></script> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>      
<title>Login System</title>
</head>
<style>
</style>

<body>
    <center>
        <p><b>LOGIN SYSTEM</b></p>
        <!-- <form id="login" action ="loginProcess.php" method="post">  -->
        <form name = "loginform">
            UCID:<br>
            <input type="text" name="username"><br>
            Password:<br>
            <input type="password" name="password"><br><br>
            <button type="button" onclick = "Process()">Submit</button>
        </form>
    </center>


</body>
 <script>
    function Process() {
        console.log("hello")
        var ucid = document.loginform.username.value;
        var pw = document.loginform.password.value;
        $.ajax({
            type:"POST",
            url: "loginProcess.php",
            data: "ajaxUCID=TESTUSERNAME",
            success: function(){
                console.log("success")
            },
            error: function(){
                console.log("error")
            }
        });
        // $.post("loginProcess.php",{ajaxUCID:"TESTUSERNAME"});
        console.log("test")
    }
 </script>

Here's my loginProcess.php file:

<!DOCTYPE html>
<html>
<head><title>process</title></head>
<body>
<?php
$ucidPHP = $_POST["ajaxUCID"];
echo "Username is ".$ucidPHP;

// $pwPHP = $_POST["ajaxPW"];
// echo "Password is ".$pwPHP;
?>
</body>
</html>

Try this -

 <script>
    function Process() {
        var ucid = document.loginform.username.value;
        var pw   = document.loginform.password.value;
        $.ajax({
            type:"POST",
            url: "loginProcess.php",
            data: {ajaxUCID:TESTUSERNAME},
            success: function(){
                console.log("success")
            },
            error: function(){
                console.log("error")
            }
        });
    }
 </script>

Hope this will work for you.

When you click on your network tab of Google chrome or equivalent of the other browser and then send your Ajax request to observe your packet delivered what result do you have ?

If you have a packet with an error can you tell us witch one, and if you receive a good header (without errors) , check the information inside it to see if it throws correct informations, like the data form in your Ajax post.

After that if the information are correct and the data structure is correct, to test, I usually do the following code to test the entire post received :

if(isset($_POST)){
  var_dump($_POST); // this will show all posts received 
}

Let me know if it works for you ;)

I don't get your problem, the code is working with me and returning the result successfully.

I think you mean that why the returned results doesn't show on the same page of the form.

Here is the correct code and below it is the explanation

index.php

    <!DOCTYPE html>
<html>
<head>
   <!-- <script src="frontEnd.js"></script> -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>      
<title>Login System</title>
</head>
<style>
</style>

<body>
    <center>
        <p><b>LOGIN SYSTEM</b></p>
        <!-- <form id="login" action ="loginProcess.php" method="post">  -->
        <form name = "loginform">
            UCID:<br>
            <input type="text" name="username"><br>
            Password:<br>
            <input type="password" name="password"><br><br>
            <button type="button" onclick = "Process()">Submit</button>
        </form>
    <div id="responseFromServer"></div>
    </center>


</body>
 <script>
    function Process() {
        console.log("hello")
        var ucid = document.loginform.username.value;
        var pw = document.loginform.password.value;
        $.ajax({
            type:"POST",
            url: "loginProcess.php",
            data: {"ajaxUCID":ucid},
            success: function(response){
        document.getElementById("responseFromServer").innerHTML =   response;
                console.log("success")
            },
            error: function(){
                console.log("error")
            }
        });
        // $.post("loginProcess.php",{ajaxUCID:"TESTUSERNAME"});
        console.log("test")
    }
 </script>

the code you provided was actually working properly, its just you didn't pick the result to display it on your page. that was done by adding a div where I will place the response.

    <div id="responseFromServer"></div>

and in the success callback of the ajax call, I just catched the response sent back from the server and placed it right inside the div, like so:

        document.getElementById("responseFromServer").innerHTML =   response;

That should work

Update#1: He wanted to redirect to the php page.

in plain English, you should use ajax requests when you want to work with the server, send requests or get results without reloading the page, you can read more here Getting Starting with AJAX

AJAX stands for Asynchronous JavaScript And XML. In a nutshell, it is the use of the XMLHttpRequest object to communicate with servers. It can send and receive information in various formats, including JSON, XML, HTML, and text files. AJAX's most appealing characteristic is its "asynchronous" nature, which means it can communicate with the server, exchange data, and update the page without having to refresh the page.

so in your case that you want to redirect the user, you don't really want to use ajax in this case you can simply do that with plain html form tag.

a form tag can have multiple attributes, here we are concerned with 2 :

  1. action
  2. method

Here is how you can update the code to get to your results

first: the form part:

<form name = "loginform" method="POST" action="loginProcess.php">
            UCID:<br>
            <input type="text" name="ajaxUCID"><br>
            Password:<br>
            <input type="password" name="password"><br><br>
            <button type="submit" >Submit</button>
        </form>

I've added 2 attributes, which are:

  1. method: I set it to POST, because this is the http request type which you accept on your server [your PHP file you used $_POST].
  2. action: I set it to the relative path of the file which should recieve your request, in our case its "loginProcess.php"

Then I changed the name of the input where we enter the username or UCID to be the same as the one you are receiving in your PHP file. in your php you were accepting a request parameter $_POST["ajaxUCID"] this means that you are accepting a POST request and you want a parameter called ajaxUCID , that must be the name of the input. this is why I did that <input type="text" name="ajaxUCID">

I have also stopped the onClick action on the button to prevent the ajax request, also I have changed its type to "submit" so that once its clicked, it will automatically submit the form for you.

I hope that helped now, if you need furthur help, leave a comment

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