weixin_33726943 2015-10-24 04:16 采纳率: 0%
浏览 29

来自PHP的JQuery AJAX响应

I want to select data from database and show it in a div using PHP response. I am inserting data which is working fine for me but don't know what to do in PHP file for response and how to use it in AJAX done function. I am sharing my code here. Please help me if you can.

Script:

$(document).ready(function(){

$("#submit_btn").click(function(){

        var all_ok = 1;

        if ($("#course_name").val() === '') {
            $('#course_name_error').show();
            all_ok = 0;
        } else {
            $('#course_name_error').hide();
        }
        if (all_ok === 1) {
            var username = $("#username").val();
            var password = $("#password").val();

$.ajax({
  method: "POST",
  url: "login.php",
  data: { name: username, password: password }
})
  .done(function(data) {
    $("#success").text("Data added Successfully!").show();
});
}
});


});

HTML Part:

<form >
Name:<input type="name" name="name" id="username" />
<p id="username_error" style="color:red; display:none;">Enter a username.</p>
Password:<input type="password" name="password" id="password" />
<p id="username_error" style="color:red; display:none;">Enter a password.</p>
<button type="button" value="subbtn" id="submit_btn">Submit</button>
</form>

PHP:

<?php 

    $name = $_POST['name'];
    $pass = $_POST['password'];
    if((isset($name) && isset($pass))){

         include 'connection.php';
         $sql = "INSERT INTO `log_in` (id, name, password) VALUES (NULL, '$name', '$pass');";
         if (mysqli_query($conn, $sql)) {

         } 
         else {
           die( "Error: " . $sql . "<br>" . mysqli_error($conn));
         }
    }

Thanks in advance.

  • 写回答

3条回答 默认 最新

  • weixin_33716557 2015-10-24 04:36
    关注

    To answer just your question, in your code

    if (mysqli_query($conn, $sql)) {
      // you could use affected rows to see if the insert was a success
      //that would be your response, the program exit and 1 is send back
      exit(1);
    }
    

    Back in your javascript

    .done(function(data) {
      if(data == 1) {
        $("#success").text("Data added Successfully!").show();
      }
    });
    

    Well, simple answer without comments regarding other things like "use pdo instead of mysqli" and other issues with the code.

    Edit:

    To receive data from the db, that code below handles your query result. The data will be available as object.

    if(is_array($result) && count($result)) {
       exit(json_encode($result, JSON_FORCE_OBJECT);
    }
    

    In your javascript code

    .done(function(data) {
       if(data) {
          // this will show you your object in the console for testing
          console.log(data);
       }
    });
    
    评论

报告相同问题?