2

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?

Mohammad
  • 21,175
  • 15
  • 55
  • 84
Mohan Wijesena
  • 225
  • 1
  • 3
  • 11
  • `load()` replaces the entire content of the selected element. It sounds like you simply need to change your `.chatbox` selector to a lower level element. If you want to append the content instead, then you would need to use `$.ajax()` to retrieve the value and `append()` it manually. – Rory McCrossan Oct 09 '18 at 12:51
  • How would `append()` know that `./one.php` is a file? – Dominic Wehrmann Oct 09 '18 at 12:52
  • 1
    you would need `$.get()` and use `$.append()` in the success callback. But read the documentation of jquery for all these functions (`load`, `get`, `append`) closely. They're quite clear and will most probably solve your question, or at least help you in asking a more specific question. – giorgio Oct 09 '18 at 12:52
  • @giorgio make sense! – Mohan Wijesena Oct 09 '18 at 12:57
  • Read [this](https://api.jquery.com/jquery.get/), [this](https://api.jquery.com/load/) and [this](https://api.jquery.com/append/), that will make sense – giorgio Oct 09 '18 at 13:01

2 Answers2

2

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);
});
Mohammad
  • 21,175
  • 15
  • 55
  • 84
1

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>
Hamzeen Hameem
  • 2,360
  • 1
  • 27
  • 28