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:
- 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}]
Is the ajax call in js file correct? I used JSON.stringify() to convert the above array into json for sending over ajax.
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.