I want to have something like a small search engine for the FAQ section on my website. All it does is search the SLQ_DB for the term upon pressing a button.
I want to output the question and the answers in two seperate divs. Therefore I have $data and $data1 which belong to the divs.
$('input#name-submit').on('click',function()
{
var name = $('input#name').val();
//alert(name);
if($.trim(name) != "")
{
$.post('ajax/name.php',{name:name},function(data, data1)
{
$('div#name-data').html(data);
alert(answer);
$('div#name-data1').html(data1);
});
}
});
But when I hit enter the second div shows "success". But the first one has data and data1 in it. When I write function(data1, data) in the js file, the data1 has all the information, and data is just "success".
What's happening here?
The echo
function in PHP outputs the content of a variable to the response body. This body is a "string" that your web application receives.
Let's say you have a code like this:
<?php
$var1 = "hello";
$var2 = "world";
echo $var1;
echo $var2;
?>
The resulting response body will look like this: helloworld
.
Now let's say this is your JS code:
$.post('ajax/name.php',{name:name},function(data) {
console.log(data); // "helloworld"
});
jQuery will pass the response body to the data variable, which now contains heloworld
.
You need to somehow separate the individual variables inside the response body, eg using JSON.
First step is to encode the data on the server, that's as simple as that:
<?php
echo json_encode(["var1"=>$var1, "var2"=>$var2]);
?>
This will create a response body that looks like this: {"var1":"hello","var2":"world"}
.
The next logical step is to decode this JSON using JavaScript:
$.post('ajax/name.php',{name:name},function(data) {
var res = JSON.parse(data);
console.log(res.var1); // "hello"
console.log(res.var2); // "world"
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.