Link to home
Start Free TrialLog in
Avatar of J N
J N

asked on

AJAX reload page data

Hi,

I want to start to learn ajax and have a little bit of JS experience. i know i need to start brushing up on JS however i am curious how i could get the page to reload mysql data and display the results without a page refresh?

thanks in advance
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Using a small lib : http://zeptojs.com/

<!DOCTYPE html>
<html>
<head>
<script src="//cdnjs.cloudflare.com/ajax/libs/zepto/1.1.2/zepto.min.js"></script>
<script>
Zepto(function($) { // wait loading of the page skeleton (DOM)

      function loadData() {
         var options = {
            url: "/path/to/script_on_the_server.php",
            params: { parameter1:"hello", parameter2:"world" },
            success: function(data_from_the_script_on_the_server) {
                 $("#divId").html( data_from_the_script_on_the_server );
            }
         }
         $.ajax(options); // http://zeptojs.com/#$.ajax
      }

      $("#buttonId").click(loadData);  // http://zeptojs.com/#on

});
</script>
</head>
<body>
<button id="buttonId">CLICK TO LOAD DATA</button>
<div id="divId"></div>
</body>
</html>

Open in new window


script_on_the_server.php :
<?php
   $parameter_from_browser = $_GET["parameter1"];
   $param2 =  $_GET["parameter2"];
   echo "<p>This is your param1" . $parameter_from_browser . "</p>";
   echo "<p>This is your param2" . $parameter2 . "</p>";
?>

Open in new window

AJAX is not really something to learn but more a concept to become familiar with.

At the heart of it you use Javascript to catch an Event and then again using Javascript to make a call back to the server to fetch some content.

How the called script generates the content and returns it is entirely up to you - it can be as a chunk of HTML that you simply place in your document when the AJAX call completes or a JSON object that you then use to dynamically manipulate the DOM - how you do it is enitrely up to you.

To use AJAX you can either go directly to the xmlHTTPrequest (not recommended) or through a library like JQuery (or Zepto which is essentially the same thing only smaller).

At the heart of it an AJAX enabled page works as follows. This sample is a very simple example of a completely functioning ajax activated page.
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
// This ensures the code runs on page load complete
$(function() {
  // Bind to the click event of the <a class="fetchData"> elements
  $('a.fetchData').click(function(e) {
     // DISABLE Default click behaviour for this element.
     // The e parameter passed to the function is the event object.
     e.preventDefault();
     // Load the html returned by the specified script into the specied element.
     // The script can be anything that returns HTML
     // As your requirements change you can look at functions like
     // $.post and $.ajax to further refine the functionality
     $('#result').load('myajaxscript.html');
  });
});
</head>
<body>
<a class="fetchData">Fetch</a>
<div id="result"></div>
</body>
</html>
</script>

Open in new window

Avatar of J N
J N

ASKER

thanks everyone!!

how would i get it to fire on a form submit for example

$send_msg=empty($_POST["send_msg"])?"":mysqli_real_escape_string($link,$_POST["send_msg"]);

if(empty($send_msg)){
    //DISPLAY NEW FORM

}else{
    //REQUEST 'REFRESH' FROM AJAX

}

Open in new window

Avatar of J N

ASKER

Additionally say i just wanted the 'refresh/update' to the current form
$send_msg=empty($_POST["send_msg"])?"":mysqli_real_escape_string($link,$_POST["send_msg"]);

if(empty($send_msg)){
    //DISPLAY NEW FORM

}else{
    //REQUEST 'REFRESH' FROM AJAX

}

Open in new window

Any particular reason you want the refresh code in the same script as the new form code?

You could do something like this
$(function() {
    $('form').submit(function() {
         // Get all the form data into a postable string
         var data = $(this).serialize();
         $.post('processscript.php', data, function(resp) {
            // PROCESS return here
         });
    });
})

Open in new window

Understanding more about what you are trying to do will help giving a more detailed response.
Avatar of J N

ASKER

Hi,

