How can I insert my ajax response values to a specific div element?

I have an ajax call, which retrieves data and should insert it into the desired div box. However, I can only use one parameter in the success method to fetch the data, not multiple parameters. One super bad/cheap fix would've been multiple ajax calls, but I just know there has to be an easier and less dirty solution than creating different calls/scripts to fetch my data that way. I also tried, as mentioned above, with multiple parameters, in the hope that maybe that would've worked.

my ajax call looks like this:

function retrieveQuestion() {

$.ajax({
    url: 'getSpecificPost.php',
    type: 'POST',
    success: function(response) {
        console.log(response);
    }
});
}

my php script looks like this (not all of it, considering the script works, and my main problem is just how to append certain data to certain divs):

    $sqli = 'SELECT * FROM posts WHERE title = ?';
    $stmt = mysqli_stmt_init($conn);

    if (!mysqli_stmt_prepare($stmt, $sqli)) {
        echo 'Error no stmt prepared';
        exit();
    } else {
        mysqli_stmt_bind_param($stmt, 's', $title);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        $resultCheck = mysqli_num_rows($result);

        if ($resultCheck > 0) {
            if ($row = mysqli_fetch_assoc($result)) {
                echo $row['title'];
                echo $row['name'];
                echo $row['id'];
            }
        }

so let's say, I have 3 div boxes, which are already made, so they don't get created dynamically.

I would like to append $row['title'] to the div box with an id title, the $row['name'] to a div box with id name, and the one with $row['id'] to a div box with the id, id.

JSON

JSON is a human readable text format generally used for transportation of data between server and client.

The json_enocde() function in PHP converts the array into a json string and JSON.parse() function in javascript converts the json string into an array of objects with the appropriate values populated in it.

The Javascript equivalent of json_encode() is JSON.stringify() and PHP equivalent of JSON.parse() is json_decode().

PHP

$sqli = 'SELECT * FROM posts WHERE title = ?';
$stmt = mysqli_stmt_init($conn);

if (!mysqli_stmt_prepare($stmt, $sqli)) {
    echo 'Error no stmt prepared';
    exit();
} else {
    mysqli_stmt_bind_param($stmt, 's', $title);
    mysqli_stmt_execute($stmt);
    $result = mysqli_stmt_get_result($stmt);
    $resultCheck = mysqli_num_rows($result);

    if ($resultCheck > 0) {

        $json_response = [];

        if ($row = mysqli_fetch_assoc($result)) {
            $json_response[] = $row;
        }

        //Echo data as JSON
        echo json_encode($json_response);
    }

Javascript

    function retrieveQuestion() {
        $.ajax({
           url: 'getSpecificPost.php',
           type: 'POST',
           success: function(response) {

               response = JSON.parse(response);

               $("#title").text(response[0].title);
               $("#name").text(response[0].name);
               $("#id").text(response[0].id);
           }
        });
    }

The Page 1 Div ID “main” will load the Page 2 (“property-detailed.php”) but only the Div ID “main” from that page. When that is done, I left a space for adding another function after the new Div loads. That’s it! When you boil it down, it really is just one line of code. A nice little function for a nice little trick.

Since Ajax response all data together. You have two choices to do... 1. Construct your html divs in server php page and directly insert in desired div where you want to update. 2. You have to go through complex JavaScript and json data... Receive data in json format and later on place in manually in desired place. But I suggest the first option create your div with respective ids in server and on success event directly insert it in div

The response from the Ajax call includes the wrapping it in a logical container like a DIV element. of movie is logically contained by a SECTION element with a corresponding ID value.

Have you tried returning a JSON with all the data? Something like this:

echo '{ title:', $row['title'], ', name: ', $row['name'], ', id: ', $row['id'], ' }'

You can also create an object and use json_encode if you do not want to bother building the JSON yourself.

Then in your JavaScript you can change your success function to this:

success: function(response) {
    response = JSON.parse(response); // converts string to Object
    for(var property in response) { // loops for title, name and id
        // Sets the text of the element with id: "title", "name" or "id"
        document.querySelector("#" + property).textContent = result[property];
    }
}

The code in JavaScript parses the JSON from a string to an Ob

In the second case, the content is not be displayed, as we make use of the display attribute of CSS with the none value. Once the other page assigned to the variable or inserted into the tag , its content is accessible with DOM 's methods.

try to send it as one string in php and use comma's then in your ajax use this:

$.ajax({
    url: 'getSpecificPost.php',
    type: 'POST',
    success: function(response) {
         var data = response.split(",");
         $('#title').val(data[0]);
         $('#name').val(data[1]);
         $('#id').val(data[2]);
    }
});
}

jQuery is a Javascript library which has been made to ease the development of JavaScript based websites and it offers massive framework for frontend web development. One major and maybe the best part of it is Ajax, Asynchronous JavaScript and XML. In common language you can you can load data into a website without refreshing it.

Try to access to you DOM html when ajax succsess. Look at this example:

Edit your php and set "return $row"

//...
if ($resultCheck > 0) {
            if ($row = mysqli_fetch_assoc($result)) {
               return $row
            }
        }

//here is your Succes ajas response
//success: function(response) {
 
var response=[];//this line is not necesari , i write because i dont hae response;
response['name'] ='testName';
response['title'] ='testtitle';
response['id'] ='testid';
$('#title').html(response['title']);
$('#name').html(response['name']);
$('#id').html(response['id']);
//   }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="title"></div>
<div id="name"></div>
<div id="id"></div>

Given some HTML in html, elem.insertAdjacentHTML(where, html) inserts it depending on the value of where: "beforebegin" – insert html right before elem, "afterbegin" – insert html into elem, at the beginning, "beforeend" – insert html into elem, at the end, "afterend" – insert html right after elem.

A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. When you pass a jQuery collection containing more than one element, or a selector matching more than one element, the first element will be used.

The createElement () method creates an Element Node with the specified name. Tip: After the element is created, use the element.appendChild () or element.insertBefore () method to insert it to the document.

The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0. Tip: You can use the length property of the NodeList object to determine the number of child nodes that matches the specified selector, then you can loop through all nodes and extract the info you want.

Comments
  • Could you maybe elaborate on what your code did? it not only helps me, but I think it will help other people aswell