I currently have a like button that now works with Ajax. With one minor flaw. I click like on a post and it updates 1 like and shows in the page. But if I refresh the page it vanishes out of sight. The like is still in the database it just doesn't show in the page. Now someone told me to use
$(document).ready(function () {}
to do this on page load, but I have no clue how to use it to make my likes show on page refresh.
Or maybe I have to make a new call on page refresh to get all the likes for each post.
This is what I have so far
function likestatus(postid,contextid){
var obj = document.getElementById(contextid);
$.post("../include/like_do.php", { streamitem_id: postid},function(data){
//see the parameter data in this function. Data contains whatever that you echo in your php file.
$("#likesprint"+postid).html(data+"Likes");
});
}
Like_do.php
<?php
session_start();
require"load.php";
if(isset($_POST['streamitem_id'])){
$check = user_core::check_liked($_SESSION['id'],$_POST['streamitem_id'],1);
user_core::do_like($_SESSION['id'],$_POST['streamitem_id'],1);
echo $check; // as your user_core::check_liked() function returns number of likes.
}else{
echo "<script>alert('Error liking post');</script>";
}
?>
Related
I have written a piece of code which triggers a slideToggle() after a 2 second wait on a page.
Now, this is not something I want to show to visitors who have the intention to immediately leave (bounce) from my site.
I determined that the best time to show the div is when a visitor has landed on my page, and navigated to another page.
So right now my code is this:
<script>
jQuery(document).ready(function(){
setTimeout(
function()
{
jQuery(".slide-div").slideToggle();
}, 2000);
});
</script>
Is there a way to listen to a visitor's behavior and trigger a function (slideToggle() in this case) when this visitor has navigated to another page?
This way, I can show my div to people who have navigated the website.
For future reference, I ended up using PHP to solve this problem.
Explanation: Each time a person navigates (or refreshes) the page, +1 is added to the $_SESSION['count'] variable. Then in footer.php I wrote a simple if else statement to determine wether my function should appear or not. wonderplugin is just a plug-in that checks if a visitor is on mobile or not.
Header.php:
<?php
session_start();
if (!isset($_SESSION['count']))
$_SESSION['count'] = 1;
else
$_SESSION['count']++;
?>
Footer.php:
<?php
$count = $_SESSION['count'];
if ($count == 1) {
//
}
elseif ($count >= 1 && $count <= 100) {
if (wonderplugin_is_device('iPhone,iPod,Android'))
echo get_function_mobile();
else
echo get_function();
}
?>
If you want a count of how many pages your users have been on you would need to hold onto a variable somewhere that is not on your page that you could increment with a page count. That may be in local storage, a cookie, or in your server side code.
Another thing you could do is add query strings to links on your pages if all you want to know is that someone has navigated from another page within your site. Then, check the query string on the page load and show your div if they are coming from an internal page.
You can use Javascript and localStorage to remember the user's action :
jQuery(document).ready(function()
{
var previousAction = localStorage.getItem('user-action');
if(previousAction)
{
setTimeout(function()
{
jQuery('.slide-div').slideToggle();
}, 2000);
}
else
{
localStorage.setItem('user-action', 'new-action-spotted');
}
});
I'm having some trouble right now with wordpress and the functions.php file. For reference I'm using ninja forms and pop-up maker.
I have a bunch of buttons. When you click one button, it opens a modal where the user will enter in their contact information. That information is then stored and a success message is displayed with a link to the resource the user requested. Since I don't want the user to have to keep filling out information for every resource, I have a cookie stored. To make up for this, I am storing the user's information inside the $_SESSION variable, since I still want to know when the user clicked a resource link.
Because I am using ninja forms I am hooking into the ninja_forms_after_submission function and storing the session in there.
function register_session(){
if(!session_id()){
session_start();
}
}
add_action('init','register_session',1);
add_action('ninja_forms_after_submission','test');
function test($form_data){
// assume ive processed some data here
// and $form_data['name'] / $form_data['email'] is valid
register_session();
$_SESSION['name'] = $form_data['name'];
$_SESSION['email'] = $form_data['email'];
}
Cool. This works and I can echo out $_SESSION and see valid data. Now, since the user is clicking links, and I want to still capture the session, I am doing the following (underneath the code above, still in functions.php):
add_action('wp_footer','save_session',500);
function save_session(){
?>
<script type="text/javascript">
(function($,document,undefined){
$(document).on('click','.pum-trigger',function(){
var post = {};
post['name'] = "<?php echo $_SESSION['name']; ?>";
post['email'] = "<?php echo $_SESSION['email']; ?>";
post['action'] = 'get_resource';
$.post(ajaxurl,post,function(response){
});
});
}(jQuery,document))
</script>
<?php
}
add_action('wp_ajax_get_resource','get_resource');
add_action('wp_ajax_nopriv_get_resource','get_resource');
function get_resource(){
echo json_encode($_POST);
}
This code does work and triggers every time a user clicks on a resource link after the first form has been filled out.
The problem is, $_SESSION['name'] and $_SESSION['email'] do not load into the javascript function until after the user refreshes the page.
So if I enter the information Name: Test, Email: test#test.com into the first form that pops up, and I verify that $_SESSION['name'] and $_SESSION['email'] were saved (by printing it out in the ninja forms hook), then I click another link, the line: echo json_encode($_POST); only shows: {"name" : "", "email" : ""}
After refreshing the page, and clicking a link, echo json_encode($_POST); now shows: {"name" : "test", "email" : "test#test.com"}
The problem with this is that the user probably won't refresh the page on their own. Is there some way to have the value that is saved from the test() function appear in the save_session() function without reloading the page? I've tried global variables, but that doesn't work either.
Any advice on how to set this up would be greatly appreciated.
How can I refresh the page automatically after the user is done uploading profile picture?
Well the picture gets updated once the user refreshes the page but I want to force refresh the page on its own.
I am uploading the file and updating my database like this:
$query="UPDATE users set image='".$username_db."_n.gif' where user_name='$username_db'";
mysqli_query($con,$query);
And after this I want a refresh code.
I have tried several ways to do so:
echo "<script type='text/javascript'>$('.display_picture_image').attr('src', '".$src."?".time()."');<scipt>";
exit;
where .display_picture_image is the image tag where I want to display the picture.
echo "<meta http-equiv='refresh' content='0'>"
exit;
Then
header("Refresh:0");
exit();
Then
header("Location:".$_SERVER[REQUEST_URI]);
exit();
Then
header("Location:page_name.php");
exit();
Then
echo "<script type='text/javascript'>location.reload();</script>";
But nothing is working. What am I doing wrong?
I have a page: index.php. It contains the form which is self referencing form.
if(isset($_POST['submit'])
include 'upload.php';
Once the picture is submitted, the code from from
upload.php
is executed. The picture is then uploaded and then
echo '<script type="text/javascript">$(window).on("load",function(){window.top.window.showcrop("'.$target_file.'","'.$username_db.'","'.$imageFileType.'");});</script>';
calls the function showcrop. in a js file which is linked in the header.
Then after the cropping area is selected and submitted this is executed:
function crop_photo() {
var x_ = $('#x').val();
var y_ = $('#y').val();
var w_ = $('#w').val();
var h_ = $('#h').val();
var photo_url_ = $('#photo_url').val();
var username_ = $('#username').val();
var fileTypeImage_ = $('#imageFileType').val();
// hide thecrop popup
$('#popup_crop').hide();
// display the loading texte
// crop photo with a php file using ajax call
$.ajax({
url: 'crop_photo.php',
type: 'POST',
data: {x:x_, y:y_, w:w_, h:h_, photo_url:photo_url_, username:username_, fileTypeImage:fileTypeImage_, targ_w:TARGET_W, targ_h:TARGET_H},
success:function(data){
// display the croped photo
}
});
}
// updateCoords : updates hidden input values after every crop selection
function updateCoords(c) {
$('#x').val(c.x);
$('#y').val(c.y);
$('#w').val(c.w);
$('#h').val(c.h);
}
Then the crop.php is executed which uploads the cropped picture and updates the database. In the end, the refresh code is written but doesn't work.
SERVER SIDE :
Note : Put below code after uploaded your file and updated your database :
header("Refresh: 300;url='REDIRECTION URI'");
The browser will redirect after 300 seconds. It can be disabled in configuration of the browser though, but it's not commonly disabled.
CLIENT SIDE :
location.reload();
Okay so I figured out the answer on my own. In my crop_photo.php file I have,
$.ajax({
url: 'crop_photo.php',
type: 'POST',
data: {x:x_, y:y_, w:w_, h:h_, photo_url:photo_url_, username:username_, fileTypeImage:fileTypeImage_, targ_w:TARGET_W, targ_h:TARGET_H},
success:function(data){
// display the croped photo
}
});
Well in the above code, i mentioned nothing within
success:function(data){
//display the cropped photo
}
Though that is where php is gonna echo stuffs.
So I edited that as,
success:function(data){
//display the cropped photo
$('#image_div').html(data);
}
By this whatever I echoed in php was put inside the division with id image_div.
Then I echoed
echo '<script>window.location='redirectbackurl.php'</script>';
and it redirected to redirectbackurl.php which redirected back to the previous link.
Code of my redirectbackurl.php
<?php
header("Location:".$_SERVER['HTTP_REFERER']);
exit();
?>
Now i understand, i could simply use location.reload(), but due to form re submission issues, i did this.
I have a page where a user creates an item to auction it. If he submits the item creation form, the browser automatically redirects him to the newly created page via the following line of php code:
header('Location: item.php?itemid='.$itemid);
I would like to display a notification right after the item creation (on the newly created page) saying that the item has been created. This is the (working) code I use to call the notifications:
<script type="text/javascript">
$(function(){
$container = $("#container").notify();
notifyItemCreation();
});
</script>
EDIT: I think people are misunderstanding the problem.
So my sellitem.php page contains a form to sell an item, if this is submitted it gets send to createitem.php, this is where I do the validation checks.
If everything is okay this is where I redirect to the newly created item.php?item='$itemid' page. I want on this (item.php?item='$itemid') page the notification to be displayed.
EDIT2: I do know how to create the item.php?itemid='$itemid' page, this gets done perfectly, it is the notification to appear that is the problem. I am using the notifications from http://www.erichynds.com/blog/a-jquery-ui-growl-ubuntu-notification-widget
Can the people who are downvoting also explain why they are.
You can use session variables. In the next request if a certain variable exists or indicates that the current item is new, you can echo the script tag and unset the variable.
You could just wrap the JS in a condition
<?php if(is_numeric($itemid)){ ?>
<script type="text/javascript">
$(function(){
$container = $("#container").notify();
notifyItemCreation();
});
</script>
<?php } ?>
You could use ISSET() as well
UPDATE: I resolved my issue by moving my form submitter script from the Header to the bottom of the jamesmsg.php page (the included one). This way the functions always get re-loaded and attached to the "new" form everytime the div is refreshed.
This is a follow-up to a previous question I had about getting only a div to refresh (and not the entire page) when submitting a form. I've stripped out all the unnecessary javascript and code to just focus on this problem but I'm still stumped.
When I click submit the first time, the data is posted and we're good. When I click submit the second time, the entire page refreshes, the URL now shows POSTed data.. the good news is the data IS inserted to the mysql db, I just need to get this form acting properly like it does for the first click (at least it appears to do so).
My main php file is james.php:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
</head>
<body>
<div id='mainpage'>
<div id='control'>CONTROL DIV 1 ... 2 ... 3</div>
<div id='statusupdates'><? include 'jamesmsg.php'; ?></div>
</div>
</body>
</html>
so you can see I have a "Control Div" which should never change and my statusupdates div which should always be updated with the submitted form data (and a subsequent pull from mysql to show the latest updates).
jamesmsg.php (mysql credentials xxx intentionally for this post):
<?
$xxx = new mysqli("xxx","xxx","xxx",xxx);
$MsgText = $_POST["MsgText"];
if ($MsgText != "") {
$query = "INSERT INTO Messages SET
MsgDate = NOW(),
MsgAuthor = 0,
MsgText = '" . mysqli_real_escape_string(xxx,$MsgText) . "'";
if (!xxx->query($query)) {
print "error! xxxx->error<BR>query = $query<BR>";
}
}
print "<form id=\"statusform\" action=\"james.php?L=1\">
<textarea name=MsgText rows=5 cols=40></textarea><BR>
<input type=submit value=Post id=uhsbutton>
</form>";
?>
<?
print "<BR><BR><pre>POST Variables:<BR>";
print_r ($_POST);
print_r ($_GET);
print "</pre>";
?>
<?
$query = "SELECT * FROM Messages ORDER BY MsgDate DESC LIMIT 5";
$msgq = $xxx->query($query);
if ($msgq->num_rows > 0) {
while ($r = $msgq->fetch_array()) {
print ".......<BR>";
print "msg ID: " . $r["ID"] . " - " . $r["MsgDate"] . " " . $r["MsgAuthor"] . "<BR>";
print $r["MsgText"] . "<BR>";
}
}
else {
print "no messages";
}
?>
<script>
/*************************************
* form submitter
**************************************/
$(document).ready(function() {
$("#statusform").submit(function(e) {
e.preventDefault();
var data=$(this).serialize();
var pUrl="jamesmsg.php";
submitFormSave(data, pUrl);
});
function submitFormSave(data, pUrl) {
$.ajax({
url: pUrl,
type: 'POST',
cache: false,
data: data,
success: function(response) {
$("#statusupdates").html(response);
}
}).success(function(){
});
}
});
</script>
You can see this in action by going to: demo
Viewing this in Chrome's console I get no errors at all.
The problem is with the success callback that you've set for your AJAX call:
success: function(response) {
$("#statusupdates").html(response);
}
This ends up overwriting the entire form and the original submit event handler you set up when the page first loaded is lost. Since there is no event handler present to prevent the default behaviour, the second button click causes the entire page to refresh.
So, what I would do is get your server response to return data in the form of JSON or XML (preferably JSON since it easily integrates with JavaScript).
Right now, your server response is returning HTML back. This is something you want to avoid. The server should serve you data and then on the client side you should dynamically generate your HTML via JavaScript to show data in a readable format.
I solved my issue by moving the javascript from the Header to appear at the bottom of the included page: jamesmsg.php.
I'm now able to post and have the appropriate div refresh without the entire page always refreshing.