tatty27
tatty27

Reputation: 1554

Pass an array to a php script using AJAX

I have a form that I would like to submit without refreshing the page, I am new to AJAX and although I have managed this task passing a single value I'm not sure how to do this with an array.

The form input (displayed using a while loop)

<input type="hidden" name="user" value="<? echo $user_id; ?>" >
<input type="text" name="reason[][<? echo $row['reasonID']; ?>]"
                   size="25" value="<? echo $row['reason_name']; ?>"/>

<input type="submit" class="submit" value="Save"/>

The script

<script type="text/javascript" src="/js/jquery.js"></script>
<script>
  $(function() {
    $(".submit").click(function() {
    var dataString = '????';
    $.ajax({
    type: "POST",
    url: "save_reasons.php",
    data: dataString,
    success: function(){
    alert('yay');
  }
});

return false;
});
});
</script>

save_reasons.php

   if(isset($_POST['save_reasons'])){
      $user_id = $_POST['user'];
       foreach($_POST['reason'] as $item=>$value)
     {
   if(is_array($value)){
       foreach($value as $ID=>$reason)
        {
        $sql = "UPDATE gradeReason SET reason_name = '$reason' WHERE reasonID = $ID";
        $result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
        }   
         }
      else{
        if($value !=''){
              $sql = "INSERT INTO gradeReason (reason_userID, category, reason_name) VALUES ($user_id, 'positioning', '$value')";
              $result = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
           }
        }
         } 
     }

After doing some research I think using the datastring is the way forward but I am not sure how to using this with an array (reason) and the userID (user) and then use it in the PHP script.

Upvotes: 1

Views: 748

Answers (2)

Roseann Solano
Roseann Solano

Reputation: 768

Send your data as json.

var myobj = { this: 'that' };
$.ajax({
  url: "my.php",
  data: JSON.stringify(myobj),
  processData: false,
  dataType: "json",
  success:function(a) { },
  error:function() {}
});

On your server side script

<?php
  $array = json_decode(file_get_contents("php://input"), true);
?>

Upvotes: 1

L105
L105

Reputation: 5419

Use jQuery serialize function to pass your values.

  $.ajax({
    type: "POST",
    url: "save_reasons.php",
    data: $('#myForm').serialize(),
    success: function(){
    alert('yay');
     }
  });

Upvotes: 1

Related Questions