Reputation: 386
I'm trying to create an update form where the user selects an ID and the rest of the form gets automatically filled with the corresponding data to that ID which would make updating really simple, obviously i'd have to use AJAX but do i really have to write a whole form code inside the PHP and return it in a single statement and then assigning it in a single innerHTML?
Is it possible to run whatever returns from the php file as a javascript, such that i would be able to write a mini scripts to set the innerHTML of each element by itself and without having to reload the whole form's HTML code, just the values inside form elements?
<?php
$myname = "test";
$myage = 22;
echo
'<script>
document.getElementById("name").innerHTML = "$myname";
document.getElementById("age").innerHTML = "$myage";
</script>';
?>
PS i have no experience of AJAX and i can only find the xmlhttp.responseText for returning the output of a PHP script.
Upvotes: 1
Views: 106
Reputation: 29635
It would be better if you return the data structured in some form (e.g.: JSON), then process it with JavaScript.
For example, instead of what you are returning, do something like this:
<?php
$to_return = array(
"name" => "test",
"age" => 22
);
echo json_enconde($to_return);
Then on your page, parse your response, and process it:
data = JSON.parse(response);
document.getElementById("name") = data.name;
document.getElementById("age") = data.age;
If you want to standardize it a little bit more, you could return something like this:
[
{
"target": "name",
"value": "test"
},
{
"target": "age",
"value": 22
}
]
and create a function like this:
function populateForm(data) {
for (var x = 0; x < data.length; x++) {
document.getElementById(data[x].target).innerHTML = data[x].value;
}
}
Then call that function with the JSON response from your PHP.
Upvotes: 1
Reputation: 871
I would recommand to return an Array in the server side (the php that handles the ajax request). and in the browser side after you get the the respone from the server then you set
document.getElementById("name").innerHTML = $myname;
document.getElementById("age").innerHTML = $myage;
Upvotes: 0