jquery to refresh div content generated by php - php

How to refresh a div content generated by the same php page using jquery
i have a test.php, that contains a div called refreshdiv, a button called refreshbutton and may other div's that display other contents
the content of refreshdiv div is generated by php
is it possible to reload the contents of the refreshdiv on clicking refreshbutton on the same page ie, test.php
here is my work around
<div id="refreshdiv">
<table>
<?php
$rec=mysql_query("select * from user_master");
for($i=0;$i<mysql_fetch_array($rec);$i++)
{
?>
<tr>
<td>
<?php echo mysql_result($rec,$i,'username');?>
</td>
</tr>
<?php } ?>
</table>
</div>
tried using $.get, but didnt get any result

Take a look at this jsFiddle I put together - it may help.
I'm making an AJAX call (a POST in this case since it's just HTML and that's what jsFiddle supports for HTML requests - but it would be no different for a $.get for you) that gets data and appends it to a table data cell (<td>). The whole page doesn't update - just the section that I'm targeting -- in this case, the <td> cell, which keeps having "hello's" appended into it.
I hope this helps. Let me know if you have add'l questions.

Use ajax
In the test.php use
if($_GET['ajax'] == 1) {
//echo new content;
}
and the jQuery code will be
function refreshClick() {
$("#refreshdiv").load("./test.php?ajax=1");
//OR
//to customize your call more, you could do
$.ajax({
method: "GET",
url: "./test.php?ajax=1",
success: function(data) { $("#refreshdiv").html(data); },
error: function(err){ Some_Error_Div.innerHTML = err; }
});
}

I think you'd need to set up a php page that will return the contents of the div then access this page via ajax and insert the contents generated by the page into your div. So the jQuery would look something like this -
$.ajax({
url: "div.php",
success: function(data){
$('#refreshdiv').html(data);
}
});

Related

calling a specific PHP function with AJAX

