简体   繁体   中英

Using AJAX to send form information to another page using a button

Hello I have two files that are supposed to be connected to one another. I want to send an AJAX request to another page that uses a sql query to send form information.

The application that I'm trying to create is a questionnaire with eight questions, each questions has four answers paired together with the same id (qid) and each answer has a value from the database. After you answer eight questions you will see a button that sends an AJAX request to the page test.php, (named submitAJAX).

The problem is that although my connection with AJAX is working, the values from the form are not being sent to my database. Previously I thought that the problem may lie with the form page, but now II think the problem lies in this file:

test.php (file with json)

<?php
$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password) or die ("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');
if(count($_GET) > 0){
   $answerPoint = intval($_GET['radiobtn']);
   $qid = intval($_GET['qid']);
$tid = intval($_GET['tid']);
   $sql2 = "INSERT INTO result (qid, points, tid) VALUES ($qid, $answerPoint, $tid)";
   $connect->query($sql2); 
   $lastid = $connect->insert_id;
   if($lastid>0) {
    echo json_encode(array('status'=>1));
}
   else{
    echo json_encode(array('status'=>0));
} 
}
?>

I think that the problem may lie in the row where: if($lastid>0) { $lastid should always be more than 0, but whenever I check test.php I get this message: {"status":0} What's intended is that I get this message: {"status":1}

<html>
    <head>
        <meta charset="utf-8">
    </head>
    <body>
<?php
$localhost = "localhost";
$username = "root";
$password = "";
$connect = mysqli_connect($localhost, $username, $password) or die ("Kunde inte koppla");
mysqli_select_db($connect, 'wildfire');

$qid = 1;
if(count($_POST) > 0){
    $qid = intval($_POST['qid'])+1;

}


?>

<form method="post" action="">
<input type="hidden" name="qid" id="qid" value="<?=$qid?>">
<?php
$sql1 = mysqli_query($connect,"SELECT * FROM question where answer != '' && qid =".intval($qid));
while($row1=mysqli_fetch_assoc($sql1)){
?>
<input type='radio' name='answer1' class="radiobtn" value="<?php echo $row1['Point'];?>">
<input type='hidden' name='tid' class="tid" value="<?php echo $row1['tid'];?>">
<?php echo $row1['answer'];?><br>
<?php
}
?>
<?php if ($qid <= 8) {  ?>
<button type="button" onclick="history.back();">Tillbaka</button>
<button type="submit">Nästa</button>
<?php } else { ?>
<button id="submitAjax" type="submit">Avsluta provet</button>
     <?php } ?>  
</form>

<script src="https://code.jquery.com/jquery-1.11.3.js"></script> 
  <script type="text/javascript">
function goBack() {
    window.history.go(-1);
}
$(document).ready(function(){ 
$("#submitAjax").click(function(){
        if($('.radiobtn').is(':checked')) { 
            var radiobtn = $('.radiobtn:checked').val();
            var qid = $('#qid').val();            
             var answer = $('input[name=answer1]:radio').val();
            $.ajax(
            {
                type: "GET",
                url: 'test.php',
                dataType: "json",
                data: "radiobtn="+radiobtn+"&qid="+qid,
                success: function (response) {
                    if(response.status == true){
                        alert('points added');
                    }
                    else{
                        alert('points not added');   
                    }
                }
            });

            return false;
        }
    });
});
  </script>

    </body>

The values that I want to send to my database from test.php are:

qid(int), tid(int), Point(int)

There is a database connection, and my test.php file's sql query should work, but its not sending form information. Is there something that I need to rewrite or fix to make it work?

First , your data parameter in the AJAX call is not using the correct syntax. You're missing brackets. It should look like:

data: JSON.stringify({ radiobtn: radiobtn, qid: qid }),

Second , I'd suggest using POST instead of GET:

type: "POST",

which means that you need to look for your data in $_POST['radiobtn'] and $_POST['qid'] on test.php. NOTE: you should check for the key you expect using isset() before assigning the value to a variable, like so:

$myBtn = isset($_POST['radiobtn']) ? $_POST['radiobtn'] : null;

Third , for testing, use a console.log() inside your condition that checks for the checkbox being checked in order to verify that condition is working as expected.

if($('.radiobtn').is(':checked')) {
    console.log('here');

UPDATE:

Fourth: You should specify the content type in your AJAX call, like so:

contentType: "application/json; charset=utf-8",

mysqli_insert_id() returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute.

In your SQL, you are providing the ID yourself, there is no auto-increment. So you should get 0 from $connect->insert_id , because the function returns zero if there was no previous query on the connection or if the query did not update an AUTO_INCREMENT value .

For your purpose, you can use the return value of mysqli_query() instead, which returns TRUE on success and FALSE on failure.

if($connect->query($sql2)) {
   echo json_encode(array('status'=>1));
}
else{
   echo json_encode(array('status'=>0));
} 

After you execute your query that inserts the result you can use a sql statement to select the last insert id. Try something like

$sql2 = "INSERT INTO result (qid, points, tid) VALUES ($qid, $answerPoint,         $tid)";
$connect->query($sql2); 
$result = $connect->query("SELECT LAST_INSERT_ID()");
$row = $result->fetch_row();
$lastid = $row[0];

That should return the correct last insert id, if that was where your error was occurring.

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