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
LVL 6
J NUnicorn wranglerAsked:
Who is Participating?
 
Julian HansenConnect With a Mentor Commented:
Can you post a bit more informaation about what different requests you would want to make via ajax.

It could be as simple as
data = {action: 'edit', ...}; // Assemble your data here to parameterise your AJAX call
$.ajax ({
   url: 'ajax.php',
   data: data, // This would be different for each call - customise here
   succeed: function (resp) {
       // php script sends back a JSON object
       // that has as properties
       //       id - id of element to update
       //  html - html to place in element
       $(resp.id).html(resp.html);
   },
   type: 'POST',
   dataType: 'json'
})

Open in new window

In your PHP script you examine the $_POST for an action.
You use the action to determine what code to run
The action code creates a JSON object - basically an array in which you have an id index and an html index.
The id is used to target the element to put the html into.
You then use json_encode() to send the data back to the browser
Example
ajax.php
<?php
$action = empty($_POST['action']) ? '' : preg_replace('/[^a-z]/','', $_POST['action']);
$result = array(id => '', html=>'');
if ($action == 'products') {
   $result['id']='#products';
   $result['html'] = '<ul><li>Product 1</li><li>Product 2</li></ul>';
}
die(json_encode($result));
?>

Open in new window

0
 
leakim971PluritechnicianCommented:
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

0
 
Julian HansenCommented:
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

0
Introducing Cloud Class® training courses

Tech changes fast. You can learn faster. That’s why we’re bringing professional training courses to Experts Exchange. With a subscription, you can access all the Cloud Class® courses to expand your education, prep for certifications, and get top-notch instructions.

 
J NUnicorn wranglerAuthor Commented:
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

0
 
J NUnicorn wranglerAuthor Commented:
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

0
 
Julian HansenCommented:
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.
0
 
J NUnicorn wranglerAuthor Commented:
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
0
 
Julian HansenCommented:
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.
0
 
J NUnicorn wranglerAuthor Commented:
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
0
 
Julian HansenCommented:
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.
0
 
J NUnicorn wranglerAuthor Commented:
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",...)"
0
 
Julian HansenCommented:
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?
0
 
J NUnicorn wranglerAuthor Commented:
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.
0
 
J NUnicorn wranglerAuthor Commented:
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
0
 
J NUnicorn wranglerAuthor Commented:
Additionally,

My php scripts all have to do with preparing some sort of mysql data fetch and manipulate that data into readable HTML
0
 
J NUnicorn wranglerAuthor Commented:
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
0
 
Julian HansenCommented:
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

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.