2

Im trying to insert data into my database with AJAX but dont working. I can verify that im connected to the database but when i click it doesnt insert the data. thanks

with a click function i take the 2 parameter that i wanna insert in my database.

$( "#q_answer1" ).click(function () {
      var q_no = $("#q_no").val(); 
      var main_no = $("#total_no").val();

      $.ajax({
         url: "server.php",
         type: "post",
         async: false,
         data: {
            "done": 1,
            "username": q_no,
            "comment": main_no

         }, 
         success: function(){
            $("#q_no").val('');
            $("#total_no").val('');
         }
      });
  });

And here is the php file, first connect to the ddbb and insert the 2 values with the mysql_query.

<?php
include("dbh.php");
if (isset($_POST['done'])) {
   $q_no = mysql_escape_string($_POST['username']);
   $total_no = mysql_escape_string($_POST['comment']);

   mysql_query("INSERT INTO variables(id, names) VALUES('{$q_no}', '{$total_no}')");
   exit();
}
?>

html is like this:

<div id="total_no">1</div>
<div id="q_answer1" class="btn left_b">yes</div>

3

4 Answers 4

1

I think you should use PDO, to connect to the database instead of the old driver, which PHP no longer supports. with PDO you can use prepared statements to prevent sql injections

PDO tutorial

filter_var() Constants

dbh.php

$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = 'db';

try {

  $db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  }
  catch(PDOException $e)
  {
    exit($e->getMessage());
  }

?>

serve.php

<?php

include("dbh.php");
if (isset($_POST['done'])) {

   $q_no = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
   $total_no = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);

try {

  $stmt = $db->prepare("INSERT INTO variables(id, names) VALUES(?, ?)");
  $stmt->execute(array($q_no, $total_no));

  echo json_encode(["message" => "success"]); // sends success response to front-end 

} catch (\Exception $e) {
  echo json_encode(["message" => $e->getMessage() ]); // sends error response to front-end
}


}
 ?>

in your ajax check if the data was inserted or not.

$("#q_answer1").click(function() {
  var q_no = $("#q_no").val();
  var main_no = $("#total_no").val();

  $.ajax({
    url: "file.php",
    type: "post",
    async: false,
    data: {
      "done": 1,
      "username": q_no,
      "comment": main_no

    },
    success: function(data) {

      const respose = JSON.parse(data);

      if (respose.message === 'success') { // data was inserted 

        $("#q_no").val('');
        $("#total_no").val('');

      }else {
        alert(respose.message); // some error has occured
      }
    }
  });
});
Sign up to request clarification or add additional context in comments.

2 Comments

@junius-ln i got this error after implementing your code: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'id' at row 1
@Jacofki it means you tried to insert a string into integer column. stackoverflow.com/questions/29462919/…
0

You have to take value of div as mentioned below,

var q_no = $("#q_no").text(); 
var main_no = $("#total_no").text();

Pass data in key-value Pair, After pass first key-value data concate other data with & sign key.

$( "#q_answer1" ).click(function () {
          var q_no = $("#q_no").val(); 
          var main_no = $("#total_no").val();

          $.ajax({
             url: "server.php",
             type: "post",
             async: false,
             data: 'done=' + 1 + '&username=' + q_no + '&comment=' + main_no,
             success: function(){
                $("#q_no").val('');
                $("#total_no").val('');
             }
          });
      });

Comments

0

You can't use val() on div. Try using text() and then check if your server.php is getting these value.

Thanks

Comments

0

You have typo error in jquery

$qAnswer1.click(function () {

Should be

$('#q_answer1').click(function () {

You can try following to test

$( "#q_answer1" ).click(function() {
  alert( "Handler for .click() called." );
});

Include the jquery at the top of your page

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Full working code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="total_no">1</div>
<div id="q_answer1" class="btn left_b">yes</div>
<script type="text/javascript">
  $( "#q_answer1" ).click(function () {
    var q_no = $("#q_no").val(); 
    var main_no = $("#total_no").val();

  $.ajax({
     url: "ajax.php",
     type: "post",
     async: false,
     data: {
        "done": 1,
        "username": q_no,
        "comment": main_no

     }, 
     success: function(){
        $("#q_no").val('');
        $("#total_no").val('');
     }
  });
});
</script>

in your PHP file try to print $_POST to see its working.

5 Comments

@Jacofki have you included jquery at the top ?
@its working, if you click on yes , try the handler code
Thanks @rakesh-jakhar, after that change i get a 500 (Internal Server Error) in the server.php (for you ajax.php).
make sure the path of server.php
is correct, and also i get this message: [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check xhr.spec.whatwg.org.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.