I have a quick question about this fade out div. I use facebox, and after the submit, and it shows an error it'll show this:
http://puu.sh/1uPnF
however I want that to fade away, after they've caught that message. On my AJAX handler for the submit form, this is the PHP code:
<?php
require_once('....');
$form_name = $_GET['form_name'];
$form_comment = $_GET['form_comment'];
$date = date('Y-n-j');
$ip = $_SERVER['REMOTE_ADDR'];
if($form_name == '') {
echo("<div class='alert alert-error-x'>Don't forget to enter a name, as we need to identify who's commenting on this article!</div>");
} else if($form_comment == '') {
echo("<div class='alert alert-error-x'>Please do not leave the comment field blank, we want to know what you're saying!</div>");
} else {
mysql_query("INSERT INTO comment (id, articleid, name, comment, date, ip) VALUES (NULL,'{$_GET['id']}','{$form_name}','{$form_comment}','{$date}','{$ip}')");
// output comment
echo "<div class='alert alert-success-x'>Posted by <strong>$form_name</strong> on <strong>{$date}</strong>$form_comment</div>";
}
?>
This is where the output of what would be submitted, on the article.php:
<?php
$amount_get = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "'"); $comments = mysql_num_rows($amount_get);
$grab = mysql_query("SELECT * FROM comment WHERE articleid='" . mysql_real_escape_string($_GET['id']) . "'");
if (mysql_num_rows($grab)==0) {
echo "<div class='alert alert-note-x'>Sorry, it looks like their are no comments to be displayed, check back later!</div>";
}
while($row = mysql_fetch_array($grab)){
?>
<div id="new_comment"></div>
<div class="article-comment">
Posted by <b><?php echo $row['name'] ?></b> on <b><?php echo $row['date'] ?></b>
<br />
<?php echo $row['comment'] ?>
</div>
<?php } ?>
</div>
</body>
</html>
Now I tried adding the below code in the core.js file, which is located on my site at krissales.com
$(window).bind("load", function() {
$('#new_comment').fadeOut(4000);
});
However it did not work. If you want to test the demo, then check it out at: http://www.krissales.com/#/media/30.This-is-a-new-article-for-Testing!
What is it that I'm doing wrong, please?
Thanks!
If you're using AJAX, I suggest you use jquery's ajax method (http://api.jquery.com/jQuery.ajax/) to make the call to your PHP file.
Then, use the success callback function of that method to show the correct response.
Hiding the response can then simply be done by fading out the div (with a delay if you want that).
if ($('#new_comment').length > 0)
{
$('#new_comment').delay(4000).fadeOut();
}
You are now trying to fade out the message on window load, but since you're using AJAX, there is no page reload happening.
Hope this helps you!
Related
I want to make a call of this php logic inside a html div but when passing it as a function the logic breaks since it does not send an error message in case of entering the pass wrong and its confirmation at the time of performing the password change.
<?php
require 'funcs/conexion.php';
require 'funcs/funcs.php';
$user_id = $mysqli->real_escape_string($_POST['user_id']);
$token = $mysqli->real_escape_string($_POST['token']);
$password = $mysqli->real_escape_string($_POST['password']);
$con_password = $mysqli->real_escape_string($_POST['con_password']);
if(validaPassword($password, $con_password))
{
$pass_hash = hashPassword($password);
if(cambiaPassword($pass_hash, $user_id, $token))
{
echo "Contraseña Modificada <br> <a href='index_alumnos.php' >Iniciar Sesion</a>";
} else {
echo "Error al modificar contraseña";
}
} else {
echo "Las contraseñas no coinciden <br> <a href='index_alumnos.php' >contacta a Academia</a>";
}
?>
If the echo happens before your actual div is drawn, the echo goes... right where it happens. Which isn't within your div.
One way of getting around this would be to put your error message into a variable and then deliver this variable into your div (whether it be through a return value, if it's a call, or some other means.)
Here's a simple example to illustrate this:
<?php
if(1 === 2) {
//great, 1 is 2
} else {
//oh no, an error
$someErrorLine = '1 is not 2';
} ?>
<h1>Hi</h1>
<div><?= $someErrorLine ?></div>
You could also check if the variable exists, something like if(isset($someErrorLine)) {} and echo the div with it, or put the div within your variable.
I am using already this code:
<?php
// [...]
ELSE IF(isset($_GET['msg'])){
echo "<div id='noticePanel' class='panel panel-success'><div class='panel-heading'>
<h2 class='panel-title'>Good job!</h2></div>
<div class='panel-body'><h4>".addslashes(strip_tags(trim(#$_GET[msg])))."</h4></div></div>";
}
//[...]
?>
Which is called from other pages if some operation goes well:
if ($result){
header("Location:index.php?msg=DB updated succesfully");
exit;
}
BUT as you may imagine, it is not clean. Working, but not the best.
Can anybody tell me if I should move it to a POST request or if this code is "widely" used to exchange status messages between pages?
And, in case of the POST, can someone write down some code or redirect me to a page where this is explained well? I searched already of course, I found THIS from mozilla, THIS with jquery and in general searching "send post php header" on google.
But I just can't understand how to do it.
Thanks a lot guys!
Because you prefer to keep your code pure
i just suggest you to do not send the message in GET/POST
just send the status like
index.php?status=success
then check the status in result file
if(isset($_GET['status']) AND $_GET['status'] == success){
echo "bla bla";
}elseif(isset($_GET['status']) AND $_GET['status'] == fail){
echo "bla bla";
}else{
//do something
}
EDIT
If you have many messages, then you can create array
$message = [
'success' => 'success message here',
'fail' => 'failmessage here',
'notFound' => 'not found message'
];
$status = ( isset($_GET['status']) AND
isset($message[$_GET['status']]) )?$_GET['status']:'notFound';
echo $message[$status];
I think i'm going to go with this: PHP. How to pass variable and auto redirect to another PHP file
<?php
session_start();
$id = $user_profile['id'];
$_SESSION['id'] = $id;
header('Location: checkIfExsists.php');
?>
And on the checkIfExsists.php page, retrieve the variable so:
<?php
session_start();
$id = $_SESSION['id'];
?>
New code
session_start()
// [...]
ELSE IF(isset($_GET['msg'])){
echo "<div id='noticePanel' class='panel panel-success'><div class='panel-heading'>
<h2 class='panel-title'>Good job!</h2></div>
<div class='panel-body'><h4>".addslashes(strip_tags(trim(#$_SESSION['msg'])))."</h4></div></div>";
}
And..
session_start();
if ($result){
$_SESSION['msg'] = "DB updated!";
header("Location:index.php?msg");
exit;
}
My colleague and me are having a hard time trying to solve this problem. We have a special kind of webshop, because we have customers and sub-customers. If the person logged in is a sub-customer, we want to show some extra html on our page. This works, but if a sub-customer logs out, and a normal customer logs in, the extra html is still visible, but we don't understand how this is possible. The problem is also vice versa: if the first logged in is a normal user, then logs out, then a sub-customer logs in, the extra html is not visible.
1. loginck.php
//after the user types his e-mail end password, we check if its a normal user or a sub-user.
If normal user then => $_SESSION['multiklant'] = 0;
else sub-user then => $_SESSION['multiklant'] = 1;
else $_SESSION['multiklant'] = 0; //user not found
2. index.php
if ($_SESSION['multiklant'] == 1) {
$userid = $_SESSION['userid'];
echo "<div class='col-md-3'>";
echo "<label for='leveradres'>Leveradres*:</label><br/>";
echo "<select id='leveradres' class='form-control'>";
echo "<option value='0'>Selecteer...</option>";
$qry = "SELECT * FROM LEVERADRESSEN WHERE LA_EMAIL = '" . $_SESSION['klemail'] . "'";
$res = mysqli_query($link, $qry);
while ($row = mysqli_fetch_assoc($res)) {
echo "<option value='" . $row['LA_ID'] . "'>" . $row['LA_NAAM'] . "</option>";
}
echo "</select>";
echo "</div>";
}
3.1 logout click on index.php
$("#logout").click(function () {
var lgout = $.get("logout.php");
lgout.done(function (data) {
$(".show-2").trigger("click");
$("#logout").addClass("hidden");
});
});
3.2 logout.php
<?php
session_start();
$_SESSION = array();
session_unset();
session_destroy();
header("Location:index.php");
exit();
?>
As you can see, we used AJAX here, but even without the problem stays. If possible we would like to keep the AJAX, but if not it can be deleted. Also a combination, where the redirect is not in de php but in the javascript part.
Could this be a caching problem? Because if we reload our browser without cache, it al works.
We are searching the internet, including this site already for 6 hours...
Code tested in Chrome on MAC and Internet Explorer 11 on Windows, gives no difference.
Your logout does a header location with exit. In other words: is the $.get('logout.php') done?
Why do you do a redirect serverside? So full page and scripts will be reloaded! And you're waiting for 'done'. Do this:
remove the lines with header and exit from logout.php
After the session is destroyed, the page is ready and the .done callback will be executed.
Look at response header after logout and check "cache-control".
I think problem in cache.
YES!
After searching a long time and trying some of your suggestions (which we are grateful for, I upvoted the most useful ones) we found the solution.
It was after reading this it all came (more) clear. Index.php is our only page with content. So yes, we start a session there, but if we change the session variables afterwards via AJAX, index.php doesn't track those changes.
This is why we tried to refresh the page after logging out, so the sessions variables would be refreshed to. That didn't work. It was until we did also a refresh after logging in also, it al worked, although with some page refresh for the users.
So we put those blocks of code in separate php files and check when needed with AJAX
This is our solution:
1. When the user logs in:
$("#blockleveradressen").load("leveradressen.php");
var testmultiklant = $.get("testmultiklant.php");
testmultiklant.done(function (data){
if(data == 3){
$("#een").removeClass().addClass("col-md-3");
$("#twee").removeClass().addClass("col-md-3");
$("#drie").removeClass().addClass("col-md-3");
}else {
$("#een").removeClass().addClass("col-md-4");
$("#twee").removeClass().addClass("col-md-4");
$("#drie").removeClass().addClass("col-md-4");
}
});
2. leveradressen.php
include "include/session.php";
include "include/MyConnect.php";
if ($_SESSION['multiklant'] == 1) {
$userid = $_SESSION['userid'];
echo "<div class='col-md-3'>";
echo "<label for='leveradres'>Leveradres*:</label><br/>";
echo "<select id='leveradres' class='form-control'>";
echo "<option value='0'>Selecteer...</option>";
$qry = "SELECT * FROM LEVERADRESSEN WHERE LA_EMAIL = '" . $_SESSION['klemail'] . "'";
$res = mysqli_query($link, $qry);
while ($row = mysqli_fetch_assoc($res)) {
echo "<option value='" . $row['LA_ID'] . "'>" . $row['LA_NAAM'] . "</option>";
}
echo "</select>";
echo "</div>";
}
3. testmultiklant.php
include "include/session.php";
if ($_SESSION['multiklant'] == 1) {
echo 3;
} else
{
echo 4;
}
4. index.php
<div id="blockleveradressen">
</div>
<div id="een" class="col-md-4">
<label for="datepicker">Leveringsdatum*:</label><br/>
<input type="text" id="datepicker" readonly="readonly"/>
<input type="hidden" id="datepickerAlt" readonly="readonly" visible="false">
</div>
<div id="twee" class="col-md-4">
<label for="timepicker">Leveringstijdstip*:</label><br/>
<input type="text" id="timepicker" class="time"/>
</div>
<div id="drie" class="col-md-4">
<label for="betaalMethode">Betaalmethode*:</label><br/>
<select id="betaalMethode" class="form-control">
<option value="Overschrijving">Overschrijving</option>
<option value="Visa">Visa</option>
<option value="Cash">Cash</option>
</select>
</div>
Just need to clean up the code, but this works. Just learned another lesson: single-paged websites and php (session more specific) are not best friends :-)
The Problem
I am trying to submit a form in php but due to the nature of what i want i need the page to not go onto the next one i just want it to submit the data and refresh the current page or whatever, at current it submits the data and goes onto page 2 which i dont want i just need it to submit the data and stay on the current page, if thats possible!
The Code
//page 1 code
<center>
<h1>What Is Jacob Dailey Doing?</h1>
<form method="post" action="jacob_dailey.php">
<select name="baby_status">
<option value="playing">Playing</option>
<option value="awake">Awake</option>
<option value="sleeping">Sleeping</option>
</select>
<br />
<input type="submit" value="Submit"/>
</form>
</center>
//page 2 code
<?php
if (isset($_POST['baby_status'])) {
$baby = $_POST['baby_status'];
setcookie("baby_status", $baby, time() + 31556926, '/'); // Data will Store For 1 Year
header('Location: ' . $_SERVER['PHP_SELF']);
}
$status = $_COOKIE['baby_status'];
echo '<center> <h1>Baby Jacob Dailey Is Currently ' . ucwords($status) . '</h1>';
if ($status == "playing") {
echo '<img src="http://cdn.sheknows.com/articles/2013/02/baby-playing-with-blocks.jpg"/>';
}
elseif ($status == "awake") {
echo '<img src="http://www.westheimphoto.com/lightbox/gallery/TaiwanStockPhotos/TWNhw1221.jpg"/>';
}
elseif ($status == "sleeping") {
echo '<img src="http://www.babycare.onlymyhealth.com/imported/images/neonatal/2012/July/19_Jul_2012/6-Months-Old-ssl.jpg"/>';
}
echo '</center>';
?>
Page 2 code shouldnt be as important but i just need it so when i click submit on page 1 it updates the information on page 2 but doesnt take me to page 2.
Cheers!
Your form can submit onto itself. Just in the action="xyz" either leave it (the whole action=... attribute) out entirely or else name the page that also contains the form there between quotes.
Then when you load the page you check the $_POST or $_GET array (depending on the method) to see if the submit button was pushed or if someone just navigated to the page. (You'll want to give you submit button a name="foo".)
action="jacob_dailey.php" in your form takes you to that page, you either paste your php code to main page and replace action with just "" or you will search AJAX and learn how to it with that
You can use jQuery.ajax(). Example here:
http://www.formget.com/form-submission-using-ajax-php-and-javascript/
This example uses a database, but you can use a php file to return values and read them from the response in javascript. Do not put any action to the form but enable a click event handler on the submit button to enable the function.
Also my example here: http://dev.ossipesonen.fi/alkoholilaskuri/
A very simple form where you insert values, pass them onto PHP with $_POST and then calculates the right amounts and sums, and you print them in the response.
Solution: Update Status Without Page Reload Using XHR and Filesystem Storage
If you want someone on another computer to see the update, then you'll need to store that information on the server. You could store the information in a database, but for this small bit of information I'm using the filesystem.
page1.php
<?php
// get baby status if available
if ( is_readable('baby_status.php') ) {
include 'baby_status.php';
}
$status = ( $status )? $status: '??';
// prepare to update select list
list($pl_check, $pl_check, $pl_check) = array('', '', '');
switch ( $status ) {
case 'playing': $pl_check = ' selected '; break;
case 'awake': $aw_check = ' selected '; break;
case 'sleeping': $sl_check = ' selected '; break;
}
?>
<center>
<h1>What Is Jacob Dailey Doing?</h1>
<form id="baby_form" method="post" action="update_baby.php">
<select id="baby_status" name="baby_status">
<option value="playing" <?php echo $pl_check ?>>Playing</option>
<option value="awake" <?php echo $aw_check ?>>Awake</option>
<option value="sleeping"<?php echo $sl_check ?>>Sleeping</option>
</select><br />
<input type="submit" value="Submit"/>
</form>
See Baby Status
</center>
<script>
// XHR/PHP/Filesystem method
function update_baby () {
var baby_status = document.getElementById('baby_status');
var status=encodeURIComponent(baby_status.options[baby_status.selectedIndex].value)
var parameters = 'baby_status=' + status
// set up XHR object
var xhr = new XMLHttpRequest()
xhr.open('POST', 'update_baby.php', true)
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
// handle response
xhr.onload = function () {
console.log(this.responseText)
alert(this.responseText)
}
xhr.send(parameters)
}
// hook up baby status function to form submit
document.getElementById('baby_form').addEventListener('submit', function(evt){
evt.preventDefault()
update_baby()
})
</script>
page2.php
<?php
// execute baby update code and get current status
include 'update_baby.php';
echo '<center> <h1>Baby Jacob Dailey Is Currently ' . ucwords($status) . '</h1>';
if ($status == "playing") {
echo '<img src="http://cdn.sheknows.com/articles/2013/02/baby-playing-with-blocks.jpg"/>';
}
elseif ($status == "awake") {
echo '<img src="http://www.westheimphoto.com/lightbox/gallery/TaiwanStockPhotos/TWNhw1221.jpg"/>';
}
elseif ($status == "sleeping") {
echo '<img src="http://www.babycare.onlymyhealth.com/imported/images/neonatal/2012/July/19_Jul_2012/6-Months-Old-ssl.jpg"/>';
}
?>
<br>
Update Baby Status
</center>
update_baby.php
<?php
if (isset($_POST['baby_status'])) {
$status = $_POST['baby_status'];
// prepare php script text for baby status file
$status_write = <<<EOT
<?php
\$status = '$status';
?>
EOT;
// write status to baby_status.php
if ( $baby_status_file = fopen('baby_status.php', 'w') ) {
fwrite($baby_status_file, $status_write);
fclose($baby_status_file);
}
echo 'Baby status updated.';
}
else {
if ( is_readable('baby_status.php') ) {
include 'baby_status.php';
}
$status = ( $status )? $status: '??';
}
?>
Note: To use this option the directory these files are in must be writeable by the web server.
Ok I have this code
a script in my head.
function checkForm(e) {
if (e.keyCode == 13) {
$('#de').hide()
$.post('search.php', { name : search.searchinput.value() }, function(output) {
$('#searchpage').html(output).show();
});
}
}
and this is the html part:
<form name="search" id="searchbox">
<input name="searchinput" value="search item here..." type="text" id="inputbox" onkeydown="checkForm(event);" onclick="clickclear(this, 'search item here...')" onblur="clickrecall(this,'search item here...')"/><input id="submit" value="" OnClick="checkForm(event);" type="submit"/>
</form>
<div id="searchpage"></div>
and this the php file where the script will pass the data into.
<?
$name= $_POST['name'];
$con=mysql_connect("localhost", "root", "");
if(!$con)
{
die ('could not connect' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE title='$name' OR description='$name' OR type='$name'");
$vv = "";
while($row = mysql_fetch_array($result))
{
$vv .= "<div id='itemdiv2' class='gradient'>";
$vv .= "<div id='imgc'>".'<img src="Images/media/'.$row['name'].'" />'."<br/>";
$vv .= "<a href='#?w=700' id='".$row['id']."' rel='popup' class='poplight'>View full</a>"."</div>";
$vv .= "<div id='pdiva'>"."<p id='ittitle'>".$row['title']."</p>";
$vv .= "<p id='itdes'>".$row['description']."</p>";
$vv .= "<a href='".$row['link']."'>".$row['link']."</a>";
$vv .= "</div>"."</div>";
}
echo $vv;
mysql_close($con);
?>
here is the sceneraio, a user put a whatever text on the textbox name:'searchinput' and so whenever the user pressed the enter key the function checkForm(e) will execute and pass the data from the input field name:'searchinput' into the php file and then that php file will process the data into the mysql and see if the data that the script has pass into the php file is match to the mysql records and then if ever it match then the php file will pass that data back into the script and then the script will output the data to the #searchpage div.
Problem:
"all are not working" and the onclick function on the go button are not working"
please help, im stuck on this. thank you in advance.
First of all, there is a website called Jsfiddle. Paste your codes in the website and then paste the URL here. It makes your post a lot more readable.
Now, here if you are using jQuery, then why are you relying on onkeydown and onclick events? Its better to use jQuery's live function.
I have changed your code. Have a look at here. You can use live function for other events like onclick,onfocus,onblur,etc. It makes your HTML code much more cleaner and readable.
Consider using load instead of post (And remove the form tag or change input to textarea or else hitting enter will submit your form)
$('#inputbox').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13')
{
$('div#searchpage').load('search.php',{name: $(this).val()});
}
});
you have to stop the form from submitting the data, use something like
onsubmit="return (checkForm(e))"
and double check for syntax errors, for example you have missed a Semicolon at this line
$('#de').hide()