Stop reload of page when clicking a link leading to php script - javascript

I'm trying to implement some sort of news module on my website. The news is contained in a text file that I parse with php and display on the site. Some of these news have links "Details..." which should take me to a php script which will show the detailed text of that news item. I know how I could accomplish this with javascript, but I need to do it without using javascript. I want my page to not reload when taken to this script.
For example:
This is a news item:
echo '<article class="newsContainer">';
echo '<img src="' . $sadrzaj[3] . '" class="news_image" alt=" ">';
echo '<h1 class="news_header">' . ucfirst(strtolower($sadrzaj[2])) . '</h1>';
echo '<p class="news_item">' . $opis . '</p>';
if($imaDetaljnije) echo 'Detaljnije...';
echo '</article>';
This is the script I normally use to load a page using AJAX and to write it to the document:
function AjaxLoadJQuery(pageToLoad){
var requestObject = new XMLHttpRequest();
requestObject.onreadystatechange = function()
{
if (requestObject.readyState == 4 && requestObject.status == 200)
{
document.open();
document.write(requestObject.responseText);
document.close();
}
if (requestObject.readyState == 4 && requestObject.status == 404)
{
alert('belaj');
}
};
requestObject.open("GET", pageToLoad, true);
requestObject.send();
}
I pass it the url of the page and the content of my page changes.
Now I'd like to preserve this sort of Single page application model, but clicking this link would cause a page reload.
Is there any way I can do this, using javascript?

Try this
<a href="link_to_page.php" onClick="window.open(this.href); return false;" target="_blank">

Related

Do not load div until after full page load

I have a smart tag inside a hidden field in my WP Forms (written with php - see below) that collects user data, however this significantly slows down the webpage. The div ID is: wpforms-10395-field_107. The url is: https://ellasbubbles.com/contact-us/
My question is, how can I prevent this div from loading until after the page has fully loaded. This way it can load in the background while the user is populating their contact form details
Note: A better solution might be to keep this div empty, and simply populate it with the shortcode on page load?
PHP (currently in functions.php) - Grabs users location details and stores them in a smart tag:
add_shortcode('geo', 'shortcode');
function wpf_dev_register_smarttag( $tags ) {
// Key is the tag, item is the tag name.
$tags['geo'] = 'geo';
return $tags;
}
add_filter( 'wpforms_smart_tags', 'wpf_dev_register_smarttag' );
function wpf_dev_process_smarttag( $content, $tag ) {
$city = do_shortcode('[userip_location type=city]');
$country = do_shortcode('[userip_location type=country]');
$region = do_shortcode('[userip_location type=region]');
$flow = do_shortcode('[track-user-flow]');
// Only run if it is our desired tag.
if ( 'geo' === $tag ) {
$userinfo = '<b>City:</b> ' . $city . "\n" . '<b>Region:</b> ' . $region . "\n" . '<b>Country:</b> ' . $country . "\n" . "\n" . '<b>User Flow:</b> ' . $flow;
// Replace the tag with our link.
$content = str_replace( '{geo}', $userinfo, $content );
}
return $content;
}
add_filter( 'wpforms_smart_tag_process', 'wpf_dev_process_smarttag', 10, 2 );
It looks like I can use:
$(window).load(function(){
$.get("<path to php file>", function(data){
Replace Placeholder code here? (maybe)
});
})

Title Tag Nested inside itself with jQuery PHP Load

