Solved

AJAX reload page data

Posted on 2014-02-12
18
479 Views
Last Modified: 2014-03-07
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
0
Comment
Question by:M. Jayme Nagy
  • 9
  • 7
18 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 39853863
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
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39854001
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
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 39854517
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
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 39854524
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
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39855427
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
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 39856748
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
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39858360
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
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 39895183
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39895527
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
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 39905514
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
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39905599
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
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 39905729
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
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
ID: 39906000
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
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 39906639
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
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 39906902
Additionally,

My php scripts all have to do with preparing some sort of mysql data fetch and manipulate that data into readable HTML
0
 
LVL 6

Author Comment

by:M. Jayme Nagy
ID: 39911239
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
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39911681
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

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

What is Node.js? Node.js is a server side scripting language much like PHP or ASP but is used to implement the complete package of HTTP webserver and application framework. The difference is that Node.js’s execution engine is asynchronous and event…
This article will show, step by step, how to integrate R code into a R Sweave document
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
The viewer will learn the benefit of using external CSS files and the relationship between class and ID selectors. Create your external css file by saving it as style.css then set up your style tags: (CODE) Reference the nav tag and set your prop…

758 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

16 Experts available now in Live!

Get 1:1 Help Now