Masood
Masood

Reputation: 41

AJAX multiple inputs not passing or sending data to PHP

I have been battling with this AJAX to pass data to PHP for SQL Insertion, it seems the data does not get passed to the PHP. I have three HTML input types, text, radio button and select. The radio is used for gender, select for the country of residence, and text for the country's dialcode concatenated with the user's mobilenumber. Javascript is used to automatically retrieve the dialcode once the user selects his/her country in the dropdown. These inputs are not being passed for SQL insertion.

I am still very much an amateur and a student. I included the code here: https://jsfiddle.net/406tb35r/1/

Code is as follows:

<script type="text/javascript">
 (function($){
     $(document).ready( function(){

        $('#country').change( function(e){
             //on change event 
            $('input[name="dialcode"]').val($(this).find('option:selected').data('co'));  
        });

    }); //make sure all html is loaded before running
 })(jQuery);  //assign jQuery to the $


function validate(evt) {
  var theEvent = evt || window.event;
  var key = theEvent.keyCode || theEvent.which;
  key = String.fromCharCode( key );
  var regex = /[0-9]|\./;
  if( !regex.test(key) ) {
    theEvent.returnValue = false;
    if(theEvent.preventDefault) theEvent.preventDefault();
  }
}

</script>
<form action="" method="post" class="start_form" id="userDetails">

        <fieldset>
          <legend><b>Are you a</b></legend>
          <input type="radio" name="gender" class="gender" value="male">Male<br>
          <input type="radio" name="gender" class="gender" value="female">Female<br>
      </fieldset> 
  <select id="country" name="country" class="country">
  <option data-co="" value="">Which country are from?</option>
  <option data-co="+27" value="ZA">South Africa</option>
  <option data-co="+376" value="AD">Andorra</option>
  <option data-co="+971" value="AE">United Arab Emirates</option>
  <option data-co="+93" value="AF">Afghanistan</option>
  </select>
  <?php 
$countryArray = array(
  'AD'=>array('name'=>'ANDORRA','code'=>'376'),
  'AE'=>array('name'=>'UNITED ARAB EMIRATES','code'=>'971'),
  'AF'=>array('name'=>'AFGHANISTAN','code'=>'93'),
  'AG'=>array('name'=>'ANTIGUA AND BARBUDA','code'=>'1268'),
  );

function countrySelector($defaultCountry = "", $id = "", $name = "", $classes = ""){
    global $countryArray; 

    $output = "<select id='".$id."' name='".$name."' class='".$classes."'>";

  foreach($countryArray as $code => $country){
    $countryName = ucwords(strtolower($country["name"])); 
    $output .= "<option data-co='".$country["code"]."' value='".$code."' ".(($code==strtoupper($defaultCountry))?"selected":"").">".$code." - ".$countryName." (+".$country["code"].")</option>";
}

  $output .= "</select>";

  return $output;  
}
?>
<input align="center" type="text" name="dialcode" class="dialcode" value="" autocomplete="off" placeholder="" mssg="" maxlength="6" readonly>
        <input type="text" name="mobile" class="mobile" value="" autocomplete="off" placeholder="What is your Mobile Number?" mssg="" maxlength="12">

        <input style="width:100%;" type="submit" name="s_submit" value="Next" id="userSubmit"><br/>
        <a href="">Skip</a>
      </form>

<script type="text/javascript">
jQuery(document).ready(function(){

  $('#userSubmit').click(function(e){
    e.preventDefault();
      var gender = $('.gender').val();
        var country = $('.country');
          var dialcode = $('.dialcode');
          var mobile = $('.mobile').val();
    $.ajax({
      type: 'POST',
      url: DIR+'/insert.php',
      data: 
            gender: gender,
            country: country,
            dialcode: dialcode,
            mobile: mobile
      success:function(){
        $('.content').load(DIR+'/welcome.php');}
      }

    });

  });
});
</script>

This is the PHP for passing above data to SQL:

<?php
session_start();
//Connect to DB
  include_once 'connect.php';
   $session = $_SESSION['id'];
   $universal = new universal;
   $susername = $universal->GETsDetails($session, "username");

   if (isset($_POST['username'])) {

   $gender = preg_replace("#[<> ]#i", "", $_POST['gender']);
   $country = preg_replace("#[<> ]#i", "", $_POST['country']);
   $mobilenumber = preg_replace("#[^0-9]#i", "", $_POST['dialcode'] . $_POST['mobile']);

      if((!$username) == ""){
        return "Your details are not logged in or do not have an account with iamstein!";
      } else {
        $users = $this->db->prepare("UPDATE users SET gender = :gender, country = :country, mobilenumber = :mobilenumber, WHERE id = :id");
        $users->execute(array(":gender" => $gender, ":country" => $country, "mobilenumber" => $mobilenumber, ":id" => $session));

      }
 }?> 

Upvotes: 0

Views: 74

Answers (1)

Rotimi
Rotimi

Reputation: 4825

You need to properly warp the data key

data: {
            gender: gender,
            country: country,
            dialcode: dialcode,
            mobile: mobile},

You weren't passing the right format for the data key.. Alternatively you can serialize the form, just to avoid this errors and mistakes.

data:$('#userDetails').serialize(),

Upvotes: 1

Related Questions