Reputation: 27
I have problem with jquery ajax request:
I have one select field and after more then one input fields.
After changing select field, ajax.php get some informations from Database in separate files. How can I call back those values and set it into previos input fields?
I know how to call all values back, and set them in , but not how to set values in separate input fields (data_1, data_2, data_3)
<select name="call_ajax" id="call_ajax">
<input type="text" value="1">Value 1
<input type="text" value="2">Value 2
</select>
<input type="text" id="data_1" value="some old data 1">
<input type="text" id="data_2" value="some old data 2">
<input type="text" id="data_3" value="some old data 3">
<script>
$("#call_ajax").change(function() {
$.ajax
({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#what").html(html); // ???????
}
});
});
</script>
ajax.php
<?php
$new_data1 = "new value 1";
$new_data2 = "new value 2";
$new_data3 = "new value 3";
?>
Upvotes: 0
Views: 1220
Reputation: 28196
Currently your PHP script returns an empty page - no input for the Ajax process. You need to output some data with your PHP script, for example in a JSON format:
<?php
$new_data1 = "new value 1";
$new_data2 = "new value 2";
$new_data3 = "new value 3";
echo json_encode(array("data_1"=>$new_data1,
"data_2"=>$new_data2,
"data_3"=>$new_data3));
?>
This would return the following:
{"data_1":"new value 1","data_2":"new value 2","data_3":"new value 3"}
Your script could then use this information like
// sample data:
var dat={"data_1":"new value 1","data_2":"new value 2","data_3":"new value 3"};
$("#call_ajax").change(function() {
/* $.getJSON("ajax.php",
function(dat){ */
// inside the callback do the following with dat:
$("input:text").each(function(){
this.value=dat[this.id]; })
/* }); */
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="call_ajax" id="call_ajax">
<option value="1">Value 1</option>
<option value="2">Value 2</option>
</select>
<input type="text" id="data_1" value="some old data 1">
<input type="text" id="data_2" value="some old data 2">
<input type="text" id="data_3" value="some old data 3">
Also, please note that there can be no <input>
elements inside a <select>
element. Use <option>
instead.
Upvotes: 1