Updated with page titles.
This is on Leaderboard.php. you can see I've currently got the PHP call in the tbody.
<!-- The Leaderboard Table -->
<table id="tblData" class="table table-hover leaderboard-table target">
<thead>
<tr>
<th class="hidden-phone">Rank</th>
<th>Sales Person</th>
<th>Total Points</th>
</tr>
</thead>
<tbody id="leaderboardresults">
<?php $getLeaderboard->getTable($_GET['competitionId']); ?>
</tbody>
</table>
<!-- The Leaderboard Table END -->
This is on API/getLeaderboard.php. This is where the getTable function is.
<?php
class getLeaderboard {
public function getTable($competitionId) {
//I run the SQL query and echo out some PHP
}
This is on Leaderboard.php.
function loadLeaderboard() {
var competitionId = $("body").attr("data-competitionId");
var url = "api/getLeaderboard.php?competitionId=" + competitionId;
$.get(url, function(data) {
//$("#leaderboardresults").html(data);
});
}
This is also on Leaderboard.php. Another AJAX call that does a AJAX get (this works perfectly), and should reload the leaderboard on success.
$(function() {
//this works (/James)
$(".navVisible").click(function() {
var Competition = $("body").attr("data-competitionId");
var Activity = $(this).attr("data-activity");
$.post("registerresults.php", { data: Activity, competitionId: Competition })
.done(function(data) {
loadLeaderboard();
});
});
loadLeaderboard();
});
This is getLeaderboardTable.php
<?php
include "common/common.php";
include "api/getLeaderboard.php";
$competitionId = $_GET['competitionId'];
$getLeaderboard->getTable($competitionId);
?>
From what I understand you need the following -
You have a page (page A) which calls an ajax function at a specific time, and it is supposed to load results.
You have a php function which provides those results when passed a parameter "competitionId".
What you are doing wrong is you have 1 and 2 in the same page without any controller. What you need to do is, move
<?php $getLeaderboard->getTable($_GET['competitionId']); ?>
into a different page, say "getLeaderboardTables.php". Then modify your html page as follows:
<table id="leaderboardresults">
<tbody>
</tbody>
</table>
and then your ajax function as follows, which will insert the data into your data holding table identified by the id leaderboardresults:
function loadLeaderboard() {
var competitionId = $("body").attr("data-competitionId");
var url = "api/getLeaderboardTables.php?competitionId=" + competitionId;
$.get(url, function(data) {
$('#leaderboardresults tr:last').after(data);
});
}
The .after ensures that new rows are appended to the end of the table. if you want to replace them, call $("#leaderboardresults").empty(); first.
Technically speaking though, you do not NEED to move the function to a different PHP page; You can do what DevZero suggested and have a switch case based controller as well so that the same page can be used.
After you have edited the question, I have the following comments -
Your table id has to be leaderboardresults, not tbody id. if you want to keep your table body as tblData, then edit your ajax script as follows
$.get(url, function(data) {
$('#tblData tr:last').after(data);
});
Most important thing, is that you have neither used a controller like DevZero suggested, nor moved the php data fetch to a different page. What you will need to do is:
Option 1 - As I mentioned above, create a new page, called getLeaderboardTables.php, over there put the db connection, include the class, and add this line
<?php $getLeaderboard->getTable($_GET['competitionId']); ?>
so this new page, when called from the browser should ONLY output the rows and NOTHING else. Then call this URL passing the competition id as i mentioned before.
Option 2 - Donot create a new page, but in your existing page, have a controller, like DevZero said, by adding the following to the very top of your html/php after the class includes as follows:
switch ($_GET['action']) {
case 'ajax':
$getLeaderboard->getTable($_GET['competitionId']); //your specific function
break;
default:
?>
Current html/php page content will come here in its entireity
<?php
}
and modify the ajax call as:
var url = "api/getLeaderboard.php?action=ajax&competitionId=" + competitionId;
The basic idea is, AJAX cannot be used to call a PHP function directly. AJAX can be used to call a PHP page, and passing some parameters to it, which in turn calls a PHP function or method to generate some output, and print that output back to the browser window. What AJAX will do is copy that output from the php page, and store it in a javascript variable to do what you want with it. So, the url which you are passing to the ajax function must only load what you want to dynamically update. Think of AJAX here as an invisible man, who takes your url, opens a invisible browser window, pastes that link, waits for page to load, copies the output of the page and stores it in a variable for you.
What you are doing is, you are loading the whole page through AJAX, not just the output which you want to dynamically update.
you can load the results into any html element you want for example if you have a div with id foo you can load the data as follows
$.get(url, function(data) {
$("#foo").html(data);
});
to call a specific function on the file, introduce to a light weight controller to the top of that file.
switch ($_GET['action']) {
case 'foobar':
foobar(); //your specific function
break;
}
So with the controller above pass in the action value of for the function your routing to and then that function will be called.

load part of html using php/jQuery

I'm trying to figure out a way to load 1 single tab(tabs by jQuery) without reloading all the others.
The issue is that I have a submit button and a dropdown that will create a new form, and when on this new form 'OK' or 'CANCEL' is clicked, it has to get the original form back.
The code to load a part of the page that I found is this:
$("#tab-X").load("manageTab.php #tab-X");
But now I would like to know how to use this in combination with the $_POST variable and the submit-button
Clarification:
I have a .php(manageTab.php) which contains the several tabs and their contents
I have in each of these tabs a dropdown containing database-stored information(code for these dropdowns is stored in other pages)
for each of these dropdowns, there exists a submit button to get aditional information out of the DB based on the selection, and put these informations in a new form for editing
this new form would ideally be able to be submitted without reloading everything except the owning tab.
Greetings
<script>
$(document).ready(function() {
$("#form1").submit(function(){
event.preventDefault();
$.post('data.php',{data : 'dummy text'},function(result){
$("#tab-X").html(result);
});
});
});
</script>
<form id="form1">
<input id="btn" type="submit">
</form>
I am not totally understand your question, but as per my understanding you can't load one tab with form submit. Its normally load whole page.
What you can do is, use ajax form submit and load the html content as per the given sample code.
$.ajax({
url: url, // action url
type:'POST', // method
data: {data:data}, // data you need to post
success: function(data) {
$("#tab_content_area").html(data); // load the response data
}
});
You can pass the html content from the php function (just need to echo the content).
AJAX is what you are looking for.
jQuery Ajax POST example with PHP
Also find more examples about ajax on google.
Example: Let me assume you have a select menu to be loaded in the tab.
You will need to send a request to your .php file using jquery, and your php file should echo your select menu.
In your jQuery,
<script>
$.post(url, { variable1:variable1, variable2:variable2 }, function(data){
$("#tab-X").html(data);
//data is whatever php file returned.
});
});
$("#form_id").submit(function(){
return false;
});
</script>
I mean whatever your options are, you will need to do the following in your .php file,
Echo that html code in your PHP script.
echo "<select name='".$selector."'>
<option value='".$option1."'>Option1</option>
<option value='".$option2."'>Option2</option>
<option value='".$option3."'>Option3</option>
</select>";
This would be returned to jQuery, which you may then append wherever you want.

