jQuery loads the data from PHP but then it disappears, why? - php

I have searched to see if there is a post similar here and if someone finds it sorry for the duplicate.
So my dilemma is this:
Given the code below, why it my returned data loading and then disappearing?
CSS
#contentbg{
background-image: url(../images/jp_01.jpg);
background-repeat: no-repeat;
background-position: top;
position: absolute;
width: 755px;
height: 629px;
}
#content{
position: relative;
}
JS
function getHome(){
$.post("php/functions.php?s=home",
function(data) {
$('#content').html(data);
});
};
HTML
<div id="contentbg">
<div id="content"></div>
</div>
<ul id="navlist">
<li id="home"></li>
</ul>
PHP
function displayHome($home){
if(isset($home)){
$home = '<img src="images/home.jpg" alt="Home" width="755" height="630" />';
return $home;
}
}
if (isset($_GET['s'])) {
switch ($_GET['s']) {
case "home":
echo displayHome($_GET['s']);
break;
}
}
I know that the data gets loaded if I alter the JS as seen below:
function getHome(){
$.post("php/functions.php?s=home",
function(html) {
alert("Data Loaded: " + html);
});
};

The problem is that you are not cancelling the standard action when you click on the link so what is happening is that you click, the javascript gets executed and then index.php gets loaded.
You need to return false from your getHome function to solve this.
function getHome(){
$.post("php/functions.php?s=home",
function(data) {
$('#content').html(data);
});
return false;
}
As you are using jquery already, you can also get rid of the inline javascript and use a function like:
$("#home a").click(function(event) {
event.preventDefault();
$.post("php/functions.php?s=home",
function(data) {
$('#content').html(data);
});
);
That assures as well that the standard event (the click on the link) gets cancelled with the first line.

I don't see any item with the id #content in your HTML, are you sure it exists?

I assume #content is defined in your HTML structure:
$('#content').load('php/functions.php?s=home');
Also try removing #content { position: relative; } for now, just incase the content is "jumping" once loaded into the document

There seems to be no "content" div in your html.
Also, use
$("#content").load("url");
as theres no need to use $.post because no post data is being sent.

Related

Can't retrieve a specific portion of an HTML file (single.php) with AJAX in Wordpress

I have a small problem with a feature that I'm trying to implement on my site. I want when I click on an excerpt from a blog post on my homepage that the content of the article (single.php) opens in a modal window.
I use jQuery and Ajax to do that and it works really well except that Ajax fetches me the entire contents of single.php file (ie the header with scripts, styles, doctype, footer, etc.). I would just like to get the div (#PostContainer) that includes the title of the article and the content.
You will probably tell me to just delete my header and footer of the single.php file, but this is not possible because it is important to keep intact my file to be able to access from the address of the blog post (www.mydomainname.com/blog-post1).
It turns out that I am not at all familiar with WordPress :/ This is the first time I build a theme. The codes I shared with you run like a charm on WordPress but recovers me all of my single.php file (header + content in my div #postContainer + footer). I would like to recover only the contents of my div #postContainer.
I'm stuck :/
Someone would help me please ?
Thank you so so much for your time !
Here are my codes :
HTML :
<a class="hs-inner-click modal" data-content="<?php the_permalink(); ?>" rel="<?php the_ID(); ?>" href="<?php the_permalink(); ?>">
CSS :
.modal-window {
position: fixed;
left: 50%;
top: 50px;
width: 720px;
background-color: #fff;
transform: translate(-50%, 0);
z-index: 11;
}
.modal-shade {
position: fixed;
height: 100%;
width: 100%;
background-color: rgba(0, 0, 0, .7);
z-index: 10;
}
.modal-close {
position: absolute;
top: 10px;
right: 10px;
}
JQUERY & AJAX in a JS file :
(function($) {
$.fn.modal = function (opt) {
var settings, createModal, closeModal, body;
settings = $.extend({
'modal': 'jquery-modal',
'close': 'jquery-modal-close',
'closeText':'',
'shade': 'jquery-modal-shade'
}, opt);
body = $('body');
closeModal = function(modal, shade) {
modal.remove();
shade.remove();
};
createModal = function(data) {
var shade, close, modal;
shade =$('<div />', {
class: settings.shade
}).on('click', function() {
closeModal(modal, shade);
});
close =$('<a />', {
text: settings.closeText,
class: settings.close,
href: '#'
}).on('click', function(e) {
closeModal(modal, shade);
e.preventDefault();
});
modal =$('<div />', {
html: data,
class: settings.modal
}).append(close);
body.prepend(shade, modal);
};
this.on('click', function(e) {
var self =$(this);
$.ajax({
url:self.data('content'),
type: 'get',
cache: false,
}).done(function(data) {
createModal(data);
}).error(function() {
createModal('There is a mistake');
});
e.preventDefault();
});
};
})(jQuery);
I would suggest to use WordPress REST API V2 for the request without the need of selecting a div or loading single.php without header & footer.
This will allow you to load post content by just calling an endpoint similar to this: /wp-json/wp/v2/posts/<id>
Full API reference here.
Alternatively I am not sure if it will work but jquery code might help you (execute onload of modal): $("#jquery-modal").load("www.mydomainname.com/blog-post1 #postContainer");
ADDITIONALLY: On ajax success append content on a dummy div and use it to find only the part of the page you need and return it.
That's the way jquery load() actually works if you check the source.
jQuery( "<div>" ).append( jQuery.parseHTML(data) ).find("#postContainer");

Image Map Coordinates Hover with ajax not working

I'm having an image map with ajax hover to retrieve information from database table major_occurrence. But it's seems not working at all with the ajax call.
The hover is clickable so that it will redirect to another doRpMap.php showing the occurrence details.
Please advise on this matter. Thanks. *Pardon me being a programming newbie.
Am I doing the correct way for:
the variable to call back getOccCount.php $result in my Main Page?
how to insert the ajax call() into my <span>?
getOccCount.php
<?php
$location_id = $_GET['location_id'];
$query = "SELECT COUNT(occurrence_id) FROM major_occurrence WHERE '$location_id' = location_id GROUP BY location_id";
$result = mysqli_query($link, $query) or die(mysqli_error($link));
$array = mysql_fetch_row($result); //fetch result
echo json_encode($array);
?>
Main page
<style type="text/css">
#map {
margin:0;
padding:0;
width:950px;
height:1211px;
background:url(images/Campus-Map.jpg);
background-size: 950px 1211px;
font-family:arial, helvetica, sans-serif;
font-size:8pt;
}
#map li {
margin:0;
padding:0;
list-style:none;
}
#map li a {
position:absolute;
display:block;
background:url(blank.gif);
text-decoration:none;
color:#000;
}
#map li a span { display:none; }
#map li a:hover span {
position:relative;
display:block;
width:200px;
left:20px;
top:20px;
border:1px solid #000;
background:#fff;
padding:5px;
filter:alpha(opacity=80);
opacity:0.8;
}
#map a.rpc{
top: 1060px ;
left: 585px;
width: 78px;
height: 65px;
}
</style>
<body>
<script>
$(document).ready(function() {
$('#map span').hover(function () {
var $t = $(this);
var location_id = $t.attr("location_id");
$.ajax({
url: 'getOccCount.php',
data: "{location_id: location_id}",
dataType: 'json',
method: 'GET',
success: function (result) {
$t.html('Total Number of Occurrence: ' + result[0]);
}
}
});
});
</script>
<ul id="map">
<li><a class="rpc" href="doRPMap.php?location_id=1"><span location_id="1"><b>RPC</b></span></a></li>
</ul>
</body>
A complete solution will require some work. Let me give you a few ideas. I apologize for having trouble with formatting ... the {} function here doesn't seem to work properly for me.
As you stated, you want to query the number of incidents for a given location. In your getOccCount.php I don't see any mechanism of passing a location id. It appears that the query always returns ALL occurrences. You probably want to add a line similar to
$location_id = #$_REQUEST['location_id'];
and use that value in a WHERE clause in your query.
The <span> you have in your html doesn't have a location_id attribute:
<span><b>RPC</b></span>
So the line where you try to retrieve that attribute will not find anything:
var location_id = $(this).attr("location_id");
You're doing the same ajax call twice, in two different ways. The whole block starting with $.ajax({ makes a call to getOccCount.php, however, I don't see you doing anything with the data passed to the success callback.
Then again in the success callback function you write $.get("getOccCount.php", ... which essentially does the same call again. This time you're trying to pass the location_id parameter, which we already know is not looked at in getOccCount.php.
Where you are trying to store the result back in the span that the user hovered over you use $('#map>span') as a selector which will store the result in ALL spans.
So, a start to your solution could look like this:
<body>
<script>
$(document).ready(function() {
$('#map span').hover(function () {
var $t = $(this);
var location_id = $t.attr("location_id");
$.ajax({
url: 'getOccCount.php',
data: "{location_id: location_id}",
dataType: 'json',
method: 'GET',
success: function (result) {
$t.html('Total Number of Occurrence: ' + result[0]);
}
});
});
});
</script>
<ul id="map">
<li><a class="rpc" href="doRPMap.php?locID=1"><span location_id="1"><b>RPC</b></span></a></li>
</ul>
</body>
Like I said, a full solution will require more work, especially on passing the location_id into your query. Hope that my ideas will help make progress.

JQuery toggle Register multible divs

I have the following problem.
I have a register which is on the right side of the page. It has a button at the end and if you click on the button the register should toogle to the screen and if you click again, it should be hidden again.
This is my current solution:
jsfiddle.net/6JLr9/
(Button: green, Content: red
My problem here is: During the hiding and showing animation, the button doesn't move, when the animation is finished, the button is directly moved to the new (correct) position. How can I make the button move at the same time?
Thank you in advance
I have made some change in Javascript and CSS. Here are the changes
Javascript :
$(document).ready(
function(){
$('.videohilfe').click(function(){
if($('.videohilfe-wrapper').css('right') == '-200px')
$('.videohilfe-wrapper').animate({right:'0px'});
else
$('.videohilfe-wrapper').animate({right:'-200px'});
});
}
);
CSS :
.registers-wrapper {
position:fixed;
right:-200px; /* changed */
z-index:50;
}
I've updated your jsfiddle.
Changed a few things in js and css.
JS:
$(document).ready(
function(){
$('.registers').click(
function(){
if($(this).hasClass('open')){
$('.registers-wrapper').animate({'margin-left':'-33px'},1000);
$(this).removeClass('open');
}else{
$('.registers-wrapper').animate({'margin-left':'-233px'},1000);
$(this).addClass('open');
}
})
}
);
CSS:
.registers {
width:33px;
height:136px;
background-repeat:no-repeat;
float:left;
z-index:50;
}
.registers-content {
height:136px;
width:200px;
background-repeat:repeat-x;
background-color:red;
float:left;
z-index:50;
}
.registers-wrapper {
position:fixed;
left:100%;
z-index:50;
margin-left:-33px;
width:233px;
}
.videohilfe-wrapper {
top:160px;
}
.videohilfe {
background-color:green;
}
.videohilfe-content {
}
Now it works as expected.

Background not showing in internet explorer when using JQuery load function

I use the following jquery code to load a page...
$(function() {
$('#stats').load('statsto.php');
var visibleInterval = 60000;
var invisibleInterval = 120000;
$(function() {
setTimer();
$(document).bind('visibilitychange'), function() {
clearTimeout(timer);
setTimer();
};
});
function displayStats() {
$('#stats').load('statsto.php');
$.ajaxSetup({ cache: false });
}
function setTimer() {
timer = setInterval(displayStats, (document.hidden) ? invisibleInterval : visibleInterval);
}
});
and here is the style from statsto.php...
body {
font-family: Verdana;
font-size: 7px;
color: #FFFFFF;
background-color: #000000;
background-image: url("grad.png");
}
But the background image is not showing in internet explorer. I have tried using background: black url("grad.png"); but that also doesn't work. I have also tried including the style in the same page as the JQuery code, but still no luck.
Hmm.. Your issue may be with the .load() function itself (in Internet Explorer). I seem to remember encountering an issue with that a while back...
Try this
$.get('statso.php', function() {
$('#stats').html();
});

PHP Image Loading

I have a PHP Image that I use like this:
<img src="image.php">
Sometimes it takes up to 10 seconds to render (there are some heavy dataloads coming in from an API). It works great but there's no way of telling whether anything is happening, I was wondering if there was a way I could show a Loading message while its doing its business, either in Javascript or PHP.
Thanks!
<img src="image.php" style="background: url(loading.gif) no-repeat center center;" />
Where loading.gif could be something like an ajax spinner animation.
I use this technique all the time.
Check out this example
HTML
<ul id="portfolio">
<li class="loading"></li>
<li class="loading"></li>
<li class="loading"></li>
</ul>
Javascript
// DOM ready
$(function () {
// image source
var images = new Array();
images[0] = 'http://farm4.static.flickr.com/3293/2805001285_4164179461_m.jpg';
images[1] = 'http://farm4.static.flickr.com/3103/2801920553_656406f2dd_m.jpg';
images[2] = 'http://farm41.static.flickr.com/3248/2802705514_b7a0ba55c9_m.jpg';
// loop through matching element
$("ul#portfolio li").each(function(index,el){
// new image object
var img = new Image();
// image onload
$(img).load(function () {
// hide first
$(this).css('display','none'); // since .hide() failed in safari
//
$(el).removeClass('loading').append(this);
$(this).fadeIn();
}).error(function () {
$(el).remove();
}).attr('src', images[index]);
});
});
CSS
ul#portfolio { margin:0; padding:0; }
ul#portfolio li { float:left; margin:0 5px 0 0; width:250px; height:250px; list-style:none; }
ul#portfolio li.loading { background: url(http://www.codedigest.com/img/loading.gif) no-repeat center center; width:50px;height:50px}
Check out the DEMO
The Code:
/*
overlay function:
-------------------------
Shows fancy ajax loading message. To remove this message box,
simply call this from your code:
$('#overlay').remove();
*/
function overlay()
{
if (!$('#overlay').is(':visible'))
{
$('<div id="overlay">Working, please wait...</div>').css({
width:'300px',
height: '80px',
//position: 'fixed', /* this is not suppported in IE6 :( */
position: 'absolute',
top: '50%',
left: '50%',
background:'url(images/spinner.gif) no-repeat 50% 50px #999999',
textAlign:'center',
padding:'10px',
border:'12px solid #cccccc',
marginLeft: '-150px',
//marginTop: '-40px',
marginTop: -40 + $(window).scrollTop() + "px",
zIndex:'99',
overflow: 'auto',
color:'#ffffff',
fontWeight:'bold',
fontSize:'17px',
opacity:0.8,
MozBorderRadius:'10px',
WebkitBorderRadius:'10px',
borderRadius:'10px'
}).appendTo($('body'));
}
}
You can edit background: property above to specify loading image too. You need to call overlay() function when you want to show the loading message. Later, you can use $('#overlay').remove(); to remove the loading message any time.
Why not try caching the image object? Would reduce the load? Or is this something that is always updating? Your JavaScript approach would simply be a image pre-loader or handler function that would replace the 'img' with a loading indicator. Look # jQuery for a simple way of doing this.
<img src="image.php">loading...</img>

Categories