Mohan Wijesena
Mohan Wijesena

Reputation: 235

Appending external PHP file in jQuery

I'm referring a question answered here.

Trying to append an external PHP file in to jQuery and tried load.

$(".chatbox").load("./one.php");

This gives me the output;

Your success message!

However the concern is this removes all HTML in the body and does not really 'append' the success message.

I tried the following instead.

$(".chatbox").append("./one.php");

which merely prints this!

./one.php

Am I missing something here?

Upvotes: 2

Views: 867

Answers (2)

Hamzeen Hameem
Hamzeen Hameem

Reputation: 2560

in case if the page you're trying to load is failing due to some reason, you also need to handle the error block to inform you about the issue. Here is a more comprehensive way to do it. Here I have called a wiki page but you will know, all the php pages are in fact interpreted as valid html by PHP engine :)

$.ajaxPrefilter( function (options) {
  if (options.crossDomain && jQuery.support.cors) {
    var http = (window.location.protocol === 'http:' ? 'http:' : 'https:');
    options.url = http + '//cors-anywhere.herokuapp.com/' + options.url;
  }
});


$.ajax({
  type: "GET",
  url: "https://en.wikipedia.org/wiki/PHP",
  data: { },
  success: function(data){
    $('#demo').html(data);
  },
  error: function(XMLHttpRequest, textStatus, errorThrown) {
    $('#demo').html("Status: " + textStatus + "<br/>Error: " + errorThrown);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="demo"></div>

Upvotes: 1

Mohammad
Mohammad

Reputation: 21489

The .load() load data from the server and place the returned HTML into the matched element. But you need to use $.ajax() or $.get() that get data and return it into callback function.

$.get("./one.php", function(data) {
   $(".chatbox").append(data);
});

Upvotes: 2

Related Questions