jQuery load default page issue - javascript

I have this page which loads quotes. It has a search form wherein if the user types in the search keyword, it will load the results via ajax. Now, if I click on the link which should load the default page with the Quotes, instead of the search results page, nothing happens.
If I am on the home/default page itself, and click on the link, it will display a random quote, but once it displays the search page, if I click on the link to display a random quote, nothing happens. Firebug shows that the function isn't being executed.
jQuery code:
function loadQuotes() {
$("#bquote").load("quotes_in.php");
}
$("a#main").click(function() {
$(this).addClass("current");
$(".toggleDiv").slideUp(600);
loadQuotes();
});
loadQuotes(); //call it once on load
$(".bsearch").keydown(function() {
//create post data
var postData = {
"search" : $(this).val()
};
//make the call
$.ajax({
type: "POST",
url: "quotes_in.php",
data: postData, //send it along with your call
success: function(response){
setTimeout(function() {
$('#left').html(response);
$("div#smore").hide();
}, 250);
}
});
})
HTML:
<!-- Begin Left Column -->
<div id="left">
<!-- Begin Panel -->
<div class="check">
<p><input type="checkbox" value="Quote" name="quote" id="quote" checked /> <label for="quote">Quote</label></p>
<p><input type="checkbox" value="Reference" name="reference" id="reference" checked /> <label for="reference">Reference</label></p>
</div>
<!-- End Panel -->
<!-- Begin Quote -->
<blockquote id="bquote">
</blockquote>
<!-- End Quote -->
</div>
<!-- End Left Column -->
<!-- Begin Naviagtion -->
<div id="navigation">
<ul>
<li><a id="main">Another?</a></li>
<li><a id="bsearch">Search</a></li>
<li><a id="babout">About</a></li>
<li><a id="bcontact">Contact</a></li>
</ul>
</div>
<!-- End Naviagtion -->
PHP search:
public function formatSearch($row, $search)
{
$cQuote = $this->highlightWords(htmlspecialchars($row['cQuotes']), $search);
return "<div class=\"swrap\">"
. "<p id=\"s_quotes\"><img src=\"image/list1.png\" alt=\"b\" style=\"position:relative; top:2px;\"> " . $cQuote . " </p>"
. "<div id=\"smore\"><p id=\"s_arabic\">" . $this->h($row['cArabic']) . "</p>"
. "<p id=\"s_author\"><b>~</b> " . $this->h($row['vAuthor']) . "</p>"
. "<p id=\"s_reference\"><span class=\"source\">Source:</span> " . $this->h($row['vReference']) . "</p></div></div>"
. "<img src=\"image/sep.png\" style=\"position:relative; left: 600px;\">";
}

The new results aren't going to be acknowledged by the JavaScript as the script only acknowledges what HTML is there upon the page load. For your function to be able to 'see' HTML generated via AJAX Functions, you need to use he Jquery live function http://api.jquery.com/live/
Convert your current click function to something like this
$('a#main').live('click', function() {
$(this).addClass("current");
$(".toggleDiv").slideUp(600);
loadQuotes();
});

Related

Can't return html from controller using Ajax calls in a Chat app

