1

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?

1
  • return a json string from your php and then parse that string in the javascript. There are surely hundreds of pre-existing pages on this site that describe how to do this. Commented Nov 4, 2018 at 23:02

1 Answer 1

2

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, e.g. 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"
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.