I have a form where users can save activity of the day, with date and time.(index.php). I have build a jquery that opens a dialog popup window on page load...I want to include this code in my second php page. This page is called add.php. the user go there when he press a submit button in page index.php. When he press the submit button, to add an activity and exist an activity in that time and date I want to show a popup. But how can I include the popup below in the add.php.
My code is below
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/jquery-ui.js" type="text/javascript"></script>
<link href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.9/themes/start/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(function () {
$("#dialog").dialog({
title: "jQuery Dialog Popup",
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
});
</script>
<div id="dialog" style="display: none">
You have an activity on this time
</div>
And this is add.php
<?php
$con = mysql_connect('127.0.0.1','root','');
if (!$con)
{
die('<div class="content">Lidhja me databazen nuk mund te kryhet</div>' .mysql_error(). ' </body></html>');
}
if(!mysql_select_db("Axhenda",$con))
die('<div class="content">Nuk mund te hapet databaza Axhenda</div>'.mysql_error(). '</body></html>');
$Data=$_POST['date'];
$Ora=$_POST['time'];
$Emri=$_POST['emritakimit'];
$Pershkrimi=$_POST['pershkrimi'];
session_start();
if (!isset($_SESSION['user_id'])){
header('location:index.php');
}
//variabli SESSION per te ruajtur ID e perdoruesit
$perdoruesi=$_SESSION['user_id'];
$selekto=mysql_query("SELECT * FROM aktiviteti WHERE Data='$Data' and Ora='$Ora'");
$nr_rreshtave=mysql_num_rows($selekto);
if ($nr_rreshtave>0)
{
//here I want to include the function above
header('locationindex.php');}
else
{
$query ="INSERT into aktiviteti VALUES('', '$perdoruesi', '$Emri', '$Pershkrimi' ,'$Data','$Ora')";
$result=mysql_query($query,$con);
if($result)
{ header('location:index.php?error-akt1=1');}
else
{ header('location:index.php?error-akt2=1');}}
mysql_close($con);
?>
please help me...Thanks in advance
You actually want the pop up to show up only if there is an error, in which case add.php redirects to an URL with error-akt1=1 or error-akt2=2 as parameter. If you added the pop up to add.php, it would break the redirects. Therefore, you need to do it on index.php instead, but ONLY if the parameters are loaded.
To make the parameters available, to you, use the code provided by BrunoLM in this post: How can I get query string values in JavaScript?
(or any other code in that post, but BrunoLM provided one in jQuery, instead of pure Javascript). I'm copying the main part here:
(function($) {
$.QueryString = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&')) })(jQuery);
Get the querystrying by putting:
$.QueryString["param-name"]
And once you have the parameter, just use an if statement around the loading of your alert, like so:
$(function () {
var error-akt1 = $.QueryString["error-akt1"];
if (error-akt1 == 1) {
$("#dialog").dialog({
title: "jQuery Dialog Popup",
buttons: {
Close: function () {
$(this).dialog('close');
}
}
});
}
});
Repeat for error-akt2 or, even better, use error-akt=1 or error-akt=2 to send different erro r messages in the same parameter and querystring variable.
Related
I'm using jQuery, AJAX and PHP to validate most of the forms on my website. The actual input validation is done via PHP (I thought this would be best to prevent users from bypassing validation using the browser source code inspector to edit scripts), but I use jQuery and AJAX to load errors into an error message div below the form's submit button.
All of this works fine, but when a form is successfully submitted I'd like to call header('Location: foo.php') to send my user back to a certain page. However, since I'm using preventDefault(), my new page is being loaded into the error message div, making the browser window look like it has two pages on top of each other (the current url doesn't change either).
Is there a fix to this? I thought I might be able to unbind the event in the PHP file by including a script after the PHP code is done, but I was not successful.
jQuery:
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
var url = window.location.href.toString().split("=");
var id = url[1];
var title = $("#title").val();
var content = $("#content").val();
var submit = $("#submit").val();
//this is where the PHP is loading the new page, along with error messages
$(".form-message").load("/php/_create.thread.php", {
title: title,
content: content,
id: id,
submit: submit
});
});
});
End of PHP file:
<?php
//if successful, exit the script and go to a new page
$submissionSuccessful = true;
exit(header('Location: /index.php'));
?>
<reference path="/javascript/jquery-3.3.1.min.js"></reference>
<script type="text/javascript">
var submissionSuccessful = "<?php echo $submissionSuccessful; ?>";
if (submissionSuccessful)
{
$("#title, #content").css(
{
"border": "2px solid #24367e"
}
);
$("#title, #content").val("");
}
</script>
The approach I talk about is similar to this
$(document).ready(function () {
$("form").submit(function(event) {
event.preventDefault();
var url = window.location.href.toString().split("=");
var id = url[1];
var title = $("#title").val();
var content = $("#content").val();
var submit = $("#submit").val();
// AJAX POST request to PHP
$.post("/php/_create.thread.php", {
title: title,
content: content,
id: id,
submit: submit
}).done(function (response) {
// response is a JSON document
if (response.error) {
// Here you basically modify the UI to show errors
$(".form-message").text(response.error)
} else {
// Here you basically modify the UI to show success
$("#title, #content").css({ "border": "2px solid #24367e" });
$("#title, #content").val("");
location.href = '/index.php' // REDIRECT!
}
});
});
});
And in the server end
<?php
if ($someSuccessCondition) {
$response = ['success' => true];
} else {
$response = ['error' => 'The Error Message'];
}
echo json_encode($response);
exit();
I'm building a photography portfolio. Some of my images have nudity, so I want to hide those by default until the user clicks a "Toggle Worksafe Mode" button.
I can do it with a standard form post (and sessions), but that causes "confirm form resubmission" errors when the user backs or reloads. I'm trying to figure out an AJAX post instead to avoid that.
UPDATE: This is the working code. Please note that this does NOT work with the "slim" jQuery distro; that's one of the main reasons I was having trouble.
Image Index Page:
<?php
session_start();
if (!isset($_SESSION['Worksafe_Mode'] {
$_SESSION['Worksafe_Mode'] = 1;
}
?>
<!-- other page content -->
<script src="scripts/jquery-3.2.1.min.js"></script>
<!-- other page content -->
<button type="button" id="Worksafe_Button" name="Worksafe_Button">
Toggle Worksafe Mode
</button>
<script>
$('#Worksafe_Button').click(function() {
$.post("worksafe_mode_toggle.php")
.done(function(data) {
window.location.href = window.location.href;
});
});
</script>
<!-- other page content -->
<?php
$Connection = Connect();
$query = mysqli_query($Connection, 'SELECT uri, name, nsfw FROM images ORDER BY uri');
while($row = mysqli_fetch_assoc($image)) {
if ($_SESSION['Worksafe_Mode'] == 1 && $row['nsfw'] == 1) {
echo 'If you are over 18, toggle Worksafe Mode to view this image';
}
else {
echo '<img alt="'.$row['title'].'" src="../'.$row['uri'].'/s.jpg" srcset="../'.$row['uri'].'/m.jpg 2x">';
}
}
?>
worksafe_mode_script:
session_start();
if (isset($_SESSION['Worksafe_Mode'])) {
if ($_SESSION['Worksafe_Mode'] == 1) {
$_SESSION['Worksafe_Mode'] = 0;
}
else {
$_SESSION['Worksafe_Mode'] = 1;
}
}
I think ajax is a good approach in your case.
I might do something like display a page of SFW images as the default, along with the toggle button.
When they click the button it triggers an ajax request to the back-end that sets/un-sets the session value in toggleWorksafe.php. Finally it triggers a page refresh.
During the page refresh the PHP code checks whether the session variable is set and shows either the filtered or unfiltered set of images, and changes the button's text to match.
To implement:
Include jQuery in the <head> section (jQuery simplifies the ajax call):
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
</head>
<body>
<?php
session_start();
if (!isset($_SESSION['Worksafe_Mode'])) {
$_SESSION['Worksafe_Mode'] = 'yes';
}
?>
<button id="workSafe" type="button" name="Worksafe_Toggle_Button">
<?php
if ($_SESSION['Worksafe_Mode'] == 'no') {
echo 'Hide NSFW images';
}
else {
echo 'Include NSFW images';
}
?>
</button>
<!-- display safe images by default -->
<?php
if ($_SESSION['Worksafe_Mode'] == 'no') {
echo '<br/><br/>Showing NSFW images';
}
else {
echo '<br/><br/>Showing safe images only';
}
?>
<!-- any other page content here -->
<script>
$('#workSafe').click(function() {
// ajax request to page toggling session value
$.post("/toggleWorksafe.php")
.done(function(data) {
window.location.href = window.location.href; // trigger a page refresh
});
});
</script>
</body>
</html>
toggleWorksafe.php:
<?php
session_start();
if (isset($_SESSION['Worksafe_Mode'])) {
if ($_SESSION['Worksafe_Mode'] == 'yes') {
$_SESSION['Worksafe_Mode'] = 'no';
}
else {
$_SESSION['Worksafe_Mode'] = 'yes';
}
}
else {
$_SESSION['Worksafe_Mode'] = 'yes';
}
?>
there are a couple of ways to do this and it related to how you hide or load you images.
1. simple method
if you don't care about the user's age, and just need to toggle, then you can do it with just a js variable, a cookie, and two version of link. with this, you don't hide images, but loads them. the filtering is done in the server, where you can use database query or a simple folder separation. for example:
var nsfw = read_cookie('nsfw', false); // not an actual js function, search for how to read cookie in js --- read cookie value, default to false
function loadImage(nsfw){
if (nsfw){
$.get('nsfw-image-list-url', function(resp){
// the url should return a json with list of image urls
var list = resp; // jQuery automatically parse json with the right MIME
list.forEach(function(val){
// insert image to page
$('#container').append('<img src="' + val + '/>');
});
});
} else {
$.get('sfw-image-list-url', function(resp){
// the url should return a json with list of image urls
var list = resp; // jQuery automatically parse json with the right MIME
list.forEach(function(val){
// insert image to page
$('#container').append('<img src="' + val + '/>');
});
});
}
}
and in you button click event:
nsfw = !nsfw;
// clear the image first if needed
$('#container').empty();
loadImage(nsfw);
2. another simple method, but not as simple as the #1
you can also do it with only one link that returns a list of images with the type of it, such as nsfw or other things.
note: this method still uses cookie
for example the returned list is like this:
[
{"url": "some-image-1.jpg", "nsfw": "true"},
{"url": "some-image-2.jpg", "nsfw": "false"},
{"url": "some-image-3.jpg", "nsfw": "true"},
{"url": "some-image-4.jpg", "nsfw": "false"},
{"url": "some-image-5.jpg", "nsfw": "false"},
{"url": "some-image-6.jpg", "nsfw": "true"}
]
then you just render it when the conditions are met.
function renderImage(nsfw){
$.get('image-list-url', function(resp){
list.forEach(function(val, key){
if (nsfw || !val.nsfw){
$('#container').append('<img src="' + val.url + '/>');
}
});
});
}
and many other methods that are too long to explain, such as using Angular, React, or Vue
still uses cookie for between reloads or backs, and does not regard user's age.
as for the session based approach, you only need that if you need to verify your users age
that is if you have a membership functionality with DOB (date of birth) data in your site, if so, you can use #KScandrett 's answer
Confirm form resubmission happens because you do not perform a redirect after a successful form submission.
Take a look at this wiki page to see how to do it right. https://en.wikipedia.org/wiki/Post/Redirect/Get
I'm working on joomla environment. I would like to run small php script by click on button event from JQuery reason I would like to use JQuery is I cannot modified existing component. Current component adding some values on Database from webpage. I would like to do same thing but from back-end with out notify any thing from another PHP file. I was trying something as code but it's not working.
Is there any other way.?
What is wrong in code.?
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#submitButton').click(function(){
$.post("/automate/UpdateMySql.php");
});
}
</script>
You were missing a dot and bracket(with semi-colon) at the end. As per the comments if you want to just Update Date And Time. You can post any random variable to UpdateMySql.php and then Create Date And Time there.
<script type="text/javascript">
var clicked = 0;
jQuery(document).ready(function(){
jQuery('#submitButton').click(function(){
clicked = 1;
jQuery.post("/automate/UpdateMySql.php" , { click : clicked });
});
});
</script>
In UpdateMySql.php write.
$clicked = $_POST['click'];
if(isset($clicked) && !empty($clicked)) {
$today = date("Y-m-d H:i:s");
$query = "UPDATE table_name date_time=".$today." WHERE anything = 'anything'";
if($query) {
return 'Updated';
} else {
return 'Something Went Wrong';
}
}
Please use:
$(document).ready(function() {
$('#submitButton').click(function(e) {
$.ajax({ type:'POST',
url:'/automate/UpdateMySql.php'
data:{name:'demo',id:"1"},
sucess:function(xhr) {
alert('table updated');
}
});
});
});
if some one need complete answer in future.
<script type="text/javascript">
var clicked = 0;
jQuery(document).ready(function(){
jQuery('#submitButton').click(function(){
clicked = 1;
jQuery.post("/automate/UpdateMySql.php" , { click : clicked });
});
});
</script>
This is the script which will send information of textboxes to another page where the information will be inserted into the mysql database.
<script type="text/javascript">
// <![CDATA[
$(document).ready(function(){
// click to submit an event
$('#Create').click(function(){
var a = $("#EventInput").val();
if(a != "What are you planning?")
{
$.post("concorunt.php?val=1&id=<?php echo $id?>&"+$("#EventForm").serialize(), {
}, function(response){
$('#ShowEvents').prepend($(response).fadeIn('slow'));
clearForm();
});
}
else
{
alert("Enter event name.");
$("#EventInput").focus();
}
});
</script>
But nothing is happening.
You did not close your documentready function. Try this:
$(document).ready(function(){
// <![CDATA[ --> Either remove this or close this.
.....
.....
}); //Missing those braces in your code
I am using jQmodal plugin , to show pop up window, welcome to site.
But the issue is every time page refresh window pop-up.
Here is my code http://jsbin.com/atoqe5/3/edit
I think it can be done using Cookies, but not much Idea how to use that. :(
Thanks!
You could set a cookie with JavaScript and set it to true when it's opened for the first time.
These are just helper functions for setting and getting cookie values, more info about setting and getting cookie values.
function setCookie(name, value, daysToLive) {
var expirationDate = new Date();
expirationDate.setDate(expirationDate.getDate() + daysToLive);
document.cookie = name + '=' + escape(value) + ((daysToLive == null) ? '' : '; expires=' + expirationDate.toUTCString());
}
function getCookie(name) {
var cookies=document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
if (cookies[i].substr(0, cookies[i].indexOf('=')).replace(/^\s+|\s+$/g, '') == name) {
return unescape(cookies[i].substr(cookies[i].indexOf('=') + 1));
}
}
}
Prevent the modal from opening if the value is set:
$(function() {
if (!getCookie('modalOpened')) {
// Put your code to open the model here...
// Set value to true to prevent the modal from opening again
setCookie('modalOpened', true);
}
});
If you are using php you can do something like this: put in each page as first line
<?php session_start(); ?>
and in you homepage
<?php session_start();
if( $_SESSION['visited'] ){
//don't show the modal box
} else {
$_SESSION['visited'] = true;
//show modal box;
}
?>
This code check if you already visited the page in this session, if you don't shows the modal box, then set the global session variable $_SESSION['visited'] to true, so you can be sure the user have already visited the page :)
hope this helped