Ajax change before and after property after submit - php

I'm using Ajax newsletter submit in Laravel.
I want to change the mail icon into checked icon if the data passed successfully.
Ajax:
success: function (json) {
container.find('.newsletter-notification').addClass('success').html("You've successfully subscribed to Newsletter.");
$('.newsletter-block .newsletter-content .content button:before').css('content', '\e080');
},
css
.newsletter-block .newsletter-content .content button:before
{
content: "\e01f";
font-family: 'simple-line-icons';
}
How can I change content: "\e01f" into content: "\e080"

Try This
CSS
.newsletter-block .newsletter-content .content button:before
{
content: "\e01f";
font-family: 'simple-line-icons';
}
.newsletter-block .newsletter-content .content button.success:before
{
content: "\e080";
font-family: 'simple-line-icons';
}
Javascript
success: function (json) {
var = newsLetterBtn = $('.newsletter-block .newsletter-content .content button');
container.find('.newsletter-notification').addClass('success').html("You've successfully subscribed to Newsletter.");
newsLetterBtn.addClass('success');
},

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.

ajax php foreach loop update after each iteration

What I am trying to do is is use jQuery/Ajax to make a request to a PHP script and return a status update each time the foreach loop completes. I want to use the output to make a progress bar.
The problem I am having is the jQuery will only update the page once the whole script has completed. Is there a way to force either the jQuery or PHP to output on every loop and not just dump all of it on success function.
jQuery(document).ready(function($) {
$(document).on('click','#fetch-snowfall-data a',function () {
$(this).text('Fetching Snowfall Data...');
$.ajax({
type: "GET",
async: true,
url: "url.php",
data:{},
dataType: "html",
success: function(response){
$("#response_container").append(response);
$('#fetch-snowfall-data a').text('Fetch Snowfall Data');
}
});
return false;
});
});
PHP
foreach ( $results['resorts'] as $resort ) {
//Do all the things here
$count++;
echo $count .'/'. $results['total_rows'];
}
Thanks everyone for all your help. I eventually managed to get this all working properly and will share exactly how I did it for anyone else's future benefit.
There are 3 files that are required - The page you are loading from, the processing script and the listening script.
You will need to know how many rows you are going to process for everything to work. I load mine from php variable $results['total_rows']; in loading.php
Loading.php
jQuery(document).ready(function($) {
setTimeout(getProgress,1000);
$(document).on('click','#fetch-snowfall-data a',function () {
$(this).text('Fetching Snowfall Data...');
$.ajax({
url: 'process.php',
success: function(data) {
$("#response_container2").append(data);
}
});
setTimeout(getProgress,3000);
return false;
});
function getProgress(){
$.ajax({
url: 'listen.php',
success: function(data) {
if(data<=<?php echo $results['total_rows']; ?> && data>=1){
console.log(data);
$('#response_container').html('<div id="progress"><div class="progress-bar" role="progressbar" style="width:'+ (data / <?php echo $results["total_rows"] ?>)*100 +'%">'+ data + '/' +<?php echo $results["total_rows"] ?> +'</div></div>');
setTimeout(getProgress,1000);
console.log('Repeat');
} else {
$('#fetch-snowfall-data a').text('Fetch Snowfall Data');
console.log('End');
}
}
});
}
});
Process.php
foreach ( $results['resorts'] as $resort ) {
//Do all the things here you want to.
$count++;
session_start();
$_SESSION['progress'] = $count;
$_SESSION['total'] = $results['total_rows'];
session_write_close();
sleep(1);
}
unset($_SESSION['progress']);
Listen.php
session_start();
echo (!empty($_SESSION['progress']) ? $_SESSION['progress'] : '');
if (!empty($_SESSION['progress']) && $_SESSION['progress'] >= $_SESSION['total']) {
unset($_SESSION['progress']);
}
Some CSS for the progress bar
#progress {
height: 20px;
margin-bottom: 20px;
/* overflow: hidden; */
background-color: #f5f5f5;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,.1);
box-shadow: inset 0 1px 2px rgba(0,0,0,.1);
}
.progress-bar {
float: left;
width: 0;
height: 100%;
font-size: 12px;
line-height: 20px;
color: #fff;
text-align: center;
background-color: #337ab7;
-webkit-box-shadow: inset 0 -1px 0 rgba(0,0,0,.15);
box-shadow: inset 0 -1px 0 rgba(0,0,0,.15);
-webkit-transition: width .6s ease;
-o-transition: width .6s ease;
transition: width .6s ease;
}
As suggested by adeneo, I dont think you can return partial content. I tried to research on this before with no avail. However, if anyone can correct me, i'll be very appreciative.
The end result for me is to do recursive ajax.
javascript
var data = '';
$(document).on('click','#fetch-snowfall-data a',function () {
ajaxCall(0);
});
function ajaxCall(num) {
$.ajax({
type: "POST",
async: true,
url: "url.php",
data: num,
dataType: "json",
xhr:function(){
//progress bar information here.
},
success: function(response) {
$("#response_container").append(response['data']);
if (response['check'] === 'next') {
var nextNum = num +1;
data += response['data'];
ajaxCall(nextNum); //call itself for the next iteration
}else if (response['check'] === 'done'){
data = response['data'];
//do stuff with the data here.
}else if (response['check'] === 'error') {
return response['data'];
}
},
error:function(xhr, status,error){
//error information here
}
});
}
For PHP:
Just make sure you output stuff in json with two information. Json.check: to see if you want to move into the next iteration, finish and output data, or report error. Json.data to output whatever data it needs. What you need to do is output each report at a time without foreach loop
--edit--
I found some topic on streaming for php
http://www.sitepoint.com/php-streaming-output-buffering-explained/
Best approach for (cross-platform) real-time data streaming in PHP?

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.

Categories