Jump to content

Ajax .load not working properly if data changed


ava_barbilla

Recommended Posts

In my previous question I managed to solve a way to load an external php file into my html thanks to your help. The php file loads perfectly fine as long as it follows the simple to criteria to load php after a given amount of time, which in my case is 1000 milliseconds. I wanted to know a method which loads data from the php file ONLY, and ONLY if the data in that php file has changed. My script what I managed to do after hours of research looks like follows:

 

 

<script type="text/javascript">$(document).ready(function () {    var auto_refresh = setInterval(    function () {        function testing() {            var result = null;            var scriptUrl = "http://localhost:8888/test-site/wp-content/my-php-files/test-check.php"; //Use this php file (NB: This file contains the same data as "test.php") as a check if data changed or not.            $.ajax({                url: scriptUrl,                type: 'POST', // I tried "GET" as well                dataType: 'html',                success: function (data) {                    result = data;                }            });            return result;        }        databaseData = testing();        currentData = $('#demo').html();        if (databaseData != currentData) { // I compare the values from the Ajax request and the value currently in my div to see if they are similar or not.            $('#demo').fadeOut('slow', function () { // I added fadeOut and FadeIn effect for the div to load when data has changed                $('#demo').load('http://localhost:8888/test-site/wp-content/my-php-files/test.php', function () {                    $('#demo').fadeIn('slow');                });            });        }    }, 1000);});</script><div id="demo"></div>

 

In this case scenario, the problem is that the div is loaded every second with the fadeIn and FadeOut effect although the data has not changed. Precisely, the same value appears even up to ten times with the effects even if it is the same value the whole time. It does not matter, if the value is altered or not, the div will be refreshed anyway. The php file contains some data (to pe precise prices) that are refreshed in a random amount of time (it can be 1 second, 10 seconds, 1 minute, etc; this is uncertain). Is there a way to compare the data in "test.php" and if it is not the same, upload the div with the new content?

 

Thanks once again!! This forum always gives great support and positive feedback.

Link to comment
Share on other sites

The reason that code doesn't work is because the ajax request is asynchronous, which means that the browser does not wait for it to finish before moving on. So that testing function will send the ajax request and then immediately return null without waiting for the ajax request to finish. That's why ajax requests have callback functions that will run after the request finishes. So you should send the request, get the result in the callback function, and then inside the callback you send the result to another function which does the compare and only plays the animation if the results are different. The alternative is to use a synchronous request where the browser does wait, but the problem with that is that the browser will actually pause and become unresponsive until the request finishes. You avoid that by using asynchronous requests with callback functions. You just need to structure the code a little differently so that it sends the requests and gets the data first, then decides whether to update the page.

  • Like 1
Link to comment
Share on other sites

Ok I understand. I utilised:

            $.ajax({                url: scriptUrl,                type: 'POST', // I tried "GET" as well                dataType: 'html',         async: false, // Note here I used a synchronous request

However, just as you stated that the browser pauses, my browser started to run very slow so I decided to delete it. I rearranged my structure as follows:

$(document).ready(function () {    var auto_refresh = setInterval(    function () {        function testing() {            var result = null;            var scriptUrl = "http://localhost:8888/test-site/wp-content/my-php-files/test.php";            $.ajax({                url: scriptUrl,                type: 'get',                dataType: 'html',                success: function (data) {                    if (data.changed) {                        $('#demo').fadeOut('slow', function () {                            $('#demo').load('http://localhost:8888/test-site/wp-content/my-php-files/test.php', function () {                                $('#demo').fadeIn('slow');                            });                        });                    }                }            });        }    }, 1000);});

Now, however, nothing appears. Does this has to do with "data.changed" I used in my if operator?

 

Regards!!

Edited by ava_barbilla
Link to comment
Share on other sites

Do you have the server returning a value called changed? If not, then yeah, that's the problem.This is what you should do. First you send the ajax request to the server to get the data. That's the first thing you do. When the request finishes and you have the data from the server, then you compare the data with what is already on the page. If it's different, then you update it with the animation.

  • Like 1
Link to comment
Share on other sites

I get no error from the server. I simply get nothing. This I think means that the "if" operator has the error or no data is transferred, however, in my first code it worked so I suppose this has to do with the "if". I tried changing this to another code which looks like this:

 

$(document).ready(function () {    $('#demo').load('http://localhost:8888/test-site/wp-content/my-php-files/test.php');    var auto_refresh = setInterval(    function () {        function testing() {            var result = null;            var div = $('#demo').html();            var scriptUrl = "http://localhost:8888/test-site/wp-content/my-php-files/test.php";            $.ajax({                url: scriptUrl,                type: 'get',                dataType: 'html',                success: function (data) {                    result = data;                    if (result != div) { // Here you can see I changed the criteria                        $('#demo').fadeOut('slow', function () {                            $('#demo').load('http://localhost:8888/test-site/wp-content/my-php-files/test.php', function () {                                $('#demo').fadeIn('slow');                            });                        });                    }                }            });        }    }, 1000);});

 

This, however, still does not work. Nothing appears just as before. To be honest, I go no clue as to what is going on. In my last topic I was trying to figure out on how to load the div and it resulted in something very strange and Ingolme was confused as to what my server was doing as well. In order to load the code, given that I use WordPress, I had to load the WordPress environment inside the PHP file. It loads perfectly, but once I set the criteria to refresh the div only if the value has changed, I get no response and my div is empty. Is the script unable to compare the values? Should I stick with this code or with the previous one? Thanks so much again for bearing with me.

Link to comment
Share on other sites

You can check for yourself. Before the if statement, you can use console.log statements to send messages to your browser's developer console. There are links in my signature if you haven't used the console before. e.g.:

console.log('result: ' + result);console.log('div: ' + div);console.log('difference: ' + (result != div));
That code you have looks fine in general, the only change I would make is to not send that last request. You already got the data from the server, so instead of using the load method to send yet another ajax request I would just use the .html method to set the HTML of the div to the data you already got from the server, then fade it back in.
  • Like 1
Link to comment
Share on other sites

It appears you've created a function named testing() but never call it at any point, so it never runs.

 

I would suggest declaring all your functions in the global scope unless you have a good reason not to.

  • Like 1
Link to comment
Share on other sites

Remove the "function testing() {" line and the corresponding closing bracket. You define a function called testing but never execute it, but there's no reason to define another function there. The code can just go in the function that runs during setInterval.

  • Like 1
Link to comment
Share on other sites

I did so, and this helped this move a step forward. Now the value refreshes, but sadly, it refreshes every second although data in the php file has not changed. I will give you some details in terms of my entire process. I use WP Web Scraper which is a plugin for WordPress which scrapes data from a website and displays it on your website using shortcodes or php code. I use this plugin to scrape a data from a website (This is to give you an overall view of what I am doing). My php file contains this:

 

<?phprequire('../../wp-blog-header.php'); //I use this to load the WordPress environment into my PHP file to execude code such as "echo do_shortcode" which is the case in this scenarioecho do_shortcode( '[wpws url="URL" query="body %3e table %3e tbody %3e tr:nth-child(1) %3e td:nth-child(8)" querydecode="1" ]' ); //Assume URL is the actual link to the site?>

 

What this is resposible for is loading the data into an external PHP file (called "test.php") which I can the load afterwards into my WordPress page. If I open this file in my browser using my localhost it works fine, displaying the data and if I use my Inspector the source code is as follows:

 

 

<!-- Start of web scrap (created by wp-web-scraper) Source URL: http://www.example.com // Link to the website Query: body > table > tbody > tr:nth-child(1) > td:nth-child(8) (cssselector) Other options: Array(    [headers] =>    [cache] => 0    [useragent] => Hello World    [timeout] => 2    [on_error] => error_hide    [output] => html    [glue] =>    [eq] =>    [gt] =>    [lt] =>    [query_type] => cssselector    [remove_query] =>    [remove_query_type] => cssselector    [replace_query] =>    [replace_query_type] => cssselector    [replace_with] =>    [basehref] => 1    [a_target] =>    [callback_raw] =>    [callback] =>    [debug] => 1    [charset] => UTF-8    [url] => http://ww.example.com //Link to the website    [query] => body > table > tbody > tr:nth-child(1) > td:nth-child(8)    [urldecode] => 1    [querydecode] => 1)--><html><head></head><body>987654.321 // The price (or data) goes here<!-- End of web scrap WPWS Cache Control: Remote-fetch via WP_Http Computing time: 0.9369 seconds--></body></html>

 

This is not to worry about, as when I directly paste the code (provided by the plugin) into my website the data appears. The data gets extracted accurately and correctly. With this, however, you never know when the data changes so I try to check every second if perhaps "987654.321" has changed to maybe "987654.322" or something similar, and if this is the case refresh the div. When data is scraped, automatically comments are included in the HTML output. When I insert the script into my WordPress page now with the changed version:

 

 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script><script>$(document).ready(function () {    $('#demo').load('http://localhost:8888/test-site/wp-content/my-php-files/test.php');    var auto_refresh = setInterval(    function () {        var result = null;        var div = $('#demo').html();        $.ajax({            url: 'http://localhost:8888/test-site/wp-content/my-php-files/test.php',            type: 'get',            dataType: 'html',            success: function (data) {                result = data;                if (Number(result) != Number(div)) { // Included "Number()" as I am dealing with numerical data to see if it works. Unfourtunately it does not.                    $('#demo').fadeOut('slow', function () {                        $('#demo').load('http://localhost:8888/test-site/wp-content/my-php-files/test.php', function () {                            $('#demo').fadeIn('slow');                        });                    });                }            }        });    }, 1000);});</script><div id="demo"></div>

 

the div is still refreshed every second eventhough the data has not changed. I tried so much, but it seems like the script is unable to compare the values, or simply sees them as different the entire time so it uploads the div. After the script is executed in my WordPress site, my "Inspector" shows the following code:

 

 

<div id="demo" style="display: block; opacity: 0.654508497187474;"> //Here opacity keeps changed to fill the fading effects criteria, which means the div blinks the whole time.<!-- Start of web scrap (created by wp-web-scraper) Source URL: http://www.example.com Query: body > table > tbody > tr:nth-child(1) > td:nth-child(8) (cssselector) Other options: Array(    [headers] =>    [cache] => 0    [useragent] => Hello World    [timeout] => 2    [on_error] => error_hide    [output] => html    [glue] =>    [eq] =>    [gt] =>    [lt] =>    [query_type] => cssselector    [remove_query] =>    [remove_query_type] => cssselector    [replace_query] =>    [replace_query_type] => cssselector    [replace_with] =>    [basehref] => 1    [a_target] =>    [callback_raw] =>    [callback] =>    [debug] => 1    [charset] => UTF-8    [url] => http://www.example.com    [query] => body > table > tbody > tr:nth-child(1) > td:nth-child(8)    [urldecode] => 1    [querydecode] => 1)--><td>987654.321</td> //Example data<!-- End of web scrap WPWS Cache Control: Remote-fetch via WP_Http Computing time: 0.9416 seconds--></div>

 

I am truly sorry for bombarding you with so much information. I thought that every detail may help. The script loads everything from the PHP file, including the comments. Do the comments have to do with this going wrong? I have got no idea.

 

Many thanks to both of you who always help me out!!

Link to comment
Share on other sites

The data is in fact changing. If you use the code I posted a few posts up to print the result and div to the console, you'll see that it's different. It's probably this line:

Computing time: 0.9416 seconds

If that changes by even a millisecond then the entire thing is different and it will refresh the page. Can you have it just output the number you need, and not all of the extra comments and things? That's what is messing it up. If you only need that number, then ideally it would only return that number and nothing else.Also, both examples show time of just under a second:

Computing time: 0.9369 secondsComputing time: 0.9416 seconds

Because of that, I would increase your refresh interval from 1 second to maybe 2 or more. If the browser is still waiting for one request to finish and fires off a second request then that can quickly build up into a situation where the browser freezes because it has a bunch of requests pending waiting for others to finish. The requests need to finish with plenty of time to spare to allow for things like network delays or a loaded server.
  • Like 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...