jadle
jadle

Reputation: 147

Ajax returning strange extra html

I have several snippets of HTML content that get loaded onto a page based on the current selected region of a world map. Here is what the request looks like:

    jQuery('#vmap').vectorMap({
        map: 'world_en',
        backgroundColor: '#fff',
        // more map config options...
        onRegionClick: function(element, code, region)
        {
            //Post request
            $.ajax('/get_post_data.php', {
                data: {region: region},
                dataType: 'html',
                success: function(response) {
                    $("#post").html(response);
                }
            });
        }  
    });

Here is get_post_data.php:

$result = '';

  // Swtich based on region
  switch($_REQUEST['region']) {
    //Asia
    case 'China':
    case 'Japan':
        $result = @include('includes/asia.inc.php');
      break;

    //Africa
    case 'Ethiopia':
    case 'Kenya':
        $result = @include('includes/africa.inc.php');
      break;

  echo $result;

And the inc.php files look like this:

<h2>Asia</h2>
<p>The article for Asia region</p>

When the AJAX runs, the corresponding HTML gets posted to the page, but the paragraph is wrapped in extra h2 tags that I didn't write anywhere, and it posts "1" as a string after the p tags. Here's what the markup looks like after the response:

<div id="post">
    <h2>Asia</h2>
        <h2>
            <p>The article for Asia region</p>
            "1"
        </h2>
</div>

I have no idea why these two extra things are added to my intended markup. When I look at the response in the console, I see the correct HTML, still with the added "1", but without the h2 tags.

Upvotes: 0

Views: 265

Answers (2)

Billy
Billy

Reputation: 788

You are using json_encode($result); This is what you are displaying, weird things can happen.

try just echo $result;

Upvotes: 1

kei
kei

Reputation: 20511

That's cause you haven't properly closed the h2 tag in inc.php

Should be

<h2>Asia</h2>

Upvotes: 3

Related Questions