So i'm building an integrated chat app in CRM. Whenever the logged in user click on a contact it displays the chat history between both users using Ajax calls, and this is where troubles begin.
So here's my Ajax Call code:
function GetChatHistory(receiver_id){
$.ajax({
dataType : "json",
url: '/chat/get_chat_history_by_user',
data:{receiver_id:receiver_id},
success:function(data)
{
$('#chathistory').html(data);
ScrollDown();
},
error: function (jqXHR, status, err) {
// alert('Local error callback');
alert("error fetching")
}
});
}
this is my controller
public function get_chat_history_by_user(){
//get the receiver id
$receiver_id = $this->input->get('receiver_id');
//get the sender id
$Logged_sender_id = $this->session->userdata['user_id'];
$history = $this->chat_model->GetReciverChatHistory($receiver_id);
foreach($history as $chat):
$message_id = $chat['id'];
$sender_id = $chat['sender_id'];
$userName = $this->UserModel->GetName($chat['sender_id']);
$userPic = $this->UserModel->PictureUrlById($chat['sender_id']);
$messagebody = $chat['message'];
$messagedatetime = date('d M H:i A',strtotime($chat['message_date_time']));
?>
<?php if($Logged_sender_id!=$sender_id){?>
<!-- Message. Default to the left -->
<div class="direct-chat-msg">
<div class="direct-chat-info clearfix">
<span ><?=$userName;?></span>
<span ><?=$messagedatetime;?></span>
</div>
<!-- /.direct-chat-info -->
<div class="direct-chat-text">
<?=$messageBody;?>
</div>
<!-- /.direct-chat-text -->
</div>
<!-- /.direct-chat-msg -->
<?php }else{?>
<!-- Message to the right -->
<div class="direct-chat-msg right">
<div class="direct-chat-info clearfix">
<span ><?=$userName;?></span>
<span ><?=$messagedatetime;?></span>
</div>
<!-- /.direct-chat-info -->
<div class="direct-chat-text">
<?=$messageBody;?>
</div>
<!-- /.direct-chat-text -->
</div>
<!-- /.direct-chat-msg -->
<?php }?>
<?php
endforeach;
}
the simple version of the view and the div i want to insert data in it :
<div id="chathistory"></div>
Please note that the models are written correctly(i did test them), and the call is written correctly because whenever i remove the foreach loop and add this to my controller :
echo json_encode($history);
and then console log the data in my ajax call i get the full chat history without a problem. so my guess is that there's something wrong with foreach loop and the html rendering !
ALSO : i did review some simple web app chat on github and they did write the controller with the same manner and it work perfectly fine for them. So what do you think is the problem please?
dataType : "json"
tells jQuery to expect JSON in the response, but you are returning HTML from the controller. So it will likely throw an error when it tries to parse your HTML as JSON. Either remove that line, or specify
dataType: "html"
instead

Ajax Tabs for Wordpress that loads and runs different shortcodes when user changes the tab

