Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Ajax load dynamic content

Posted on 2014-12-13
10
Medium Priority
?
317 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
  • 3
10 Comments
 
LVL 30

Assisted Solution

by:Alexandre Simões
Alexandre Simões earned 1000 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 44

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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 

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
 
LVL 44

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 44

Accepted Solution

by:
Chris Stanyon earned 1000 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 does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

There are a couple ways to attach a JavaScript function to dynamically created elements. You can make a new script for each element as it’s created or you can use delegation. Delegation allows a single script that is added at page creation to mat…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. 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…
Suggested Courses

618 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