I have a form with many many inputs and I use the following code to send all my form data to php proccesing:
HTML:
<form>
<input type="text" name="a" />
<input type="text" name="b" />
<input type="text" name="c" />
<input type="text" name="d" />
<input type="text" name="e" />
<input type="text" name="f" />
<button type="button" onclick="update()">UPDATE</button>
</form>
<!-- HERE I SHOW THE VALUES FROM ABOVE INPUTS -->
<input type="text" id="a" />
<input type="text" id="b" />
<input type="text" id="c" />
<input type="text" id="d" />
<input type="text" id="e" />
<input type="text" id="f" />
JS:
<script>
function update()
{
var str = $("form").serializeArray();
$.ajax({
type: "POST",
url: "update.php",
data: str,
dataType: 'json',
success: function(result)
{
document.getElementById("a").value = result.a;
document.getElementById("b").value = result.b;
document.getElementById("c").value = result.c;
document.getElementById("d").value = result.d;
document.getElementById("e").value = result.e;
document.getElementById("f").value = result.f;
},
error: function(result){
console.log("Error:");
console.log(result);
}
});
// return false;
}
</script>
AND update.php:
<?php
$a = $_POST['a'];
$b = $_POST['b'];
$c = $_POST['c'];
$a = $_POST['d'];
$b = $_POST['e'];
$c = $_POST['f'];
$arr = array(
'a' => $a,
'b' => $b,
'c' => $c,
'a' => $d,
'b' => $e,
'c' => $f
);
echo json_encode($arr);
?>
-
First question: Is there a simple method of passing all serialize() variables in PHP, instead of writing all of them like I did in my code? There are too many and I think is is not OK that I have to manually add all of them.
$a = $_POST['a']; $b = $_POST['b']; $c = $_POST['c']; $d = $_POST['d']; $e = $_POST['e']; $f = $_POST['f'];
Is there a short way to pass ajax result array values from PHP in multiple inputs, instead of using the following code?
document.getElementById("a").value = result.a; document.getElementById("b").value = result.b; document.getElementById("c").value = result.c; document.getElementById("d").value = result.d; document.getElementById("e").value = result.e; document.getElementById("f").value = result.f;
All I am trying to say that I have too many inputs on the form and I don't want to add those variables manually. It takes too much time and it is easy to mistake at getting id's and names.