user3889963 user3889963 - 2 months ago 7
Ajax Question

Issue with creating and looping through json object

I am trying to create a json object in js, use ajax to send it to a php page and loop through it in the php page.

My code is as follows

form page

<html>
<body>
Input 1: <input type="text" data-id="1" data-old="30"/><br>
Input 2:<input type="text" data-id="2" data-old="40"/><br>
Input 3:<input type="text" data-id="3" data-old="50"/><br>

<input type="text" id="max" value="3" hidden/>

<button type="button" id="proceed">Go</button>
</body>
</html>


js

$("#proceed").on("click",function(){
var num=$("#max").val();
var array=[]; //[] or {} ??
for(i=1;i<=num;i++){
var old=$('input[data-id="'+i+'"]').data("old");
var new=$('input[data-id="'+i+'"]').val();
var deduct;
if(new!==old && new!==""){
deduct=old-new;
array.push({"pid":i,"deduct":deduct});
}

var updateArray = JSON.stringify(array);
$.ajax({
type:"POST",
url:"../control/stock-c.php",
data:{updateArray:updateArray, func:"manualSync"},
dataType:"json",
success:function(){
alert("yay");
}
});

}
});


stock-c.php

require_once '../model/stock-m.php';
$updateArray=$_POST["updateArray"];
$array= json_decode($updateArray);
$obj=new Stock();
foreach($array as $obj1){
$result=$obj->deductMainstock($obj1->pid,$obj1->deduct);
}
return $result;


The Stock class exists in the the stock-m.php and I can confirm that the method deductMainstock() works (includes a mysqli update query).

However when running my code it seems that the deductMainStock() hasn't worked. I know there's a bulk of code so to keep it simple I need to know the following:


  1. Is the var array created in js file done properly?? I need to create a json object to send the details using ajax in the following format:



array=[{"pid"=1,"deduct"=a_value},{"pid"=2,"deduct"=another_value},{"pid"=3,"deduct"=another_value}]


  1. Is the ajax call in js file correct? I used JSON.stringify() to convert the above array into json for sending over ajax.

  2. Am I looping through the array properly in stock-c.php? I need to send "pid" and "deduct" as number variables to the deductMainstock() method.


Answer
  1. Please change the variable name var new to something else since its reserved keyword.
  2. var updateArray = JSON.stringify(array); You no need to stringify the array.
  3. Move the ajax call out side the for loop.

Below is the updated code

Script

<script>
$("#proceed").on("click",function(){
  var num=$("#max").val();
  var array=[];  //[] or {} ??
  for(i=1;i<=num;i++){
      var old=$('input[data-id="'+i+'"]').data("old");
      var new_val=$('input[data-id="'+i+'"]').val();
      var deduct;
      if(new_val!==old && new_val!==""){
          deduct=old-new_val;
          array.push({"pid":i,"deduct":deduct});
      }

  }
  if(array.length){
     $.ajax({
       type:"POST",
       url:"../control/stock-c.php",
       data:{updateArray:array, func:"manualSync"},
       dataType:"json",
       success:function(){
         alert("yay");
       }        
     });
  }

});
</script>

PHP

Post value will be array so remove the json_decode from your code.

<?php 
require_once '../model/stock-m.php';
$array = $_POST["updateArray"];
$obj = new Stock();
foreach ($array as $obj1) {
    $result = $obj->deductMainstock($obj1->pid,$obj1->deduct);
}
return $result;

?>

Hope this will help.