简体   繁体   中英

Passing prompt data from javascript to php using ajax

First of all i know there are multiple topics about this on stackoverflow, i read most of them but i still cant figure out why the following is not working.

So i have a form like this:

echo "<td> <form action=\"admin.php\" method=\"GET\" onsubmit=\" modifyPassword();\">

this is the modifyPassword function:

function modifyPassword(){
   var newpw=prompt("Enter a new password");
   if(newpw !== null){
   $.ajax({
           type: "GET",
           url: "admin.php",
           data: newpw,
           success: function(data)
            {
              console.log(data);
            }
            });
            }}

And when the form is actually submitted i want to get the value from what is typed in like this:

echo $_GET['data'];

This is all in the same file. The output of $_GET['data'] does not show anything.

Can someone tell me what i am doing wrong?

//edit, more code: I am using multiple forms, so here is the code that handles the form:

}elseif (isset($_GET['Modify'])){


        echo $_GET['data'];

Form itself:

echo "<td> <form action=\"admin.php\" method=\"GET\" onsubmit=\" modifyPassword();\">
                         <input type='hidden' name='counter' value=\"$count\"/> 
                         <input type=\"submit\" value=\"Modify\" name=\"Modify\"/>

Function that is provided:

<script type="text/javascript">
                        function modifyPassword(){

                            var newpw=prompt("Enter a new password");
                            if(newpw !== null){
                                $.ajax({
                                    type: "GET",
                                    url: "admin.php",
                                    data: {data: newpw}, // passing a key/value pair
                                    success: function(data)
                                    {
                                        console.log(data);
                                    }
                                });
                            }}
                        </script>

data: newpw, should be data: {data: newpw}, This will result in $_GET['data'] being populated. In this case 'data' becomes the key, while 'newpw' is the value.

function modifyPassword(){
   var newpw=prompt("Enter a new password");
   if(newpw !== null){
       $.ajax({
           type: "GET",
           url: "admin.php",
           data: {data: newpw}, // passing a key/value pair
           success: function(data)
            {
              console.log(data);
            }
       });
   }}

I will argue that you should not use so many variables with the same name - just to make things less confusing during bug hunting.

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