1

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

    });



});

3 Answers 3

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Done, thanks for pointing out. Fixed with one more change in the ajax in addition. Had to append the response.responseText instead of response
0

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

2 Comments

@AsmaZinneeraJabir Can you open your web inspector, go to the network tab, and inspect the network request to see if you can get further information.
Everything seems to be ok. Guess it doesn't show because the success message is not from the server. Is there a way to display the custom message?
0

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

Comments

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.