简体   繁体   中英

JQuery AJAX response from PHP

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.

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);
   }
});

You can have value in success from php

Jquery:

$.ajax({
  method: "POST",
  url: "login.php",
  data: { name: username, password: password },
  success: function (data)
    {
        var result=$.parseJSON(data);
        $("#success").text(data.content).show();
    }
});

You need to pass json_encode array to respond to ajax. PHP:

$result['content']="";
 $sql = "INSERT INTO `log_in` (id, name, password) VALUES (NULL, '$name', '$pass');";
if (mysqli_query($conn, $sql)) {

} else {
    $result['content']= "Error: " . $sql . "<br>" . mysqli_error($conn));
}
echo json_encode($result);

3 things to do :-

1) In your ajax call add datatype : json as shown below

$.ajax({
  method: "POST",
  url: "login.php",
  dataType : 'json',
  data: {
     name: username,
     password: password
  }
})

2) in your ajax php file , do the following

<?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)) {
            $response['status']   = "success";
            $response['statusMsg']   = "Data added Successfully!";
            $response['username'] = $name;
         } 
         else {
            $response['username']    = "";
            $response['status']      = "failed";
            $response['statusMsg']   = "Error: " . $sql . "<br>" .mysqli_error($conn);

        }
    }

    echo json_encode($response);

I create an array with all parameter that i need to send back to the (done/success) callback function. You can add as many key-value pairs in the array back to callback function. And then encode them in json in the end.

  1. You can use "success" callback instead of "done" callback, i show here with "success" , i hope "done" would also work same

    .success:function(data){

    if(data['status'] == "success"){

      $("#success").text(data['statusMsg']).show(); 

    }else{

      $("#failed").text(data['statusMsg']).show(); 

    } });

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