How does one execute a shortcode, which is placed in a tab, only when the user clicks on the Tab's Title. How do we do this for five tabs? MY objective is to reduce load time of me website. So, only that content which the user wants must load when he clicks on the tab.
I'm fairly certain the best way to do this is by utilizing Wordpress's admin-ajax.php. I've searched a great deal. And I've found most of the code (I think) to create the AJAX tabs. But, when I fire the code it doesn't show up. Rather the HTML shows us, the AJAX doesn't.
$(document).ready(function() {
$('.my_tabs a').click(function(e) {
e.preventDefault();
var tab_id = $('this').attr('id');
$.ajax({
type: "POST",
url: "wp-admin/admin-ajax.php",
dataType: 'html',
data: ({
action: 'my_tab_menu',
id: tab_id
}),
success: function(data) {
$('#my_tab' + tab_id).html(data);
},
error: function(data) {
alert("Error!");
return false;
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my_tabs">
Tab 1
Tab 2
Tab 3
Tab 4
Tab 5
</div>
<div class="my_section" id="my_tab1">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<div class="my_section" id="my_tab2">
<?php echo do_shortcode ('[shortcode-2]'); ?>
</div>
<div class="my_section" id="my_tab3">
<?php echo do_shortcode ('[shortcode-3]'); ?>
</div>
<div class="my_section" id="my_tab4">
<?php echo do_shortcode ('[shortcode-4]'); ?>
</div>
<div class="my_section" id="my_tab5">
<?php echo do_shortcode ('[shortcode-5]'); ?>
</div>
I add all the code directly into the page using a page-builder. So, I'm not using functions.php to add_action for this particular tab that I'm trying to implement.
I found all the code from a similar post on stackover:
Ajax tabs (wordpress)
They call template_parts into the tabs. Where as I want to execute a shortcode.
I'm what you'd call a coding bimbo. All help shall be much appreciated.
Thank you. And if you've managed to read till here, you deserve to have a pleasant day. :D
Okay, so you can't achieve it the way you have laid your template. As soon as you echo the shortcode and the browser renders the page, the shortcode contents must have printed. You need to create a custom-page-template.php, create a page and on that page you need to send the shortcode handler as soon as you click on the tab through GET or POST method using ajax.
In your Custom Template you receive the [shortcode-1]. An example code would be like you see below:
<?php
/*
Template Name: Shortcode Processor
*/
$current_shortcode = $_POST['shortcode_name'];
?>
<div id="shortcode-contents">
<?php echo do_shortcode($current_shortcode); ?>
</div>
Now you have the response in your Ajax Call. You can now inject the success html inside your desired tab.
Try
<button class="tabs" id="my-tabid1" data-target=".my-section1.box">Tab 1</button>
<button class="tabs" id="my-tabid2" data-target=".my-section2.box">Tab 2</button>
<button class="tabs" id="my-tabid3" data-target=".my-section3.box">Tab 3</button>
<div class="my_section1 box active" id="my-tab1">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<div class="my-section2 box" id="my-tab2">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<div class="my-section3 box" id="my_tab3">
<?php echo do_shortcode ('[shortcode-1]'); ?>
</div>
<style>
.box {
display: none;
}
.box.active {
display: block;
}
</style>
<script>
$('.tabs').on('click', function(){
var $target = $($(this).data('target'));
$target.siblings().removeClass('active');
$target.addClass('active');
});
</script>

Properly Reload div via Ajax - Script disappears

I have my header.php containing a button which triggers the sidebar menu to appear. Button and sidebar are visible only for logged in users. At the end of this block there is a little piece of code that adds the class "active" to my sidebar for making it visible. It's something like:
<div id="header">
<!-- if is_user_logged_in -->
<a id="menu-toggle" href="#" type="button">
<i class="sprite-t-toggle-side"></i>
</a>
<!-- sidebar menu-->
<div id="sidebar-wrapper"><!-- menu content --></div>
<script>
var $menu = $("#sidebar-wrapper");
$("#menu-toggle").on("click", function(e) {
e.preventDefault(),
$menu.toggleClass("active");
});
</script>
</div>
Now, I make my users login via AJAX and once they're logged I just refresh my header block for displaying button and sidebar. I use this line of code to do so in my AJAX success:
success: function(data){
if (data.loggedin == true){
$("#header").load(location.href + " #header");
}
}
Until here everything is fine, users are logged and button is displayed but when I click on it nothing happens. Sidebar won't appear and If I look at the code my little function, at the end of header, is missing. Otherwise, If I reload the whole page it works.
What's happening? What am I doing wrong?
Why reload the entire header. Why not just grab the logged in part of it
I think problem is that you are reloading the entire #header you need to just reload part of it.
$("#header").load(location.href + " #header"); <- this will replace all html in
the #header
<div id="header">
<div id="loadajax"></div> <!-- Put loaded ajax in here --->
<!-- if is_user_logged_in -->
<a id="menu-toggle" href="#" type="button">
<i class="sprite-t-toggle-side"></i>
</a>
<!-- sidebar menu-->
<div id="sidebar-wrapper"><!-- menu content --></div>
<script>
function runMenu() {
var $menu = $("#sidebar-wrapper");
$("#menu-toggle").on("click", function(e) {
e.preventDefault(),
$menu.toggleClass("active");
});
}
runMenu();
</script>
</div>
success: function(data){
if (data.loggedin == true){
$("#loadajax").load(location.href + " #header");
runMenu();
}
}

Updating span with jQuery, fetching it with PHP?

I have a jQuery-script that updates a span when the user clicks on different buttons. It updates and displays as desired.
But I want to fetch this "variable" with PHP and input it into a file.
When the document loads the value of the span is 0, and gets higher as the user click specific buttons. When I write the value of the span to my text file it is always 0. Help?
jQuery:
$(".button").click(function()
{
$(this).addClass("button-clicked");
$(this).siblings(".button").addClass("disabled");
$(this).siblings(".rett").addClass("rett-ved-feil");
$(this).unbind("click");
$(this).siblings(".button").unbind("click");
if($(this).hasClass("rett"))
{
rettVar++;
$("#antall-rett").html(rettVar);
$("#score").html(rettVar);
$(this).addClass("button-clicked-riktig");
}
});
PHP:
if (isset($_POST["submit"]))
{
$doc = new DOMDocument;
$doc->loadHTMLFile('index.php');
$node = $doc->getElementById('score');
$score = $node->nodeValue;
$fil = fopen("score.txt","a");
$loglinje = $_POST["navn"] . ": " . $score;
fwrite ($fil, $loglinje . "\n");
fclose($fil);
}
HTML:
<!doctype html>
<title>Huskampanje Quiz</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="mediaqueries.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<script src="js/jquery-1.11.2.js" type="text/javascript"></script>
<script src="js/myjs.js" type="text/javascript"></script>
<script src="js/scrollToggle.js" type="text/javascript"></script>
<section class="section" id="intro">
<div class="content">
<h1>Huskampanje quiz<br /><span class="handsome">Ta quizen her</span></h1>
</div>
<img src="img/pil.png" id="pil" />
</section>
<section class="section" id="håndverker-section">
<div class="content">
<p>
Når det gis et prisoverslag på en håndverkertejeneste kan endelig pris maks overstige..
</p>
<span class="button">5%</span>
<span class="button">10%</span>
<span class="button rett">15%</span>
<span class="button">20%</span>
<span class="steps">4/10</span>
</div>
</section>
<section class="section" id="naturskade-section">
<div class="content">
<p>
Ved påsketider har snøen ligget en stund på hyttetak, og oppnår høyere egenvekt enn når den er fersk. Om vi har et
hyttetak på 100 kvadratmeter og snødybden er 1 meter vil vekten av snøen være omlag..
</p>
<span class="button rett">30 tonn</span>
<span class="button">10 tonn</span>
<span class="button">5 tonn</span>
<span class="button">20 tonn</span>
<span class="steps">10/10</span>
</div>
</section>
<ul id="sticky">
<li id="header-sticky">Antall rett</li>
<li id="antall-rett">0</li>
</ul>
<section id="resultat">
<div class="content" id="resultat-content">
<div class="score">
<span id="score">0</span>
<form action="index.php" method="post">
<input type="text" name="navn">
<input type="submit" name="submit">
</form>
<?php
if (isset($_POST["submit"]))
{
$doc = new DOMDocument;
$doc->loadHTMLFile('index.php');
$node = $doc->getElementById('score');
$score = $node->nodeValue;
$fil = fopen("score.txt","a");
$loglinje = $_POST["navn"] . ": " . $score;
fwrite ($fil, $loglinje . "\n");
fclose($fil);
}
?>
</div>
</div>
</section>
As they told you, Javascript is client side while PHP is server side.
This means that what in client side happends, stays there and server doesn't care at all. If you want to update your file with the value, you got two ways to do it.
1.AJAX, send the value async to a php file and write the value desired into your file/database...
2.Make a form and retrieve the data and save it where you want. For this, make hidden inputs for example that will increment with every click.
Edit: for number 2, if you have multiple pages, you can have an input hidden with name, for example: "right_answers"
<form>
...
<!-- first page -->
<input type="hidden" name="right_answers" value="0">
...
</form>
Then in the next page, at the start, check if the answer is correct:
<?php
if($_POST['question'] == "answer") {
$goodAnswer = $_POST['right_answers']+1;
}
else {
$goodAnswer = $_POST['right_answer'];
}
?>
<form>
...
<input type="hidden" name="right_answers" value="<?php echo $goodAnswers; ?>">
...
</form>
This way you will always know the correct answers the user made. It's just an idea, sure there are better ways.
Your PHP script (file) will run on your server. The user, who has opened your webpage somewhere in the world, can't and never should see or alter your server-side files, like your PHPs. Every user who opens your webpage sees the same PHP, so if 5 users are browsing your page, they are all see the content that index.php has generated for them. The output of your PHP file (a HTML code) will be in their browsers (in the users computer's memory), and you can modify it with jQuery. It will always remain in the memory of the users' computer. So if you want to save something a user typed, you have to send it back to your server and here a PHP can catch it and save it for you. But it's not a good idea to save it to a file, since if 5 users sending back data, you should save 5 separate files for them (and you have to identify all users). But the basics are here:
You have to make a PHP file that can catch your input, save it as ajax.php:
<?php
$fil = fopen("score.txt","a");
$loglinje = "score:".$score;
fwrite ($fil, $loglinje . "\n");
fclose($fil);
?>
Then you have to send the data back to the server, so your jQuery code should something like that:
<script>
$(".button").click(function()
{
$(this).addClass("button-clicked");
$(this).siblings(".button").addClass("disabled");
$(this).siblings(".rett").addClass("rett-ved-feil");
$(this).unbind("click");
$(this).siblings(".button").unbind("click");
if($(this).hasClass("rett"))
{
rettVar++;
$.ajax({
url: '/ajax.php',
type: 'post',
dataType: 'json',
data: {
score: rettVar
}
})
.always(function() {
})
.fail(function() {
alert('There is an error occured.');
})
.done(function(result) {
$("#antall-rett").html(rettVar);
$("#score").html(rettVar);
$(this).addClass("button-clicked-riktig");
});
}
});
</script>
So this way the jQuery send back the score to the server, which is save it to you.
I hope it helps, but please consider, this code is only an example. I DO NOT recommend it to use in real-world application, since it has some security backdraws and maybe you should save the values to a database rather than a text file.

Displaying jQuery checkbox selection

This web page is currently displaying data from an "all" category from an rss feed once the page is loaded. My question is there are several categories which I would like the user to select and display. There are a total of 10 categories, and each correspond to a separate rss feed. Can anyone explain how I handle this event? Also, if one of the categories is selected, will it automatically override the current data being displayed? I will elaborate any unclear parts if needed. Thank you!
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/mobile/1.3.0/jquery.mobile-1.3.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$.ajax({
type: 'GET',
url: '/example',
dataType: 'xml',
success: function (xml) {
$(xml).find("item").each(function () {
var title = $(this).find("title").text();
var description = $(this).find("description").text();
var linkUrl = $(this).find("link").text();
//var link = "<a href='" + linkUrl + "' target='_blank'>Read More<a>";
var displaytitle = "<a href='" + linkUrl + "' target='_blank'>" + title + "</a>"
$('#feedContainer').append('<h3>'+displaytitle+'</h3><p>'+description+'</p>');
});
}
});
});
</script>
</head>
<body>
<div data-role="page" id="page">
<!-- /field panel -->
<div data-role="panel" id="fieldpanel" data-position="left" data-display="push">
<ul data-role="listview" data-inset="true" data-filter="false">
<fieldset data-role="controlgroup">
<legend>Categories</legend>
<input type="checkbox" name="checkbox-bio" id="checkbox-bio">
<label for="checkbox-bio">Bioengineering</label>
<input type="checkbox" name="checkbox-com" id="checkbox-com">
<label for="checkbox-com">Communications</label>
<input type="checkbox" name="checkbox-eleP" id="checkbox-eleP">
<label for="checkbox-eleP">Electrical/Power</label>
<input type="checkbox" name="checkbox-eleD" id="checkbox-eleD">
<label for="checkbox-eleD">Electronics/Design</label>
<input type="checkbox" name="checkbox-nano" id="checkbox-nano">
<label for="checkbox-nano">NanoEngineering</label>
<input type="checkbox" name="checkbox-opt" id="checkbox-opt">
<label for="checkbox-opt">Optics/Display</label>
<input type="checkbox" name="checkbox-semi" id="checkbox-semi">
<label for="checkbox-semi">Semiconductors</label>
</fieldset>
</ul>
</div><!-- /field panel -->
<!-- /settings panel -->
<div data-role="panel" id="settingspanel" data-position="right" data-display="push">
<ul data-role="listview" data-inset="true" data-filter="false">
<li>Join IEEE</li>
<li> subscription services</li>
</ul>
</div><!-- /settings panel -->
<div data-role="header" data-theme="b">
Menu
Settings
<h1>MOBILE</h1>
</div>
<div data-role="content">
<div id="feedContainer"></div>
<h3></h3>
<p></p>
</div>
<div data-role="footer">
<h4>Advertisements</h4>
</div>
</div>
</body>
</html>
I will assume you want to get the basic information about this code!
Ok, the first thing to handle is the type of the data to be shown.
<input type="checkbox" id="1" />
<input type="checkbox" id="2" />
Lets start with 2 instead of 10! The jQuery code for this would be easy to understand.
$('input[type=checkbox]').click(function () { // click on checkbox
var val = $(this).attr('id'); // get its id as value
if(val == '2') {
$('someelement).html('2 was selected');
$('#1').prop('checked', false); // unselect the other one
}
}
So, this is the basic code which will execute when a click event occurs on a checkbox. Now in your code you'll be using something like ajax then add the ajax request code before the .html() thing and write the response there.
To update the content being displayed you will be needed to use only one element as the basic clipboard for your app. Why? Because everytime you will get the data, you will be needed to replace the current content with that one and this way you will get only the current data; the selected data.
Lets try one checkbox from your code:
<input type="checkbox" name="checkbox-bio" id="checkbox-bio">
<label for="checkbox-bio">Bioengineering</label>
<input type="checkbox" name="checkbox-com" id="checkbox-com">
<label for="checkbox-com">Communications</label>
Now lets handle the jQuery
$('input[type="checkbox"]').click(function () {
// and all others will be here just as they are.. to check the id
// your ajax request is perfect, just copy paste that here..:)
});
But just need to make a change there, instead of sending the same request try to add one more thing there,
$.ajax({
// url and datatype here,
data: value
// success function goes here
});
Note that the value was the variable that we took from the checkbox. Which will be sent with the request so that you can process only the necessary part of the RSS and leave all other, just like an if else block.
Here is a working fiddle for this http://jsfiddle.net/afzaal_ahmad_zeeshan/KU9JT/.
But I am sorry, I didnot include the if else block to make the code work as it was meant to be. But you'll understand how to manipulate this.

Categories

Resources