HTML - Change\Update page contents without refreshing\reloading the page - php

I get the data from DB and display it in a div... what I want to do is when I click a link it should change the content of the div
one option is to pass parameter through URL to itself and reload the page...
I need to do it without reloading\refreshing...
<?php
$id = '1';
function recp( $rId ) {
$id = $rId;
}
?>
<a href="#" onClick="<?php recp('1') ?>" > One </a>
<a href="#" onClick="<?php recp('2') ?>" > Two </a>
<a href="#" onClick="<?php recp('3') ?>" > Three </a>
<div id='myStyle'>
<?php
require ('myConnect.php');
$results = mysql_query("SELECT para FROM content WHERE para_ID='$id'");
if( mysql_num_rows($results) > 0 ) {
$row = mysql_fetch_array( $results );
echo $row['para'];
}
?>
</div>
The goal is when I click any of the links the contents of the div and php variable\s gets updated without refreshing.... so that user could see new data and after that if some query is performed it is on new variable\s
p.s I know it is gonna require some AJAX but I don't know AJAX.. so please reply with something by which I can learn... my knowledge is limited to HTML, PHP, some JavaScript & some jQuery

You've got the right idea, so here's how to go ahead: the onclick handlers run on the client side, in the browser, so you cannot call a PHP function directly. Instead, you need to add a JavaScript function that (as you mentioned) uses AJAX to call a PHP script and retrieve the data. Using jQuery, you can do something like this:
<script type="text/javascript">
function recp(id) {
$('#myStyle').load('data.php?id=' + id);
}
</script>
<a href="#" onClick="recp('1')" > One </a>
<a href="#" onClick="recp('2')" > Two </a>
<a href="#" onClick="recp('3')" > Three </a>
<div id='myStyle'>
</div>
Then you put your PHP code into a separate file: (I've called it data.php in the above example)
<?php
require ('myConnect.php');
$id = $_GET['id'];
$results = mysql_query("SELECT para FROM content WHERE para_ID='$id'");
if( mysql_num_rows($results) > 0 )
{
$row = mysql_fetch_array( $results );
echo $row['para'];
}
?>

jQuery will do the job.
You can use either jQuery.ajax function, which is general one for performing ajax calls, or its wrappers: jQuery.get, jQuery.post for getting/posting data.
Its very easy to use, for example, check out this tutorial, which shows how to use jQuery with PHP.

Related

How do I run my php function through Ajax and loop through the results?

So I am trying to build a simple search function for my website, and I don't want to have to refresh the page to return results. The code that i have here works perfectly, But I don't know how to Implement this using Jquery. I mainly have 2 pages, index.php and library.php
The section from the library.php that handles the search is as follows.
require_once('auth/includes/connect.php');
class MainLib
{
public function search($keyword){
try {
$db = DB();
$query = $db->prepare("SELECT houses.*, users.user_id FROM houses JOIN users ON users.user_id=houses.ownerid WHERE houses.location=:keyword");
$query->bindParam(":keyword", $keyword, PDO::PARAM_STR);
$query->execute();
if ($query->rowCount() > 0) {
return $query->fetchAll(PDO::FETCH_OBJ);
}
} catch (PDOException $e) {
exit($e->getMessage());
}
}
}
And the Section From the index.php that prints the results is as follows
<?php $hdata = new MainLib();
if(isset($_POST[$search])){
$houses = $hdata->search($search); // get user details
foreach($houses as $house){
?>
<div class="single-property-box">
<div class="property-item">
<a class="property-img" href="#"><img src="houses/<?php echo $house->main_image ?>" alt="#">
</a>
<ul class="feature_text">
<?php
if($house->featured=='true'){
?>
<li class="feature_cb"><span> Featured</span></li>
<?php }?>
<li class="feature_or"><span><?php echo $house->gender ?></span></li>
</ul>
<div class="property-author-wrap">
<a href="#" class="property-author">
<img src="dash/auth/users/<?php echo $house->profilepic ?>" alt="...">
<span><?php echo $house->title ?>. <?php echo $house->surname ?></span>
</a>
<ul class="save-btn">
<li data-toggle="tooltip" data-placement="top" title="" data-original-title="Bookmark"><i class="lnr lnr-heart"></i></li>
<li data-toggle="tooltip" data-placement="top" title="" data-original-title="Add to Compare"><i class="fas fa-arrows-alt-h"></i></li>
</ul>
</div>
</div>
<?php }}?>
So How would I accomplish the same result without having to reload the page every time ?
Here's a basic ajax search form setup using jQuery. Note that the search input is in a form with onsubmit="return false" - this is one way to prevent the default form submission which would trigger a page reload.
The button calls a function which gets the value of the search input, makes sure it's not blank, and puts it into an ajax function
The PHP page will receive the search term as $_GET['term'] and do it's thing. In the end, you will output (echo) html from your PHP functions, which the ajax done() callback will put into your search_results div. There are more optimized ways of transferring the data back - maybe a minimal json string that contains just the info you need for results, and your javascript takes it and inflates it into an html template. For large search results, this would be better because it means less data getting transferred and faster results.
function search() {
let term = $('#search_term').val().trim()
if (term == "") return; // nothign to search
$.ajax({
url: "searchFunctionPage.php",
method: 'get',
data: {
term: term
}
}).done(function(html) {
$('#search_results').html(html);
});
// sample data since we dont have the ajax running in the snippet
let html = 'Found 100 results.. <div>result 1</div><div>...</div>';
$('#search_results').html(html);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit='return false;'>
<input type='text' placeholder="Type in your search keyphrase" id='search_term' />
<button type='button' onclick='search()'>Search</button>
</form>
<div id='search_results'></div>

Have all rows deleted by link/button click, and prevent it from auto executing

I need some help with this code. I'd really like to delete all of the rows in a table just by the press of a link/button. In this case, there's a small "x" in the corner of the box where the message is displayed.
I've tried to set the href and onclick function to: $query = mysql_query("DELETE FROM ad"); But it somehow executes the command without pressing the "X" button. If I do remove the line from the code, it all works. (I do wish to have the delete function on the page I'm working on, and not to add a delete.php page for instance) Is there any solution for this problem?
<?php if($row_ad['type'] == 1){ ?>
<div class="box error-box fx">
<a class="close-box" href="#"><i class="fa fa-times"></i></a>
<center>
<h3><?php echo $row_ad['title']; ?></h3>
<p><?php echo $row_ad['text']; ?></p></center>
<?php } ?>
PHP is serverside and HTML/JS is client-side, the only way to do what you want is to look up AJAX;
http://en.wikipedia.org/wiki/Ajax_%28programming%29
http://www.w3schools.com/ajax/

Refreshing div with ajax loses link to javascript file

I have a div that includes shoutbox posts. I'm using jQuery and ajax to change the pages within the div. However, when the page changes, it loses the link to the javascript file so that the next time I try to change the page it actually continues with the link action instead of doing the ajax in the background. Then after that it's back to normal and it alternates back and forth between being linked to the file and not.
Also before, it was rendering the whole page so that my layout was being displayed on the refresh instead of just the shoutbox posts. I'm guessing that finally getting it to refresh without re displaying the whole layout again is what's causing it to lose the connection to the javascript file.
This is the code for the posts. The shoutbox_arrows contains the links to change the page. refresh_me is what I'm loading into my div to refresh the content.
<div id="shoutbox_arrows">
<?php $current_page=s tr_replace( '?', '#', getURI(fullURL())); ?>
<ul class="no_dots">
<li id="first_page"><<
</li>
<li id="previous_page"><
</li>
<li><strong>Pg#<?php if ($page > $last_page) {echo $last_page;} else {echo $_SESSION['shoutbox_page'];} ?></strong>
</li>
<li id="next_page">>
</li>
<li id="last_page">>>
</li>
</ul>
</div>
<div id="shoutbox" class="custom_scrollbar">
<div id="refresh_me">
<?php if (sizeof($shouts)==0 ) { ?>
<p>There are no posts.</p>
<?php } foreach ($shouts as $shout) { foreach ($shout as $k=>$v) { $shout[$k] = utf8_encode($v); if ($k == 'guest') { $shout[$k] = ucwords($v); } } ?>
<div class="post_info">
<div class="left">
<?php if ($shout[ 'user_id']==n ull) {echo $shout[ 'guest'];} else { ?><?php echo ucwords(userinfo($shout['user_id'])->username); ?>
<?php } ?>
</div>
<div class="right">
<?php time_format($shout[ 'created_at']); ?>
</div>
</div>
<p class="post_comment" id="shoutbox_comment_<?php echo $shout['id']; ?>">
<?php echo $shout[ 'comment']; ?>
</p>
<?php if (!$shout[ 'last_edited_by']==n ull) { ?>
<p class="last_edited">Edited by
<?php echo ucwords(userinfo($shout[ 'last_edited_by'])->username); ?>
<?php time_prefix($shout[ 'updated_at']); ?>
<?php time_format($shout[ 'updated_at']); ?>.</p>
<?php } ?>
<?php if (current_user()) { if (current_user()->user_id == $shout['user_id'] or current_user()->is_mod) { ?>
<p class="post_edit"> <span class="edit" id="<?php echo $page; ?>">
<a id="<?php echo $shout['id']; ?>" href="<?php $post_to = '?id=' . $shout['id']. '&uid=' . $shout['user_id']; echo $post_to; ?>">
edit
</a>
</span> | <span class="delete" id="<?php echo $page; ?>">
<a href="<?php $post_to = '?id=' . $shout['id']. '&uid=' . $shout['user_id']; echo $post_to; ?>">
delete
</a>
</span>
<span class="hide" id="<?php echo $page; ?>">
<?php if (current_user()->is_mod) { ?> | <a href="<?php $post_to = '?id=' . $shout['id']. '&uid=' . $shout['user_id']; echo $post_to; ?>">
hide
</a><?php } ?>
</span>
</p>
<?php }} ?>
<?php } ?>
</div>
</div>
This is the page that my ajax request is going to.
<?php
if (isset($data['page'])) {
$_SESSION['shoutbox_page'] = intval($data['page']);
}
$redirect = ltrim(str_replace('#', '?', $data['redirect']), '/');
redirect_to($redirect);
Div that contains the content to be refreshed.
<div id="shoutbox_container">
<?php relativeInclude( 'views/shoutbox/shoutbox'); ?>
</div>
jQuery
$('#shoutbox_arrows ul li a').click(function (event) {
event.preventDefault();
$.post('views/shoutbox/' + $(this).attr('href'), function (data) {
$('#refresh_me').load(location.href + " #refresh_me>", "");
$('#shoutbox_arrows').load(location.href + " #shoutbox_arrows>", "");
});
});
So I guess to clarify the issue:
The shoutbox_container displays posts for the shoutbox. The page is controller by a session that gets passed as a variable to get the correct chunk of posts to show. Clicking on the links in shoutbox_arrows sends an ajax request to a page which changes the session variable. The div that contains the post itself (refresh_me) as well as the arrows (for the links) get refreshed. After changing the page once, the shoutbox is no longer connected to the javascript file so when you click to change the page again, instead of an ajax request, the page itself actually changes to the link.
Any ideas how I can fix this? I've spent a lot of time on this and it's getting rather frustrating. I feel like I could just settle for it as it is now but it's bugging me too much that it's not working exactly how I intend (although generally it works in terms of changing the pages).
Also just a note, I used jsfiddle to tidy up the code but it looks like it did some funky stuff (looking just at $current_page=s tr_replace). lol. So there aren't any syntax errors if that's what you're thinking. ><
Also I was going to set up a fiddle but I don't really know how to handle links in it so it would have been useless.
The issue is that you bind the click handler to the a tags on document ready (the jQuery code you provided). So when you replace the content of #shoutbox_arrows you remove the click handler you previously attached since those original handlers are removed from the DOM along with the original elements.
You need to use the jQuery .on() method and event bubbling. This will attach the handler on a parent element that will not be removed in your content replace and can continue to "watch" for the event to bubble up from it children elements.
Try replacing your jQuery code with this:
$('#shoutbox_arrows').on('click', 'ul li a', function (event) {
event.preventDefault();
$.post('views/shoutbox/' + $(this).attr('href'), function (data) {
$('#refresh_me').load(location.href + " #refresh_me>", "");
$('#shoutbox_arrows').load(location.href + " #shoutbox_arrows>", "");
});
});
For performance, you should add a class to the a, and targeting it directly with $('a.aClass')
Good ways to improve jQuery selector performance?

Change image onclick - Javascript buttons & AJAX?

I'm have a wordpress installation where i have 2x custom fields, that both store images (or rather the urls for the images).
I then have a div that i want to display the images in. but i want to display the first image, then have some nice buttons that will scroll to the next image.
My code so far is below:
<div>
<?php
$front_cover = get_post_meta($post->ID, 'front_cover', true);
$back_cover = get_post_meta($post->ID, 'back_cover', true);
$artwork = $front_cover;
if ($back_cover === '') {
echo '<img src="'.$artwork.'" />';
} else {
echo '<img src="'.$artwork.'" />';
?>
<div class="artwork_controls">
Previous
Next
<span class="sliderPagination">1 of 3</span>
</div>
</div>
<?php } ?>
As you can see. my If statement checks if the back_cover has any content... if it doesn't it displays the front_cover only.
If the back_cover does have content it should display the front cover and then the buttons that the user clicks to load up the back cover.
My thinking was that i could get the 'previous' and 'next' buttons to dynamically change the $artwork variable, but i don't believe that's possible as the PHP would have already been processed?
This code could be completely wrong, but hopefully you can see what i'm trying to do?
<div>
<?php $front_cover = get_post_meta($post->ID, 'front_cover', true); ?>
<?php $back_cover = get_post_meta($post->ID, 'back_cover', true); ?>
<?php $artwork = $front_cover; ?>
<?php if ($back_cover === '') { ?>
<img src="<?php echo $artwork; ?>" />
<?php } else { ?>
<img id="imgA" src="<?php echo $artwork; ?>" />
<img id="imgB" src="<?php echo $back_cover; ?>" style="display:none;"/>
<div class="artwork_controls">
<span class="sliderBtnPrev" onClick="document.getElementById('imgA').style.display='none';document.getElementById('imgB').style.display='';">Show B</span>
<span class="sliderBtnNext" onClick="document.getElementById('imgB').style.display='none';document.getElementById('imgA').style.display='';">Show A</span>
</div>
<?php } ?>
</div>
One way would be to do AJAX calls and fetch images upon clicking the "Previous" and "Next" buttons.
However you can just put all your images in the final html and do all the rest with javascript and some css.
So if you just put the two images in the html, lets say they have ids "front-image" and "back-image" so you've got this
<img id="front-image" src="imgs/front-cover.jpg"/>
<img id="back-image" src="imgs/back-cover.jpg" style="visiblity: hidden"/>
Notice the style="visibility: hidden". From than on you can have onClick handlers on your Previous and Next buttons which just set the visibility of the two images.
clickHandlerPrev() {
document.querySelector("#front-image").style.visibility = "";
document.querySelector("#back-image").style.visibility = "hidden";
}
clickHandlerNext() {
document.querySelector("#front-image").style.visibility = "hidden";
document.querySelector("#back-image").style.visibility = "";
}
Then your buttons would look like this
Previous
Next
Though if I'm getting your goal right, I think your buttons are better named simply "Front cover" and "Back cover" since you're not iterating over lots of images, but switching just those two.

mouseover event similar to buttons on bottom of questions on this website

Ok,
Firstly, if you click on the questions link at the top of this page, each question has some buttons at the bottom that pertain to the question. when you mouseover them it shows more about the button. How is this done? I want to do this on my site.
So basically, i am using a php while loop to echo listitems's queried from a users id in mysql.
each listitem contains some more block and inline elements. some of those block elements have onmouseover/mouseout events attached to them. yet if i use the same class name on those elements, when i trigger a mouseover, it triggers every element with that class name. I am new to php / js / jquery, and not sure on the best way to go about it. any help would be grand. Example below.
<ul class="ulclass">
<?php
$link = mysql_query("SELECT * FROM table WHERE id='".$_SESSION['id']."' ORDER BY lid");
$i = 1;
while ($row=mysql_fetch_assoc($link)) {
$ico = $row['url'];
echo '
<li>
<a href="'.$row['url'].'" target="_blank" >
<div class="title">'.$row['title'].'</div>
</a>
<div onclick="/*here i want to change the next div.css display to block*/">
<img src="something.png" class="something_img"/>
<div class="drop_menu" id="drop_menu'.$i.'"
onmouseout="t=setTimeout(\'/*here i want to change this div.
css display back to none*/\',300);" >
<form method="post" action="" onmouseover="clearTimeout(t);">
<input type="hidden" name="deletetitle" value="'.$row['hash'].'"/>
<input type="submit" class="" name="delete" value="x"/>
</form>
</div>
</div>
</li>';
$i++;
}
?>
</ul>
let's fix some little things first. You don't really need to put all the HTML in a string, you can just do stuff like:
<?php
while ( $i < 10 ) {
?>
<li>Line number <?php echo $i; ?></li>
<?php
$i++;
}
?>
This way you will retain syntax highlighting and you won't have all kinds of problems that will arise from using string (like having to escape all single quotes etc.).
On the subject of JavaScript / jQuery – you shouldn't really use inline event handlers, such as onclick / onmouseover. It's really hard to maintain mixed up code, it's already enough there is HTML and PHP, don't add JavaScript to the same place. You should put in a separate file (or at least in a separate <script> tag before the closing </body> tag) and hook to the elements by their classes. I simplified your code a little, I am also not 100% sure what you wanted to achieve with the code you posted, but judging by the example of stackoverlow tag links, I will do something similiar:
<a href="'.$row['url'].'" target="_blank" class="tag">
<div class="title">'.$row['title'].'</div>
<div class="drop-out">Content of the drop-out.</div>
</a>
So, we have class tag for the link, and we want to hover it and see the internal element, and we take the mouse out it should disappear, let's see what jQuery we need for that (don't forget to add it to your page):
$('.tag').hover(
function () {
// `this` points to the DOM element we are hovering
$(this).children('.drop-out').css({
display : 'block'
, opacity : 1
});
}
, function () {
$(this).children('.drop-out').animate({
opacity : 0
}, 350, function () {
$(this).css('display', 'none');
});
}
);
Here's the example: http://jsfiddle.net/R6sYD/
jQuery methods used in this example:
http://api.jquery.com/hover/
http://api.jquery.com/children/
http://api.jquery.com/css/
http://api.jquery.com/animate/
Hope this helps.

Categories