Using JQuery, AJAX and PHP

I am creating a PHP site and have ran into the following problem, i would like to be able to click a hyperlink on a page, send a small data item to a php script, have the script perform its function and then return the results.
I am using AJAX with this site to have each page load into a div section of the site, all pages, data and responses load into this central div, like so:
<html>
<body>
<div id="topMenuBar">
<div id="contents">
//ALL DATA IS LOADED HERE...//
</div>
</div>
</body>
</html>
So, when a page is selected from the top menu i simply have the following code run:
$('#topMenuBar a').click(function(e)
{
e.preventDefault();
$('#contents').load($(this).attr('href'), function()
{
});
});
Now that pages load into the content section, I am loading a page called "results.php" which connects to a DB, queries it, and the creates a HTML table with the results. Each table row has a small hyperlink which when clicked is intended to send a value to another PHP script and then clear the contents div and then repopulate the div with the response from this script (getInfo.php). For example, a row will have the following PHP code generate a link:
<label class="moreInfo"><a name="test01" onClick="getInfoFromPHP(<?php echo $data[$id]; ?> )">Get Info</a></label>
So when the table is generated by PHP it, the link when clicked passes a JS function the value.
What i now need to do is to send the value to a PHP script which will again query the DB, and have the results inserted into the "contents" div. I have been trying the following function.
function getInfoFromPHP(myVar){
var netID = myVar;
$.ajax({
url: "getInfo.php",
type: "POST",
data: {
networkID: netID
},
success: function(html) {
$('#contents').empty();
$('#contents').load(html);
}
});
};
When i call the function it does seem to send the data to the script but i get the following error from firebug:
POST http://127.0.0.1/private/networks/includes/leave_a_network.php - 200 OK -15ms
GET http://127.0.0.1/%3Ch2%3EHello 403 Forbidden 21ms
"NetworkError: 403 Forbidden - http://127.0.0.1/%3Ch2%3EHello" Hello
The PHP script is only doing the following:
<?php
session_start();
$networkID = $_POST['networkID'];
echo "<h2>Hello World</h2>";
?>
What is the best way to send data to a PHP script and have it load into a div?
Thanks for any feedback.
In the success function, put $('#contents').html(html); instead of load.
success: function(html) {
Is returning html as a string that does not need to be 'load'ed again like you try here -
$('#contents').load(html);
Change that line to this
$('#contents').html(html);
A better way is using $.ajax to send the request. On the success callback, you can analyse the result, and do what you want with :
http://api.jquery.com/jQuery.ajax/

php javascript partial page reload

I have a page set-up, with several divs.
For now all we need is
<div id="main">...</div> & <div id="sidebar">...</div>
Each div has code such as:
<?php include("page.php") ?>
The main div does all the work, and includes a JavaScript function. E.g. at the moment the user can click a button to remember an item displayed in a table.
Am I able to only reload the sidebar instead of the whole page when the user calls this function?
I am posting the function here, and all I need now is to be able to refresh the sidepanel and its included php files if that is possible? I assume something along the lines of this could do the job? or am I wrong? load("#sidebar")
function saveToFavorites(code)
{
$.ajax({
async:false,
type: "POST",
url: 'formPostsUser.php?reqtype=addToFavorite',
data:'coursecode='+ code,
success: function(data)
{
$('.result').html(data);
if(data != "")
{
alert(data);
load("#sidebar")
}
}
});
}
Kind regards
Alex
Happy about any and every reply and hint ;)
First thing
<div="sidebar">..</div>
The above markup is wrong HTML. You should give the sidebar as the value of your properties such as id or class
<div id="sidebar">..</div>
Loading the Sidebar content
You can use jQuery ajax to load content of this div using jQuery load method like this
$(function(){
$("#sidebar").load("yourPHPPageToReturnSideBarContent.php");
});
Assuming yourPHPPageToReturnSideBarContent.php is the PHP page which renders the HTML Markkup for the sidebar. Note that this will load the content on the document ready event.
Loading the side bar content on an event
If you want to load it on a purticular event like a button click you can do it like this
$(function(){
$(document).on("click","yourButtonId",function(){
$("#sidebar").load("yourPHPPageToReturnSideBarContent.php");
});
});
The above script will load the side bar content on a button click. The button's id is e "yourButtonId" in this example.
Note that i used jQuery on here to bind the function because it will take care of current element and future element in case if you want to load the markup which contains the button dynamically.