I have an area where a user and input a music feed / news items click submit and it upload to the database. however the inputed data does not appear until the page is reloaded. as of now i have just put in a js reload script in once this completes so the data appears after a second or so. however, its kind of sloppy and i would rather have the data pull in immediately after without a page reload. i have read that AjAX was the best way to accomplish this however i am green in the matter and not quite sure how to go about it.

The reason why i would want to 'refresh' the current page is that all of my php scripts come are on that page i guess i could just use includes but i have not developed it as such. any advice is GREATLY appreciated
I would separate the functionality - it will make it easier to manage.

One script renders the form
The second script accepts data from the AJAX post and returns a status / content to the browser.
Avatar of J N

ASKER

Hi,
Sorry this has taken me so long to reply but i have a slight problem. it seems that when i use ajax and its working its refreshs the entire page within a small div. is it possible to refresh only the contents of the div and replace them instead of reloading the entire page and putting it in a smaller div within the same page
thanks
The problem is that your script that is being called by AJAX is rendering the entire page.

Instead the AJAX script should only render out the part that you want to display in the div.

So, you need to make the script that you call accept the input parameters and then just generate the output for that particular div.

Example
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(function() {
    $('form').submit(function() {
         // Get all the form data into a postable string
         var data = $(this).serialize();
         $.post('processscript.php', data, function(resp) {
            $('#result').html(resp);
         });
    });
});
</script>
</head>
<body>
  <form>
     <!-- Form goes here -->
  </form>
  <div id="resutl"></div>
</body>
</html>

Open in new window

processscript.php
<?php
if ($_POST) {
  $val = empty($_POST['value']) ? 0 : $_POST['value'];
}
echo "The value received was $val";
}
?>

Open in new window

The above demonstrates the basics of what you want to do.
Avatar of J N

ASKER

HI,

Sorry i have not gotten back to you.

I have been doing some research on the matter and im curious if i could make a blanket function where i could have some variables so i could use the function over and over
ex:

function GET_AJAX_DATA (file, results,.........)

then potentially include in the html as onclick="GET_AJAX_DATA ("process.php","#status",...)"
I have been doing some research on the matter and im curious if i could make a blanket function where i could have some variables so i could use the function over and over
ex:
This is the easy part - the part you still need to solve is the backend script that responds to those variables and sends back only the HTML that you are interested in.

What server side script are you using ? PHP?
Avatar of J N

ASKER

Yea the php stuff I have pretty well got working. I'll have to do some tweaks once I understand ajax. I'm pretty green with JavaScript and not sure how to approach ajax to accomplish a generic reusable function so I'm no going back over and over again to re create a similar function to do that same thing.
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of J N

ASKER

Hi
Typically my processing forms will output direct HTML, change a session variable or is a POST to change a parameter of the HTML output
Avatar of J N

ASKER

Additionally,

My php scripts all have to do with preparing some sort of mysql data fetch and manipulate that data into readable HTML
Avatar of J N

ASKER

Hi

so ive made this ajax function based on the one above
//GRAB PHP INFO
function ajax_update_class(ajaxfile,input_class) {
  // Get all the form data 
  $.ajax({
    type: "POST",
    url: ajaxfile,
    success: function(a){
      document.getElementsByClassName(input_class).innerHTML=a;
      alert(a);
    }
  });
}

Open in new window

then i call it like so

onclick="ajax_update_class('ajax/online_users.php','online_users'); return false"

the alert is just to see if it got the data which it is doing. However it is not updating the classes when i have defined as such

<span class="online_users">12</span>

works if i use id and getElementsbyId but not class
That's because docment.getElementsByClassName returns an array.

You need to do this
function ajax_update_class(ajaxfile,input_class)
{
  $.ajax({
  type: "POST",
  url: ajaxfile,
  success: function(a){
      var els = document.getElementsByClassName(input_class);
      for(i=0;i<els.length;i++) {
        els[i].innerHTML = a;
      }
    }
  });
}

Open in new window