简体   繁体   中英

php ajax jquery responseText not returned

I am trying to write an insert query with jquery, ajax and php. The record is getting inserted but returns a status error. First I tried to echo the message in php as it didn't work I tried it with print json_encode but both returned the status as error. Why doesn't it return the responseText?

{readyState: 0, responseText: "", status: 0, statusText: "error"}

This is the addmember.php file

<?php
     require '../database.php';

    function random_password( $length = 8 ) {
            $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_-=+;:,.?";
            $password = substr( str_shuffle( $chars ), 0, $length );
            return $password;
             }


    $password = random_password(8);
    //$regno=$_POST['regNo'];
    $adminno=$_POST['adminNo'];
    $batch=$_POST['batchText'];
    $type=$_POST["memberType"];
    $initials=$_POST["initialName"];
    $fullname=$_POST["fullName"];
    $address=$_POST["address"];
    $telephone=$_POST["contact"];
    $email=$_POST["email"];
    $nic=$_POST["nic"];
    $dob=$_POST["birthDate"];
    $priv=$_POST["memberType"];
    $userid="";

    $sql="select username from memberinfo where username='$adminno'";
    $result=mysqli_query($con,$sql); 
    if(mysqli_num_rows($result)==0){
        $sql="insert into memberinfo(username,nic_no,class,name_initial,full_name,address,telephone,email,date_of_birth) VALUES ('$adminno','$nic','$batch','$initials', '$fullname', '$address', '$telephone','$email','$dob')";
        $result1=mysqli_query($con,$sql);   
        $sql = "select * from memberinfo where username='$adminno'";
                                $result = $con->query($sql);
                                if ($result->num_rows > 0) {
                                    // output data of each row
                                    while($row = $result->fetch_assoc()) {

                                        $userid = $row['user_id'];
                                    }
                                }

        $sql="insert into userlogin(user_id,username,privilege,password) VALUES ('$userid','$adminno','$priv','$password')";
        $result2=mysqli_query($con,$sql);   

        if ($result1 && $result2) {

               $message = "<p>New record created successfully</p>";

         } else {
                $message = "<p>Error: " . $sql . "<br>" . $con->error.".</p>";
        }
    } else{
        $message = "<p>Admission no already exists.</p>";
    }

    print json_encode($message); 


     $con->close()                


?>

This is the .js file with the ajax function

$(document).ready(function(){

    $('#addmember').click(function(){
        console.log("addmember");
        var adminno=$("#adminNo").val();
        var nic=$("#nic").val();
        var batch=$("#batchText").val();
        var initials=$("#initialName").val();
        var fullname=$("#fullName").val();
        var address=$("#address").val();
        var telephone=$("#contact").val();
        var email=$("#email").val();
        var dob=$("#birthDate").val();
        var priv=$("#memberType").val();

                        //$("#result").html("<img alt='ajax search' src='ajax-loader.gif'/>");
                         $.ajax({
                            type:"POST",
                            url:"../ajax/addmember.php",
                            dataType: "json",
                            data:{'adminNo':adminno, 'nic':nic,'batchText':batch,'initialName':initials, 'fullName':fullname, 'address':address, 'contact':telephone,'email':email,'birthDate':dob,'memberType':priv},
                            success:function(response){

                                console.log(response);
                                $("#result").append(response);
                             },
                             error:function(response){
                                console.log(response);
                             }
                          });

    });



});

Status zero normally means the page is navigating away. Stop it from happening.

$('#addmember').click(function(evt){   //<--add the evt
    evt.preventDefault(); //cancel the click

You are not returning valid JSON from the server. You're json encoding a string, but valid JSON requires an object, or array to encapsulate the day coming back.

So at the very least:

echo json_encode(array($message));

No need for the JSON response. Simply return the message from your PHP script as shown below (note the use of echo and the semicolon following close() ):

PHP

$con->close();
echo $message;

Also, remove the JSON filetype from your AJAX call and instead append response.responseText rather than response :

JS

$.ajax({
       type:"POST",
       url:"../ajax/addmember.php",
       data:{'adminNo':adminno,'nic':nic,'batchText':batch,'initialName':initials, 'fullName':fullname, 'address':address, 'contact':telephone,'email':email,'birthDate':dob,'memberType':priv},
       success:function(response){
                   console.log(response);
                   $("#result").append(response.responseText);
                 },
       error:function(response){
                   console.log(response);
                 }
       });

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