1

I am trying to insert more than one data in db using js ajax but it is not working and when i am trying to inserting only one data it is successfully working

Here is my indexa.php

 <html>
  <head>

<script type="text/javascript">
    function insert() {
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        } else{
            xmlhttp = new ActionXObject('Microsoft.XMLHTTP');
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById('success_failed_msg').innerHTML = xmlhttp.responseText;
            } else {
                console.log("faliled");
            }
        }

        parameters = 'first_name='+document.getElementById('firstName').value;
        console.log(parameters);
        xmlhttp.open('POST','insert.inc.php',true);
        xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
        xmlhttp.send(parameters);
    }
</script>


  </head>
 <body>
      First Name : <input type="text" id="firstName"><br/><br/>
      Last Name : <input type="text" id="lastName"><br/><br/>
      Username : <input type="text" id="userName"><br/><br/>
    Password : <input type="password" id="password"><br/><br/>  
    Re-type Password : <input type="password" id="retypePassword"><br/><br/>        
    <input type="button" value="Submit" onclick="insert()">
<div id="success_failed_msg"></div>
 </body>
 </html>

My include.inc.php

    if (isset($_POST['first_name'])) {
$firstname = $_POST['first_name'];


    if (!empty($firstname)) {

    $insert_select = "INSERT INTO ajax_member_data(`first_name`) VALUES('".mysqli_real_escape_string($db_connect,$firstname)."')";

    if ($insert_query_run = mysqli_query($db_connect,$insert_select)) {
        echo 'Data inserted successfully';
    } else {
        echo 'Failed';
    }

     } else {
    echo 'Please enter the value';
     }
  }

and when I am trying this script it

    <script type="text/javascript">
        function insert() {
           if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        } else{
            xmlhttp = new ActionXObject('Microsoft.XMLHTTP');
        }
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById('success_failed_msg').innerHTML = xmlhttp.responseText;
            } else {
                console.log("faliled");
            }
        }

        parameters = 'first_name='+document.getElementById('firstName').value'&last_name='+document.getElementById('lastName').value'&username='+document.getElementById('userName').value'&password='+document.getElementById('password').value'&retype_password='+document.getElementById('retypePassword').value;
        console.log(parameters);
        xmlhttp.open('POST','insert.inc.php',true);
        xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
        xmlhttp.send(parameters);
    }
</script>

my include.inc.php

    if (isset($_POST['first_name']) && isset($_POST['last_name']) && isset($_POST['username']) && isset($_POST['password']) && isset($_POST['retype_password'])) {
    $firstname = $_POST['first_name'];
    $lastname = $_POST['last_name'];
   $usrname = $_POST['username'];
    $password = $_POST['password'];
    $retype_password = $_POST['retype_password'];

       if (!empty($firstname) && !empty($lastname) && !empty($usrname) && !empty($password) && !empty($retype_password)) {

    $insert_select = "INSERT INTO ajax_member_data(`first_name`,`last_name`,`user_name`,`password`) VALUES('".mysqli_real_escape_string($db_connect,$firstname)."', '".mysqli_real_escape_string($db_connect,$lastname)."', '".mysqli_real_escape_string($db_connect,$usrname)."', '".mysqli_real_escape_string($db_connect,$password)."')";

    if ($insert_query_run = mysqli_query($db_connect,$insert_select)) {
        echo 'Data inserted successfully';
    } else {
        echo 'Failed';
       }

     } else {
        echo 'Please enter the value';
    }
}   

4 Answers 4

2

You haven't done concatenation properly. See here,

parameters = 'first_name='+document.getElementById('firstName').value'&last_name='+document.getElementById('lastName').value'&username='+document.getElementById('userName').value'&password='+document.getElementById('password').value'&retype_password='+document.getElementById('retypePassword').value;
                                                                     ^ missing +                                            ^ missing +                                           ^ missing +                                           ^ missing +

It should be,

parameters = 'first_name='+document.getElementById('firstName').value+'&last_name='+document.getElementById('lastName').value+'&username='+document.getElementById('userName').value+'&password='+document.getElementById('password').value+'&retype_password='+document.getElementById('retypePassword').value;

Sidenote: Learn about prepared statements because right now your query is susceptible to SQL injection. Also see how you can prevent SQL injection in PHP.

Sign up to request clarification or add additional context in comments.

Comments

2

You are missing plus(+) sign while passing parameter. Please change your code as below:

Old Code:

parameters = 'first_name='+document.getElementById('firstName').value'&last_name='+document.getElementById('lastName').value'&username='+document.getElementById('userName').value'&password='+document.getElementById('password').value'&retype_password='+document.getElementById('retypePassword').value;

New Code:(Added plus(+) sign wherever it was required)

parameters = 'first_name='+document.getElementById('firstName').value + '&last_name='+document.getElementById('lastName').value + '&username='+document.getElementById('userName').value + '&password='+document.getElementById('password').value + '&retype_password='+document.getElementById('retypePassword').value;

Comments

2

If you wrap the input fields with a form and use jQuery serialize could be easier.

Example HTML:

<form>
    First Name : <input type="text" id="firstName"><br/><br/>
      Last Name : <input type="text" id="lastName"><br/><br/>
      Username : <input type="text" id="userName"><br/><br/>
    Password : <input type="password" id="password"><br/><br/>  
    Re-type Password : <input type="password" id="retypePassword"><br/><br/>        
    <input type="button" value="Submit">
    <div id="success_failed_msg"></div>
</form>

Example JS:

//you can use the var sending to avoid 
// more than one request at the same time
var sending = false;
$('form').on('submit', function(ev){
  ev.preventDefault();
  if (!sending) {
    $.ajax({
        url: 'insert.inc.php',
        method: 'post',
        dataType: 'json',
        data: $('form').serialize(),
        cache: false,
        beforeSend: function() {
            //here you can show an ajax loading icon
            sending = true;
        },
        success: function(response){
           //here you can show a success message and check if the
           //response is correct
           //response object depends on the server side response
           if (response.success || response.success === 'true') {
                //show success message...
           } else {
                //show error message...                 
           }
        },
        error: function(err){
           //here you can show an error message
        },
        complete: function(){
           //here you can hide the ajax loading icon
           sending = false;
        }
      });
  }

});

Documentation from jQuery:

And you can format a json response from the server side

You can read more about json and ajax here:

And a tutorial about how to see the request on Firefox: https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor

And on Chrome: https://developers.google.com/web/tools/chrome-devtools/network-performance/resource-loading

8 Comments

but your given query is not working and what i have to fill in beforeSend, success,error and complete can u please tell me
In the original code or have you tried with jQuery?
yes i have tried. how can i post the answer to u in stackoverflow actuall i am new
You can use pastebin
here is my pastebin <iframe src="//pastebin.com/embed_iframe/gJq1u7Gx" style="border:none;width:100%"></iframe>
|
1
    var sending = false;
     $('form').on('submit', function(ev){
      ev.preventDefault();
    if (!sending) {
     $.ajax({
    url: 'insert.inc.php',
    method: 'post',
    dataType: 'json',
    data: $('form').serialize(),
    cache: false,
    beforeSend: function() {
        console.log("processing");
        sending = true;
    },
    success: function(response){
       if (response.success || response.success === 'true') {
        ('#success_failed_msg').text(response);
       } else {
        ('#success_failed_msg').text('response failed');
       }
    },
    error: function(err){
        ('#success_failed_msg').text(err);
    },
    complete: function(){
        console.log('process complete');
       sending = false;
    }
  });
     }

      });

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.