How to change the content of a div without reloading the webpage?

I have a website, that uses PHP to select the content,
<div>
<? include ("navigation.php"); // navigation.php generates the menu ?>
</div>
<div>
<?
$type = $_GET["type"];
switch ($type) {
case "page" :
include "Text.php";
break;
case "news":
include "news_2.php";
break;
default :
include "main.php";
}
?>
</div>
The url is of the format domain.com/index.php?type.
I need to change the block #content without reloading the whole page, how can I do this?
As you've tagged the question with "jquery" I assume you know what that is, and that you're loading it into your page.
All you need to is give your div and ID... content here
And then use a bit of jquery.. in its simplest form just to load your content from 'myurl.php' into 'mydiv' when the page has finished loading:
$(document).ready(function() {
$("#mydiv").load("myurl.php");
});
You'll no doubt want some logic to determine what loads, and under what circumstances. If you need to pass data back to the URL then you'll need to go for jquery ajax ($.ajax). Its all pretty easy, loads of examples on the web, and good docs on the JQuery website.
This would best be done with Ajax. I like using jQuery's ajax function. Something like this:
function load(page){
var datastring='ANY DATA YOU WANT TO SEND';
$.ajax({
type: "POST",
url: 'your/pagehtml/',
data: "bust="+Date()+datastring,
dataType: "html",
cache: false,
success: function(html){
$('#content').html(html)
}
});
return false;
}
You wouldn't need to send the page in the URL this way. Anytime you change the url, you must be loading a different page. Outside of .htaccess rewrite. Which isn't what you need.
Fire this on click or whatever you want.
If you're using jQuery, it's pretty easy. You didn't post what is supposed to trigger the change, so I'll assume you have a list of links in another element with an id of nav.
Read more about the jQuery Ajax request here: http://api.jquery.com/jQuery.ajax/
//run on page load
$(function(){
//bind a click event to the nav links
$("#nav a").bind("click", function(e){
//keep the links from going to another page by preventing their default behavior
e.preventDefault();
//this = link; grab the url
var pageLocation = this.href;
//fire off an ajax request
$.ajax({
url: pageLocation,
//on success, set the html to the responsetext
success: function(data){
$("#content").html(data.responseText);
}
});
});
});
I'd also suggest doing some code cleanup like caching your $("#content") element on the load event (something like window.container = $("#container"), and using window.container later on), but I left it as-is so that everything remains clear.

Categories