Image Map Coordinates Hover with ajax not working - php

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.

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");

Posting With AJAX not working, Can't get $_POST value

So I'm having a little issue. I am working on a site and this is the first I have used ajax to post to to a page. I have a form with a submit button and a link on it. When the submit button is pressed everything works but users should be able to click the link to by pass a page but I still need some information posted to that page so I googled ho to post with out a submit button and ajax came up so I figured I'd give it a shot. It seems to not be working. Here is the code that I am using.
$('#chkEndAccDate').click(function(evt){
alert("before ajax");
var totalcost = $('#total_cost').val();
$.ajax({
type: "POST",
url: "http://sandbox.phareconsulting.com/complete_order.php",
`enter code here`data: {cost : totalCost}
});
alert("after ajax");
});
This code also doesn't work when i try it
$(document).on('click','#chkEndAccDate',function(){
cost = $('#total_cost').val();
$.post("http://www.sandbox.phareconsulting.com/complete_order.php",
{cost: cost},function(d){
alert("post");
});
});
In the php file right now I am simply doing print_r($_POST); but the post array is empty. Can some one please help me out. I think that some of us just don't understand ajax correctly. I thought I did but I am not able to get it to work.
Thank you.
This should be proper syntax:
data: "{'cost':'" + cost+ "'}"
Use this
data:{cost: cost}
for sending the data.
Use this code:
$(document).on('click','#chkEndAccDate',function(){
cost = $('#total_cost').val();
$.post("http://sandbox.phareconsulting.com/complete_order.php",
{cost: cost},function(d){
});
});
s.d and Thiefmaster have already written the correct syntax, however, it may be a good idea to change the name of your variable so as to avoid confusion.
var totalCost = $('#total_cost').val();
Then use:
data: {cost : totalCost}
Its a good idea to use the jQuery Form Plugin to send ajax forms this will by itself grab the data and send it to the form action url.
This plugin also gives you functions that control the sending process . This is an example :
var bar = $('#progressBar');
var percent = $('#percent');
var status = $('#status');
$('#form-id').ajaxForm({
beforeSend: function() {
//validate the data
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
// draw a progress bar during ajax request
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
complete: function(xhr) {
bar.width("100%");
percent.html("100%");
}
});
Html for the progress bar :
<div id="progress">
<div id="bar"></div >
<div id="percent">0%</div >
</div>
css :
#progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
#bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
#percent { position:absolute; display:inline-block; top:3px; left:48%; }

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();
});

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

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.

jQuery Plugin to update live a <li> from PHP

is there any jQuery plugin to create something like the live feed from the Twitter Main Page , using PHP, which is getting the data from a MySQL database?
How has to be the PHP file?
Thanks.
You really don't need a plugin for this, you could easily create something similar yourself using jQuery to make AJAX calls to a PHP MySQL feed
Create a script to make reoccurring AJAX calls using setTimeout() and then add the new found results to the feed container using .prepend()
HTML
<html>
<head><title>Tweets</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<style>
#tweets {
width: 500px;
font-family: Helvetica, Arial, sans-serif;
}
#tweets li {
background-color: #E5EECC;
margin: 2px;
list-style-type: none;
}
.author {
font-weight: bold
}
.date {
font-size: 10px;
}
</style>
<script>
jQuery(document).ready(function() {
setInterval("showNewTweets()", 1000);
});
function showNewTweets() {
$.getJSON("feed.php", null, function(data) {
if (data != null) {
$("#tweets").prepend($("<li><span class=\"author\">" + data.author + "</span> " + data.tweet + "<br /><span class=\"date\">" + data.date + "</span></li>").fadeIn("slow"));
}
});
}
</script>
</head>
<body>
<ul id="tweets"></ul>
</body>
</html>
PHP
<?php
echo json_encode(array( "author" => "someone",
"tweet" => "The time is: " . time(),
"date" => date('l jS \of F Y h:i:s A')));
?>
setInterval() would be more adequate, since you want a check at regular intervals.
Then, there is a jquery comet plugin that explores the implementation of the "push" technology. Check it out here.
var frequency = 5000, // number of milliseconds between updates.
updater = function() {
jQuery.ajax({
url: 'http://twitter.com/example/something.html',
success: function(data) {
// update your page based upon the value of data, e.g.:
jQuery('ul#feed').append('<li>' + data + '</li>');
}
});
},
interval = setInterval(updater, frequency);
<script>
$(document).ready(function(){
var frequency = 10000; // 10 seconds = 10000
var updater = function() {
$.ajax({
url: 'mesaj.html', // data source html php
cache: false,
success: function(data) {
$("#message").html(data); // div id
}
});
};
interval = setInterval(updater, frequency);
});
</script>
example
<div id="message">{ do not write }</div>

Categories