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';
    }
}   
Owaiz Yusufi
  • 849
  • 1
  • 14
  • 34

4 Answers4

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.

Community
  • 1
  • 1
Rajdeep Paul
  • 16,887
  • 3
  • 18
  • 37
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;
Deepak Rai
  • 246
  • 3
  • 8
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

SebCar
  • 328
  • 3
  • 12
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;
    }
  });
     }

      });
Owaiz Yusufi
  • 849
  • 1
  • 14
  • 34