Solved

Ajax load dynamic content

Posted on 2014-12-13
10
273 Views
Last Modified: 2014-12-18
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

0
Comment
Question by:Refael
  • 4
  • 3
  • 3
10 Comments
 
LVL 30

Assisted Solution

by:Alexandre Simões
Alexandre Simões earned 250 total points
ID: 40498452
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
 

Author Comment

by:Refael
ID: 40499336
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
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 40500414
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
 

Author Comment

by:Refael
ID: 40505791
Hi Chris Stanyon, I am sorry but i could not understand your comment?
Can you maybe explain or give an example? Thank you.
0
 
LVL 30

Expert Comment

by:Alexandre Simões
ID: 40505824
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 40506136
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
 

Author Comment

by:Refael
ID: 40506597
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
 
LVL 42

Accepted Solution

by:
Chris Stanyon earned 250 total points
ID: 40506611
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
 

Author Closing Comment

by:Refael
ID: 40506646
Thanks guys for your help :-)
0
 
LVL 30

Expert Comment

by:Alexandre Simões
ID: 40506657
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

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
How to build a simple, quick and effective accordion menu using just 15 lines of jQuery and 2 css classes
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

743 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now