I have a dynamic site that loads only the body when a usr clicks a page. I am trying t change the title tag, but am getting no luck.
HTML:
<head>
// Title tag is contained in the php file
<?php include (BASEPATH . "includes/widgets/pageTitle.php"); ?>
</head>
JavaScript/jQuery:
$(document).on('click', 'a', function(e) {
// Page url of destination
var pageurl = $(this).attr('href');
var baseurl = "http://localhost/offstreams/";
// prevent page from loading
e.preventDefault();
// Empty info inside the body class and reload new info
// THIS WORKS PERFECTLY
$('.body').empty().load(pageurl + " > .body > *");
//!!!!!!!!!!!!!!!!!!!!!
// THIS IS THE PROBLEM
//!!!!!!!!!!!!!!!!!!!!!
$('title').empty().load(pageurl + "> title > *");
// Push the URL state
if(pageurl!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
//stop refreshing to the page given in
return false;
}
});
A Snippet of PHP code:
//Band page title tag
if (isset($_GET['member']) && isset($_GET['edit']) && isset($_GET['band'])){
$band_id = $_GET['band'];
$sql = "SELECT `band_name` FROM `bands` WHERE `band_id` = '$band_id'";
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($query)){
$band_name = $row['band_name'];
echo "<title>" . $band_name . " | " . "Offstreams</title>";
}
An example output on actual load would be Count to Four | Offstreams, which is what I want.
When I do the ajax load, the website works, but the title tag gives the default url like localhost/offstreams/etc... and the title tag turns into
<title>
<title>Count to Four | Offstreams</title>
</title>
Does anyone know why?
It looks like you're doubling up on title tags there, the $('title').empty() bit will be leaving the previous ones there.
Try putting the title tags in your initial html:
<head>
// Title tag is contained in the php file
<title><?php include (BASEPATH . "includes/widgets/pageTitle.php"); ?></title>
</head>
And removing them from your php:
echo $band_name . " | " . "Offstreams";
I don't understand the reason for outputting the title in a loop since there is only one per page, unless I am missing something in your code. Seems like it needs to be outside.
if (isset($_GET['member']) && isset($_GET['edit']) && isset($_GET['band'])){
$band_id = $_GET['band'];
$sql = "SELECT `band_name` FROM `bands` WHERE `band_id` = '$band_id'";
$query = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($query)){
$band_name = $row['band_name'];
}
echo "<title>" . $band_name . " | " . "Offstreams</title>";
}
In regards to your JQuery script, keep this in mind from the .load() documentation:
jQuery uses the browser's .innerHTML property to parse the retrieved
document and insert it into the current document. During this process,
browsers often filter elements from the document such as <html>,
<title>, or <head> elements. As a result, the elements retrieved by
.load() may not be exactly the same as if the document were retrieved
directly by the browser.
In other words, what you're doing may not work properly all the time with all browsers. With that in mind, give this a try.
$(document).on('click', 'a', function(e) {
// Page url of destination
var pageurl = $(this).attr('href');
// prevent page from loading
e.preventDefault();
// Empty info inside the body class and reload new info
// THIS WORKS PERFECTLY
$('.body').empty().load(pageurl + " > .body > *");
// Give this a try
$(pageurl).load(pageurl, function() {
$('title').load('title', function() {
document.title = $(this).text();
});
});
// Push the URL state
if(pageurl !== window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
//stop refreshing to the page given in
return false;
});

javascript call inside php where loop not working and breaks query

I am attempting to call a javascript function inside a php where loop. I've succeeded in calling the variable, however the function only works on the first line, and then breaks a subsequent query.
The javascript is a simple show/hide of a div or span tag with a specific id. I'm trying to have this appear for every instance of a variable, but only open the span associated with that entry, so I used a php variable from the query.
The javascript code is contained in the header; it works fine without the php, and the php works fine without the javascript but I can't seem to make them work together.
Here's the code:
while($row = mysqli_fetch_array($qir)) {
$ingredient_id = $row['ingredient_id'];
echo '<input type="checkbox" value="' . $ingredient_id . '" name="markdelete[]">';
echo $row['amt'] . ' ' .$row['ingredient_name']; ?> <button onclick="showHide('<?php echo $row['ingredient_id']; ?>'); return false">Edit amount</button> <br />
<span id="<?php echo $row['ingredient_id']; ?>" class="hide">
<?php include_once('amt.php');
echo '</span> ';
// }
echo '<br />';
}
echo '<input type ="submit" name="remove" value="Remove">';
First of all, the showHide is only working on the first record
It is also making this query not respond at all.
if (isset($_POST['remove'])) {
iF (!empty($_POST['markdelete'])) {
foreach ($_POST['markdelete'] as $delete_id) {
// remove specific source from source_subject
$rem_ing = "DELETE from dish_ingredient
where ingredient_id = $delete_id
and dish_id = $dish_id ";
mysqli_query($dbc, $rem_ing)
or die ('Error removing ingredient: '.mysqli_error($dbc));
}
}
}
I tried removing the return false;, to no avail. Please let me know if I need to show more of the code (e.g. the javascript itself)
Edit:
I've tried working within the php string (this is actually what I had tried first) but it seems to break everything (no javascript, no php)
echo $row['amt'] . ' ' .$row['ingredient_name'] . '<button onclick="showHide(\''. $row['ingredient_id'] .'\') return false">Edit amount</button> <br />';
echo '<span id=" '. $row['ingredient_id'] .' " class="hide">';
include_once('amt.php');
echo '</span> ';
Edit: I am open to other solutions if this is not something that is possible. I'm feeling a bit stumped. Realistically I just want to have a list of items called from a mysql database, and have a field appear onclick to edit an associated variable if desired without having to send it to another page or reload the script for usability (hence the javascript piece).
Thanks again, anyone who can assist.
Note: this is the script that I am calling:
<script language="JavaScript" type="text/JavaScript">
menu_status = new Array();
function showHide(theid){
if (document.getElementById) {
var switch_id = document.getElementById(theid);
if(menu_status[theid] != 'show') {
switch_id.className = 'show';
menu_status[theid] = 'show';
}else{
switch_id.className = 'hide';
menu_status[theid] = 'hide';
}
}
}
</script>
You don't need tag there as you are already in php block.Try it without and use
showHide(\''.$row['ingredient_id'].'\')
and change
<?php include_once(....);
to
include_once(........);
Hopefully that would work
===========
try this for you javascript
<script language="JavaScript" type="text/JavaScript">
function showHide(theid){
if (document.getElementById) {
var switch_id = document.getElementById(theid);
if(!switch_id) {
switch_id.className = (switch_id.className.indexOf("show") > -1) ? "hide" : "show"
}
}
}
Okay after a long time on this, I finally figured out what was going on. Part of the issue was that I was trying to call a form inside a form, which I had forgotten is not permitted in HTML, so this required some redesign.
Other issues involved calling loops within inside loops, which caused problems where the first record would work, but not for the remaining records.
The javascript above did not need to be modified, only the way that it was called.
Here is what worked. The main key was using include() instead of include_once().
while($r = $qir->fetch_assoc()) {
$ingredient_id = $r['ingredient_id'];
$amt = $r['amt'];
$ingredient_name = $r['ingredient_name'];
echo $r['amt'] . ' ' .$r['ingredient_name'];
if ($row['user_id'] == $user_id) {
echo ' <span class="openlink"><button onclick="showHide(\''.$ingredient_id. '\')">edit amount</button></span><br/>';
echo '<div id="'.$ingredient_id.'" class="hide">';
include('amt1.php');
echo '</div>';
}
}

How to dump every Flickr photo url from a set?

I'm not sure if this question is possible but what I want is to take a set of photos from Flickr and dump every url into a file (text is fine). Dumping them within anchor tags would be plus. So far I've seen this and I looked through the Galleria viewers JavaScript code but no luck. I'm expecting a simple few lines of code to do this because Galleria does it but I'm not really sure where in their code Flickr is accessed to get the image urls.
I think this might be the answer actually but if someone else comes along and has another answer I'll of course accept theirs instead of just mine.
It seems that phpflickr has this example which should work:
<?php
require_once("phpFlickr/phpFlickr.php");
// Create new phpFlickr object
$f = new phpFlickr("[API Key]");
$f->enableCache(
"db",
"mysql://[username]:[password]#[server]/[database]"
);
$i = 0;
if (!empty($_POST['username'])) {
// Find the NSID of the username inputted via the form
$person = $f->people_findByUsername($_POST['username']);
// Get the friendly URL of the user's photos
$photos_url = $f->urls_getUserPhotos($person['id']);
// Get the user's first 36 public photos
$photos = $f->people_getPublicPhotos($person['id'], NULL, NULL, 36);
// Loop through the photos and output the html
foreach ((array)$photos['photos']['photo'] as $photo) {
echo "<a href=$photos_url$photo[id]>";
echo "<img border='0' alt='$photo[title]' ".
"src=" . $f->buildPhotoURL($photo, "Square") . ">";
echo "</a>";
$i++;
// If it reaches the sixth photo, insert a line break
if ($i % 6 == 0) {
echo "<br>\n";
}
}
}
?>
<h3>Enter a username to search for</h3>
<form method='post'>
<input name='username'><br>
<input type='submit' value='Display Photos'>
</form>
<p>View Source</p>

How to link back to specific jquery-ui tabs during the pagination

I'm new to PHP and jquery-ui,
I have a problems in my php projects, I'm doing pagination within a jquery-ui tabs, but when click on next page or page number the page refreshed and display the 1st tab, while the pagination table is in 2nd tab. The following is my pagination code.
<?php
$range = 3;
if ($currentpage > 1) {
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=1'><<</a> ";
$prevpage = $currentpage - 1;
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$prevpage'><</a> ";
}
for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) {
if (($x > 0) && ($x <= $totalpages)) {
if ($x == $currentpage) {
echo " [<b>$x</b>] ";
} else {
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$x'>$x</a> ";
}
}
}
if ($currentpage != $totalpages) {
$nextpage = $currentpage + 1;
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$nextpage'>></a> ";
echo " <a href='{$_SERVER['PHP_SELF']}?currentpage=$totalpages'>>></a> ";
}
?>
I had tried to replace $_SERVER['PHP_SELF'] with #usersTab2 (the tab I wanted to go) but it wont work.
I'm using php $_GET method to get the current page data.The pagination works well, just I can't link back to the specific tab I want...
Hope to get replay and your help is much appreciate~ =)
ps: I'm sry for my english...
Add an id to all tabs;
And when load this page, create a rule to get value in hash from url and fire a click event in js.
Example:
url = test.com/#tab2
When page is ready, get the value in hash and fire event:
var div = get the value in hash url;
$("#"+div).click();
You will need to use JavaScript to target and load your pages. By using HTML links, the browser will refresh the page. I would suggest using the jQuery load() function.
Example:
<a href='javascript:void()' class='nextpage'>ยป</a>
Then in your script:
$('.nextpage').click(function() { $('#page').load('loader.php?page=number'); });

Categories