Ajax load dynamic content

Hello Experts,

I tried to solve it once here with no luck so I try again :-))


In a website there are two pages. The first page in the home page containing a photo and the second page have a table populated by a dynamic url address ( look at the script code below).

The task : I need to perform a calculation on the table and echo the result in the home page.
No cookies please and no localstorage  just simple Ajax load would do.

Below are my tryouts with no luck......

// This is how the table is being populated on to the second pages (the page with the table):

<div><?php $tab = file_get_contents("http://domain.com/table/index.php?lang=en&name=project01"); echo $tab;?></div>

// Now I need to load this table with Ajax then perform the calculation and then append the result to a div on the first page (home-page). So i try something like this:

$.get ("http://domain.com/table/index.php?lang=en&name=project01", function() {
		
	    var TotalUnits = $("tr").not("tr.no-hover").size() -1;
	    var TotalBuy = $("tr.prevented").size();
	    var PrecentageBuy = TotalBuy / TotalUnits * 100;
	    var echoPrecentageBuy = parseFloat(PrecentageBuy).toFixed(0);
		
	   $( "#result").append(echoPrecentageBuy);

});

Open in new window

RefaelAsked:
Who is Participating?
 
Chris StanyonConnect With a Mentor Commented:
Hey Refael,

You've done pretty much what I advised - you're using the tablepage.php as your local PHP proxy file so you don't have to worry about the CORS problem. The tablepage.php loads the data from the remote server and your AJAX request loads the tablepage.php file.
0
 
Alexandre SimõesConnect With a Mentor Manager / Technology SpecialistCommented:
What I see is that your ajax request is not dealing with the response at all.
The $.get callback function has 3 arguments from which the first is the response data. In your case the html table you actually want to perform the calculation.
Try this:
$.get ("http://domain.com/table/index.php?lang=en&name=project01", function(data) {
		var $table = $(data);
	    var TotalUnits = $table.find("tr").not("tr.no-hover").size() -1;
	    var TotalBuy = $table.find("tr.prevented").size();
	    var PrecentageBuy = TotalBuy / TotalUnits * 100;
	    var echoPrecentageBuy = parseFloat(PrecentageBuy).toFixed(0);
		
	   $( "#result").append(echoPrecentageBuy);
});

Open in new window

This expects that there's an element with the id="result" already on the page before the ajax call is made.
0
 
RefaelAuthor Commented:
Hello Alexandre Simões, Thank you.

I tried your code yet that's what i am getting in the console.  This is the same domain yet the URL in the get is in a sub-doamin. How can I enable CORS? is this done via the htaccess or the phpini?

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ..... This can be fixed by moving the resource to the same domain or enabling CORS.
0
Cloud Class® Course: CompTIA Healthcare IT Tech

This course will help prep you to earn the CompTIA Healthcare IT Technician certification showing that you have the knowledge and skills needed to succeed in installing, managing, and troubleshooting IT systems in medical and clinical settings.

 
Chris StanyonCommented:
CORS is something that would need to be enabled on the remote server, so unless you have access to that then forget it. If you do have access to the remote server, it may just be easier to put a PHP script on there that returns JSON data rather than an HTML tables - you can then make a standard JSONP request.

Alternatively, you could create a PHP script on your own server, that reads the remote html and outputs it:

<?php
   $tab = file_get_contents("http://domain.com/table/index.php?lang=en&name=project01");
   echo $tab;
?>

Open in new window


Your Javascript would then ask for the information from YOUR OWN PHP script and you wouldn't have the Cross Domain issue.
0
 
RefaelAuthor Commented:
Hi Chris Stanyon, I am sorry but i could not understand your comment?
Can you maybe explain or give an example? Thank you.
0
 
Alexandre SimõesManager / Technology SpecialistCommented:
Essentially... do you own the page to where you're connecting to?
If not, forget about CORS.

You can always do this server-side. I mean, your ajax call connects to a method in the server-side of your own website that in turn does the http request to the remote website, bringing back it's contents.

I know very little about PHP, but I'm pretty sure it's possible to do this with it.
0
 
Chris StanyonCommented:
Basically, AJAX calls are normally subject to what's called a Same Origin Policy, meaning you can't make an AJAX call across different domains. In order to make a request to a different domain, the server needs to have CORS enabled. If you have control over the remote server then you an enable this and your AJAX request will work. If you don't have control over the remote server then you can't enable CORS, so you can't make the request.

PHP is not subject to a Same Origin Policy, which means PHP can make requests to different domains.

This means that you can write a PHP file that makes the request to the remote server, and pulls in the data. You host this file on your own server, and then your AJAX request is made to your own file, which will work because you're requesting data from your own server.

You can then choose to handle the received data in either the PHP file or your Javascript file, depending on what you need.
0
 
RefaelAuthor Commented:
Hi Chris Stanyon,  Hi Alexandre Simões

The above looks very intimidating for me. I took another approach using the "load" function and right after I do the calculation I replace the content with the result. It works good. yet the only problem was that i got different calculation result while in the table page it self so I used the "document.location.href" to distinguish between all the other pages in the site and the table page it self. Maybe it is not the perfect solution but it seem to work just fine.

$("#result").load("tablepage.php .table", function () {
      // here i preform the calculations.....
     $("#result").html( // here i simply output the calculation);
}

Open in new window

0
 
RefaelAuthor Commented:
Thanks guys for your help :-)
0
 
Alexandre SimõesManager / Technology SpecialistCommented:
What I saw is that in PHP you can create a php file called, for example, proxy.php with the following inside:
<?
header('Content-type: text/HTML');
$url=$_GET['url'];
$html=file_get_contents($html);
echo $html;
?>

Open in new window

With this you can simple do an ajax request like:
var url= "http://domain.com/table/index.php?lang=en&name=project01";
url = 'proxy.php?url='+url:
$.ajax({
    url: url,
    dataType: 'json',
    success:  function (data) {
        // data will hold the html of the referenced page
    }
});

Open in new window

As @Chris told, what you did was more or less what we said.
This way here is, IMHO, a more "proper" way lets say. And you can actually reuse it in the future for other kind of cross-domain requests (even to get JSON and such if you tweak it a bit).
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.