Pass PHP variables without using href in Bootstrap tabs - php

I'm trying to send PHP variables using the <a> tag and the data attribute on the same PHP page using the Bootstrap tabs:
HTML (Bootstrap tab option):
<a style='padding:20px;' href='#tab_e' data-page='$page' class='passrss' data-rssid='$rssid' data-toggle='tab'>Test</a>
PHP (stored in #tab_e tab):
$rsspassedid = GET $rssid from the a tag (data-rssid)
I'd like to get the value stored in data-rssid on click and pass it to a variable further down in the same PHP file so that when the tab is opened using #tab_e, the mySQL statement will run based on the value provided in $rssid and display the results of the query. I'm not sure if any jQuery/AJAX would be required for this but is it possible to get data stored in the data attribute of the <a> tag in PHP?
UPDATE
I've tried storing the variables in the pagination links but still no luck, here's the XHR object I created:
<script>
$(document).ready(function () {
$('.passrss').click(function () {
$('span.pass-tabe').load('tabe.php?rssid=' + $(this).data('rssid') + '&page=' + $(this).data('page'));
});
});
</script>
Tabe passes the variables stored in the a tag to a seperate php file (tabe.php) which then loads into the browser using <span class="pass-tabe"></span>, as for pagination - the links are stored in the tabe.php file but they refer back to the main php file hence pagination fails to work e.g.
originalphpfile.php?page=$page&rssid=$rssidpassed&pageurl=$x#tab_e
NOTE: $rssidpassed is stored in tabe.php which it gets from the XHR object e.g.
$_GET['rssid']
UPDATE 2
I've added the code for pagination below where I'm having the issue at the moment which is stored in tabe.php:
$perpage = 10;
$pageurl = (isset($_GET['pageurl'])) ? (int)$_GET['pageurl'] : 1;
$start = ($pageurl - 1) * $perpage;
$pagequery = mysql_query("SELECT COUNT('topic_id') FROM topic WHERE cat_id='$page' AND topic.users_id = '$rssid'");
$pagination = ceil(mysql_result($pagequery, 0) / $perpage);
//query goes here
//pagination numbers
if($pagination >= 1){
echo "<div style='text-align:center;'><ul class='pagination'>";
for($x=1; $x<=$pagination; $x++){
echo ($x == $pageurl) ? "<li class='active'><a href='originalphpfile.php?page=$page&pageurl=$x#tab_e'>$x</a></li>":"<li><a href='originalphpfile.php?page=$page&pageurl=$x#tab_e'>$x</a></li>";
}
echo "</ul></div>";
}
When I click on pagination links, it doesn't load the second, third, etc set of results as it returns to the originalphpfile.php
Is there any work around for this?

I'm going to go ahead and turn this into an answer because our comment blocks are getting long.
In your PHP template, to turn PHP into something useful you're going to need to do something like this:
// file1.php
// notice <?= ?> is quick echo, the same as <? echo $rssid; ?>
<a style='padding:20px;' href='#tab_e' data-rssid='<?= $rssid ?>' data-toggle='tab'>Test</a>
In your javascript, the reason you're getting $rssid is because you're not echoing the value, I think, according to the post.
// file2.php
$page = array_key_exists($_GET,'page') && is_numeric( $_GET['page'] ) ? $_GET['page'] : 1
// do query i.e select * from x offset $page * $per_page limit $per_page
// do stuff with your pagination in a loop defining an index $number
<a class="pagination" onclick="getPage(<?= $number ?>)"><?= $number; ?></a>
Then in jquery:
// Call this when they click the tab
var id;
function setId(id){
id = id;
getPage(1);
}
// call this when they click the pagination
function getPage(number){
$('span.pass-tabe').load('tabe.php?rssid=' + $id + '&page=' +number )
}
Please massage the example code, it seems as if you're doing something complex and it's hard to necessarily grasp your exact use case precisely.

Issue resolved, I echoed out the AJAX into the tabe php file and changed the pagination HTML links:
tabe.php pagination link:
<a href='#tab_e' class='passrssurl' data-rssid='$rsspassedid' data-url='$x' data-page='$page' data-toggle='tab'>
tabe.php echo AJAX:
echo "<script>
$(document).ready(function () {
$('.passrssurl').click(function () {
$('span.pass-tabe').load('tabe.php?rssid=' + $(this).data('rssid') + '&page=' + $(this).data('page') + '&pageurl=' + $(this).data('url'));
});
});
</script>";

Related

Session variable not updating after AJAX call

I'm a tad stumped here. I have 2 php pages. One displays the template essentially, and on click, an AJAX call calls an external page and displays all the necessary information. My problem is my session variable isn't updating. I'm using some pagination and the numbers aren't updating. Some code on my template page:
Redndering pagination
session_start();
$pagination .= $_SESSION['position'] == "" ? '' : 'Items '.$_SESSION['position'].'-'.$_SESSION['item_per_page'].' of '.$get_total_rows ;
if($pages > 1)
{
$pagination .= '<ul class="paginate nav nav-pills">';
for($i = 1; $i<=$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
<?php echo $pagination; ?>
<div id="results">
<!-- Results from query will go in here -->
</div>
j$(".paginate_click").click(function (e) {
j$("#results").prepend('<div class="loading-indication"><img src="/assets/loader.gif" /></div>');
var clicked_id = j$(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
j$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
j$("#results").load("development_fetch.php", {'page': (page_num-1)}, function(){
});
j$(this).addClass('active'); //add active class to currently clicked element
return false; //prevent going to herf link
});
in development_fetch.php:
session_start();
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
$position = ($page_number * $item_per_page);
$_SESSION['position'] = $position;
$_SESSION['item_per_page'] = $item_per_page;
//Grab code to display inside template blah.
If you click on page 1 in the pagination, it should result in:
Items 0 - 100 of 1000
If I click page 2, it should be:
Items 100 - 200 of 1000
but instead it just stays at:
Items 0 - 100 of 1000
0 is the $_SESSION['position']
100 is the $_SESSION['item_per_page']
I don't understand why it isn't updating. Please help stackers!
i already solved mine. the issue i'm having is that, when i'm doing the ajax, the session variable is not updating in realtime. what i did, is that, i just turned the ajax asynchronous to false, since when you are doing the asynchronous, the value being cache is not the updated value since it is in asynchronous mode. if you are using jquery, just do this:
$.ajax({
type: 'POST',
url: 'url',
data: 'the datas',
success: function() {},
async: false
});
Put session_start(); at the begining of the page loaded with AJAX.
i think i found it, in your development_fetch.php
$position = ($page_number * $item_per_page);
okay, $page_number has a value, but what about $item_per_page ? i guess its zero, and the result of multiplication of course is zero. Then you set those zeroes on the $_SESSION
solution:
set your $item_per_page
session_start();
$item_per_page = 20;
// ...rest of code
i also got this issue, but mine was acting weird. it seems that the session was not fast enough to catch with the ajax.. is this problem already resolved?

Calling individual Divs by id from PHP generated list using jQuery

I am generating divs in PHP, from an array, thus:
echo "<div id='parentdiv'>";
for($counter = 0; $counter < count($list); $counter++){
echo "<div>".$list['important_info']."</div>";
}
echo "</div>";//parentdiv
I want to add some click functionality to each div independently, i.e. the action performed on clicking depends on the div, and more importantly the index of the array, $list;
I want to give each div an id based on it's index in the PHP array.
So I could do
echo "<div id='"."divindex_".$counter."'>".$list['important_info']."</div>";
where "divindex_" is just used to prevent the id form beginning with a numeric value.
Then, I think in jQuery I can write click functions for each div.
However the problem is the $list size is variable, so I don't know how many divs there are.
So what I'm thinking is something like,
$("#parentdiv div").click(function(){
var id = split($(this).attr('id').split("_")[1];//get the php index from the id
//do something with the id, e.g. ajax or whatever
  });
Is there a better way to do this? If you think what I'm doing is strange and not a very good idea, then I understand. But I don't know how to do this any other way. Any help appreciated.
Simply use:
$("#parentdiv div").click(function(){
var id = $(this).index(); //index of div, 0 based
var val = $(this).text(); //content of div, if you need it
});
No need to add unique IDs :) .
Demo:
http://jsfiddle.net/q9TaJ/
Docs:
http://api.jquery.com/index/
First, make sure to properly escape your outputs:
echo '<div id="parentdiv">';
for ($counter = 0; $counter < count($list); $counter++){
echo sprintf('<div data-id="%d">%s</div>',
$counter,
htmlspecialchars($list['important_info'])
);
}
echo '</div>';//parentdiv
I'm also using a special attribute called data-id which you can easily access in jQuery with this code:
$('#parentdiv > div').on('click', function() {
var id = $(this).data('id');
});
you can pass your variables as html attributes. Then bind the click event to a single class.
<div class="divs" data-id="myid"></div>
in jquery
$('.divs').click(function(){
console.log($(this).data('id));
});

How do I implement Ajax/JQuery to an existing PHP MYSQL pagination script?

Below is a working pagination script that displays content from a MySQL database. I need to have the pages seamlessly load within the container "#content" rather than have the entire page refreshed. I search extensively for hours but none of the tutorials I encountered helped me implement Ajax/JQuery on this script.
Here is the code I use to display my articles + pagination.
<div id="content">
<?php
include('db.php');
$stmt = $db->query('SELECT * FROM db');
$numrows = $stmt->rowCount();
$rowsperpage=21;
$totalpages=ceil($numrows/$rowsperpage);
if(isset($pageid)&&is_numeric($pageid)){$page=$pageid;}else{$page=1;}
if($page>$totalpages){$page = $totalpages;}
if($page<1){$page=1;}
$offset=($page-1)*$rowsperpage;
$stmt=$db->prepare("SELECT * FROM db ORDER BY ID DESC LIMIT ?,?");
$stmt->bindValue(1, "$offset", PDO::PARAM_STR);
$stmt->bindValue(2, "$rowsperpage", PDO::PARAM_STR);
if($stmt->execute()) {
while ($row = $stmt->fetch()) {
echo '
<article>
article here
</article>
';}}
$range=4;
echo'
<div id="pagination">';
if($page>1){
echo "
<a href='http://www.domain.com/1/'><<</a>";
$prevpage = $page - 1;
echo "
<a href='http://www.domain.com/$prevpage/'><</a>";
}
for ($x = ($page - $range); $x < (($page + $range) + 1); $x++) {
if(($x>0)&&($x<= $totalpages)){
if($x==$page){
echo'
<span class="current">'.$x.'</span>';
}
else{echo"<a href='http://www.domain.com/$x/'>$x</a>";}
}
}
if($page!=$totalpages){
$nextpage=$page+1;
echo"
<a href='http://www.domain.com/$nextpage/'>></a>";
echo "
<a href='http://www.domain.com/$totalpages/'>>></a>";
}
echo '
</div>';
?>
Your setup is a little unclear, but bear with me.
I'm going to assume that on the client side you know when to load the next page (ie the user clicks a button or scrolls to the end of the page etc...) I'm also going to assume that the PHP code you've posted is in its own file and outputs only what you've posted in your question (aka it outputs only the HTML for the articles and nothing else, no wrappers, nothing, if not make it so.
What you're going to want to do is use jQuery (From your question it looks like you already have it on your site so adding another library isn't too taboo) to make an AJAX request to this PHP page. The PHP then echos out what you've posted and the jQuery inserts this on the page inside the #content div.
First a note: I wouldn't recommend having your PHP page output the content div, I would recommend having that stay on the client side and only changing the content of it to what your script returns.
To load new content, you can use this javascript function on the client side:
function makePaginationRequest( pagenum = 1 ) {
// Make ajax request
$.ajax("test2.php", {
// Data to send to the PHP page
data: { "pagenum": pagenum },
// Type of data to receive (html)
dataType: 'html',
// What to do if we encounter a problem fetching it
error: function(xhr, text){
alert("Whoops! The request for new content failed");
},
// What to do when this completes succesfully
success: function(pagination) {
$('#content').html(pagination);
}
})
}
You can place any other parameters you need to pass to the server inside the "data" object (the data: { "pagenum": pagenum }, in key-value form. As you can see from the example, you pass the page number to this function and it passes the "pagenum" request variable to the server.
You'll want to implement a better error handler obviously. As well as change the "test2.htm" filename to that of your PHP script.
A better way of doing this
I feel compelled to mention this:
The way above (what you asked for) is really a messy way of doing this. Whenever you request AJAX data from your server, the server should return content, not markup. You should then insert this content into markup on the client side.
To do this, you would modify your PHP script to first put everything in an array (or an array of array for multiple articles) like this:
while ($row = $stmt->fetch()) {
$output_array[] = array(
"post_title" => $row["title"],
"post_date" => $row["date"],
// etc....
);
}
Then echo it like so:
die(json_encode($output_array));
Then modify your json request:
function makePaginationRequest( pagenum = 1 ) {
$.ajax("test2.htm", {
data: { "pagenum": pagenum },
dataType: 'json',
error: function(xhr, text){
alert("Whoops! The request for new content failed");
},
success: function(pagination) {
// Empty the content area
$('#content').empty();
// Insert each item
for ( var i in pagination ) {
var div = $('<article></article>');
div.append('<span class="title">' + pagination[i].post_title + "</span>");
div.append('<span class="date">' + pagination[i].post_date + "</span>");
$('#content').append(div)
}
}
})
}
jQuery will automagically parse this JSON output into a native javascript object for you.
Taking this approach of having the client make the markup takes alot of load off of your server, and requires less bandwith.
Food for thought, hope that helps.
If you want to do the least amount of rewriting to your original script, the jQuery .load() method might be your best bet. You would basically just need to supply an id to the element that contains all of your articles; something like this should work:
<div id="container">
<div id="articles-container">
<article> ... </article>
</div>
</div>
<div id="pagination">
1 ...
</div>
Then add a script tag and some jQuery code:
<script>
$(function(){
$('#pagination').on('click', 'a', function(e){
e.preventDefault();
var url = $(this).attr('href');
$('#container').load(url + ' #articles-container');
});
});
</script>
.load() will fetch the page, and if you add the optional fragment to the URL, it will filter the result to the element matching the fragment.
EDIT:
Okay, so, to make this work with your current pagination, you need to manually swap the elements. So, assuming your generated markup looks something like this:
<div id="pagination">
1
<span class="current">2</span>
3
4
5
</div>
We want this to happen after the load() completes, so we need to add a callback function to it. I'm also adding a self reference to the clicked element, which we need later:
$(function(){
$('#pagination').on('click', 'a', function(e){
e.preventDefault();
var $this = $(this);
var url = $this.attr('href');
$('#container').load(url + ' #articles-container', function(response, status, jqxhr){
});
});
});
Inside the callback is where we start manipulating #pagination. The first part is easy enough:
var $curr = $('#pagination span.current');
var page = $curr.text();
$curr.replaceWith('' + page + '');
Now we need to replace the link we just clicked:
$this.replaceWith('<span class="current">' + $this.text() + '</span>');
Et viola!, your pagination should be updated. Here's the whole update:
$(function(){
$('#pagination').on('click', 'a', function(e){
e.preventDefault();
var $this = $(this);
var url = $this.attr('href');
$('#container').load(url + ' #articles-container', function(response, status, jqxhr){
var $curr = $('#pagination span.current');
var page = $curr.text();
$curr.replaceWith('' + page + '');
$this.replaceWith('<span class="current">' + $this.text() + '</span>');
});
});
});

Javascript pagination (next project / previous project) with jQuery?

I recently came upon a site that has done exactly what I want as far as pagination goes. I have the same basic setup as the site I just found.
I would like to have prev and next links to navigate through my portfolio. Each project would be in a separate file (1.php, 2.php, 3.php, etc.) For example, if I am on the 1.php page and I click "next project" it will take me to 2.php.
The site I am referencing to accomplishes this with javascript. I don't think it's jQuery:
function nextPg(step) {
var str = window.location.href;
if(pNum = str.match(/(\d+)\.php/i)){
pNum = pNum[1] * 1 + step+'';
if ((pNum<1) || (pNum > 20)) { pNum = 1; }
pNum = "".substr(0, 4-pNum.length)+pNum;
window.location = str.replace(/\d+\.php/i, pNum+'.php');
}
}
And then the HTML:
Next Project
I can't really decipher the code above, but I assume the script detects what page you are on and the injects a number into the next page link that is one higher than the current page.
I suppose I could copy this code but it seems like it's not the best solution. Is there a way to do this with php(for people with javascript turned off)? And if not, can this script be converted for use with jQuery?
Also, if it can be done with php, can it be done without dirty URLs?
For example, http://www.example.com/index.php?next=31
I would like to retain link-ability.
I have searched on stackoverflow on this topic. There are many questions about pagination within a page, but none about navigating to another page that I could find.
From your question you know how many pages there are going to be. From this I mean that the content for the pages themselves are hardcoded, and not dynamically loaded from a database.
If this is the approach you're going to take you can take the same course in your javascript: set an array up with the filenames that you will be requesting, and then attach event handlers to your prev/next buttons to cycle through the array. You will also need to keep track of the 'current' page, and check that incrementing/decrementing the current page will not take you out of the bounds of your page array.
My solution below does the loading of the next page via AJAX, and does not change the actual location of the browser. This seems like a better approach to me, but your situation may be different. If so, you can just replace the related AJAX calls with window.location = pages[curPage] statements.
jQuery: (untested)
$(function() {
var pages = [
'1.php',
'2.php',
'3.php'
];
var curPage = 0;
$('.next').bind('click', function() {
curPage++;
if(curPage > pages.length)
curPage = 0;
$.ajax({
url: pages[curPage],
success: function(html) {
$('#pageContentContainer').html(html);
}
});
});
$('.prev').bind('click', function() {
curPage--;
if(curPage < 0)
curPage = (pages.length -1);
$.ajax({
url: pages[curPage],
success: function(html) {
$('#pageContentContainer').html(html);
}
});
});
});
HTML:
<div id = "pageContentContainer">
This is the default content to display upon page load.
</div>
<a class = "prev">Previous</a>
<a class = "next">Next</a>
To migrate this solution to one that does not have the pages themselves hardcoded but instead loaded from an external database, you could simply write a PHP script that outputs a JSON encoded array of the pages, and then call that script via AJAX and parse the JSON to replace the pages array above.
var pages = [];
$.ajax({
url: '/ajax/pages.php',
success: function(json) {
pages = JSON.parse(json);
}
});
You can do this without ever effecting the structure of the URL.
Create a function too control the page flow, with an ajax call
function changePage(page){
$.ajax({
type: 'POST',
url: 'myPaginationFile.php',
data: 'page='+page,
success: function(data){
//work with the returned data.
}
});
}
This function MUST be created as a Global function.
Now we call the function on page load so we always land at the first page initially.
changePage('1');
Then we need to create a Pagination File to handle our requests, and output what we need.
<?php
//include whatever you need here. We'll use MySQL for this example
$page = $_REQUEST['page'];
if($page){
$q = $("SELECT * FROM my_table");
$cur_page = $page; // what page are we on
$per_page = 15; //how many results do we want to show per page?
$results = mysql_query($q) or die("MySQL Error:" .mysql_error()); //query
$num_rows = mysql_num_rows($result); // how many rows are returned
$prev_page = $page-1 // previous page is this page, minus 1 page.
$next_page = $page+1 //next page is this page, plus 1 page.
$page_start = (($per_page * $page)-$per_page); //where does our page index start
if($num_rows<=$per_page){
$num_pages = 1;
//we checked to see if the rows we received were less than 15.
//if true, then we only have 1 page.
}else if(($num_rows % $per_page)==0){
$num_pages = ($num_rows/$per_page);
}else{
$num_pages = ($num_rows/$per_page)+1;
$num_pages = (int)$num_pages;
}
$q. = "order by myColumn ASC LIMIT $page_start, $per_page";
//add our pagination, order by our column, sort it by ascending
$result = mysql_query($q) or die ("MySQL Error: ".mysql_error());
while($row = mysql_fetch_array($result){
echo $row[0].','.$row[1].','.$row[2];
if($prev_page){
echo ' Previous ';
for(i=1;$i<=$num_pages;$i++){
if($1 != $page){
echo "<a href=\"JavaScript:changePage('".$i."');\";> ".$i."</a>";
}else{
echo '<a class="current_page"><b>'.$i.'</a>';
}
}
if($page != $num_pages){
echo "<a class='next_link' href='#' id='next-".$next_page."'> Next </a>';
}
}
}
}
I choose to explicitly define the next and previous functions; so here we go with jQuery!
$(".prev_link").live('click', function(e){
e.preventDefault();//not modifying URL's here.
var page = $(this).attr("id");
var page = page.replace(/prev-/g, '');
changePage(page);
});
$(".next_link").live('click', function(e){
e.preventDefault(); // not modifying URL's here
var page = $(this).attr("id");
var page = page.replace(/next-/g, '');
changePage(page);
});
Then finally, we go back to our changePage function that we built initially and we set a target for our data to go to, preferably a DIV already existing within the DOM.
...
success: function(data){
$("#paginationDiv").html(data);
}
I hope this gives you at least some insight into how I'd perform pagination with ajax and php without modifying the URL bar.
Good luck!

jQuery: Using an <a> link to submit an ajax query

I am trying to send a php script some content to be stored in a database via ajax. I am using the jQuery framework. I would like to use a link on a page to send the information. I am having trouble writing the function that will send and receive the information, everything that I have tried is asymptotic.
EDIT
The idea is that the user will click the link, and a column called "show_online" (a tiny int) in a table called "listings" will update to either 1 or 0 (**a basic binary toggle!) On success, specific link that was clicked will be updated (if it sent a 1 before, it will be set as 0).
EDIT
There will be 20-30 of these links on a page. I have set each containing div with a unique id ('onlineStatus'). I would rather not have a separate js function for every instance.
Any assistance is much appreciated. The essential code is below.
<script type="text/javascript">
function doAjaxPostOnline( shouldPost, bizID ){
load("ajaxPostOnline.php?b='+bizID+'&p='+shouldPost", jsonData, callbackFunction);
function callbackFunction(responseText, textStatus, XMLHttpRequest)
{
// if you need more functionality than just replacing the contents, do it here
}
}
}
</script>
<!-- the link that submits the info -->:
<div id='onlineStatus<?php echo $b_id ?>'>
<a href='#' onclick="doAjaxPostOnline( 0, <?php echo $b_id ?> ); return false;" >Post Online</a>
</div>
ajaxPostOnline.php
<!-- ajaxPostOnline.php ... the page that the form posts to -->
<?php
$id = mysql_real_escape_string($_GET['b']);
$show = mysql_real_escape_string($_GET['p']);
if( $id && ctype_digit($id) && ($show == 1 || $show == 0) ) {
mysql_query( "UPDATE listing SET show_online = $show
WHERE id = $id LIMIT 1" );
}
if($result) {
if($show == '0'){
$return = "<a class='onlineStatus' href='#' onchange='doAjaxPostOnline( 1, <?php echo $b_id ?> ); return false;' >Post Online</a>";
}
if($show == '1'){
$return = "<a class='onlineStatus' href='#' onchange='doAjaxPostOnline( 0, $b_id ); return false;' >Post Online</a>";
}
print json_encode(array("id" => $id, "return" => $return));
}
?>
The load() function in jQuery is really cool for this sort of thing.
Here's an example. Basically, you have an outer div as a container. You call a script/service which returns html. You have a div in that html with an id that you will refer to later in the ajax call. The replacement div replaces the inner html of the container div. You pass your data as a json object as the second parameter to the load method, and you can pass a reference to a callback function as the third parameter. The callback function will receive every possible piece of information from the response (the full response text for further parsing/processing, the http status code, and the XMLHttpRequest object associated with this ajax call).
$("#id_of_some_outer_div").load("somepage.php #id_of_replacement_div", jsonData, callbackFunction);
function callbackFunction(responseText, textStatus, XMLHttpRequest)
{
// if you need more functionality than just replacing the contents, do it here
}
so, in your case you're talking about replacing links. Put the original link inside of a div on both sides of the operation.
Here's the link to the jQuery api doc for load():
load
EDIT:
In response to your comment about doing multiple replacements in one pass:
You can have the callback function do all the work for you.
Add a unique css class to all divs that need replacing. This will allow you to select all of them in one shot. Remember that html elements can have more than one css class (that's what the "c" in CSS means). So, they'd all be <div id="[some unique id]" class="replace_me"... Then, if you have a variable set to $("div.replace_me"), this will be a collection of all divs with the replace_me style.
Whatever elements that come from the ajax call (whether they're another div container or just a single "a" element) should have a unique id similar to the container they're to be inserted into. For example, div_replace1 would be the id of a container and div_replace1_insert would be the id of the element to be inserted
Inside the callback function, iterate over the replacements using $("div.replace_me").each(function(){ ...
Inside each iteration the "this" keyword refers to the current item. You can grab the id of this item, have a variable like var replacement_id = this.id + "_insert"; (as in the example above) which is now the unique id of the element you'd like to insert. $("#" + replacement_id) will now give you a reference to the element you want to insert. You can do the insertion something like this: this.html( $("#" + replacement_id) );
You may have to edit the code above (it's not tested), but this would be the general idea. You can use naming conventions to relate elements in the ajax return data to elements on the page, iterate the elements on the page with "each", and replace them with this.html()
did you really mean to declare your ajax success return function as
function(html)
? .. i think maybe you mean for the param to be 'data' ?
Since your php script is returning json you should set the dataType to json. Note that in your posted code sample, the success function() was outside of the $.ajax() and it needs to be inside.
$.ajax({
url: "ajaxPostOnline.php?b=" + bizID + "&p=" + shouldPost,
dataType: "json",
success: function(json){
$("#onlineStatus" + bizID).html(json.return);
}
});
You might want to check out the getJSON method since it's more concise for this particular situation.
$.getJSON("ajaxPostOnline.php", {b:bizID, p:shouldPost}, function(json) {
$("#onlineStatus" + bizID).html(json.return);
});
EDIT: Original question was edited and the provided sample changed significantly. I would still recommend the $.getJSON method.
Unless I am mistaken, it seems you have an error mixing AJAX and server-side scripting.
That depends on whether $return is PHP parsed anywhere after assignment snippet in ajaxPostOnline.php (hardly, if it is called from AJAX!).
$return = "<a class='onlineStatus' href='#' onchange='doAjaxPostOnline( 1, <?php echo $b_id ?> ); return false;' >Post Online</a>";
Surely this should be:
$return = "<a class='onlineStatus' href='#' onchange='doAjaxPostOnline( 1, ".$id." ); return false;' >Post Online</a>";

Categories