简体   繁体   中英

Ajax call returns data but in purely string format.

In PHP I can do things like this:

echo "<div>".$myvariable."</div>";

Which will print out my variable with div's in HTML for its tags. However recently, I needed to do a ajax call using jquery. I'm somewhat familiar with ajax but I don't use it much. Anyways, I run the ajax code, it prints the data into my HMTL element box like I wanted, however, the div tags are printed and displayed along with the content itself!

The entire return data is pretty much 1 long string, rather than the PHP parsing my data like I want it to. Where did I go wrong? Why is it only returning 1 long string?

PHP CODE:

<?php

require 'database.php';

$meal = $_POST['meals'];

$meal_q = "SELECT item
              FROM meal_ingredients
              WHERE meal_name='$meal'
              ORDER BY item";

$meal_c = $conn->query($meal_q);
    while ($row = $meal_c->fetch_assoc()){
         $view_ingredient = $row['item'];
         echo "<div>".$view_ingredient."</div>";
    };

?>

JQUERY CODE:

if($('body').hasClass('CreateMealPage')){

    $('tr').on('click', function(e){
        $('#sidebar').animate({right: '-200px'}, 500);
        var meals = $(this).find('.meals').text();

        $.ajax({
          method: "POST",
          url: 'meal_list.php',
          data: {meals: meals},
          success: function(data) {
            var sidebar = document.getElementById('sidebar');
            sidebar.innerHTML = "";
            sidebar.append(data);
          }
        });
    });

};

WHAT IS RENDERED ON SCREEN:

<div>ingredientname</div>
<div>ingredientname</div>
<div>ingredientname</div>

RATHER THAN:

ingredientname
ingredientname
ingredientname

just replace

sidebar.innerHTML = "";
sidebar.append(data);

with

sidebar.innerHTML = data;

To answer your comment you can use append with following in jquery

$(sidebar).append($(data))

so jquery's append needs to be used, instead of append, from dom api, which takes a node element only in arguments. If you still need to use append of dom api, use something like:

sidebar.append(document.createRange().createContextualFragme‌​nt(data))

Add dataType: "html" to the properties in your $.ajax() call, like this:

    $.ajax({
      method: "POST",
      url: 'meal_list.php',
      dataType: "html",
      data: {meals: meals},
      success: function(data) {
        var sidebar = document.getElementById('sidebar');
        sidebar.innerHTML = "";
        sidebar.append(data);
      }
    });

This will inform the call to expect HTML data to be returned in the response body.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM