JavaScript/PHP: Alert dialog after successfully saved - javascript

I new in programming. Currently, I develop a system that registration part. The registration part is successfully saved to the database. What I want to know is how to popup an alert dialog with one button e.g "Ok" after registration was successful and redirect to another page, such as home page. Now I only echo "successfully saved"
Below is my current code
<?php
require "DbConnect.php";
$name = $_POST['name'];
$badgeid = $_POST['badgeid'];
$position = $_POST['position'];
$department = $_POST['department'];
$factory = $_POST['factory'];
$reviewer = $_POST['reviewer'];
$title = $_POST['title'];
$year = $_POST['year'];
$month = $_POST['month'];
$suggestionwill = $_POST['suggestionwill'];
$present = $_POST['present'];
$details = $_POST['details'];
$benefit = $_POST['benefit'];
$sql_query = "INSERT INTO topsuggest (name,badgeid,position,department,factory,
reviewer,title,year,month,suggestionwill,present,details,benefit) VALUES('$name','$badgeid','$position','$department','$factory','$reviewer','$title','$year','$month','$suggestionwill','$present','$details','$benefit')";
if(mysqli_query($conn,$sql_query))
{
echo "<p id='msg'></p>";
}
else
{
echo "Error!! Not Saved".mysqli_error($con);
}
?>

Just use php header and use javascript to alert a message .
if(mysqli_query($conn,$sql_query))
{
echo "<script>alert('Successfuly Saved');</script>";
header('Location: PATH TO BE REDIRECTED');
}
For a example
if(mysqli_query($conn,$sql_query))
{
echo "<script>alert('Successfuly Saved');</script>";
header('Location: ../Insert/Index.php');
}
Please note that space between Location: is compulsory

After inserting data you can simply redirect to your interested page with a success message like:
header("location:page_of_interest.php?msg=Record Inserted");
and on page_of_interest.php you can simply check for msg and show if it is set like:
if(isset($_GET['msg'])){
echo $_GET['msg'];
}

Related

Javascript inside else statement isn't working. Message doesn't appear

I'm making a basic login for a php website, the function is really simple if checks if the data send using POST is in a MySQL table and if it's correct it would allow the user to proceed it the data is incorrect, it should show a message saying credentials are incorrect:
<?php
include("required/datos.php");
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$grupo = mysqli_real_escape_string($db,$_POST['grupo']);
$sql = "SELECT * FROM usuarios WHERE BINARY password = '$mypassword' and grupo = '$grupo'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if ($count == 1) {
$_SESSION['grupo'] = $grupo;
$_SESSION['autorizado'] = TRUE;
header('location: horario.php');
}
} else {
$message = "Credenciales incorrectas";
echo "<script type='text/javascript'>alert('$message');</script>";
header('Refresh: 0; URL=index.php');
}
?>
The if statement is working so far, and even the else but the message isn't showing out at all, I'm trying to look where exactly is the problem but I can't found it.
Try this code. Your brackets are in the wrong position.
<?php
include("required/datos.php");
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$mypassword = mysqli_real_escape_string($db,$_POST['password']);
$grupo = mysqli_real_escape_string($db,$_POST['grupo']);
$sql = "SELECT * FROM usuarios WHERE BINARY password = '$mypassword' and grupo = '$grupo'";
$result = mysqli_query($db,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$count = mysqli_num_rows($result);
if ($count == 1) {
$_SESSION['grupo'] = $grupo;
$_SESSION['autorizado'] = TRUE;
header('location: horario.php');
} else {
$message = "Credenciales incorrectas";
echo "<script type='text/javascript'>alert('$message');</script>";
header('Refresh: 0; URL=index.php');
}
}
?>
Like mentioned in the comments you have one curly braket that messes up your code. The else statement is now checking for the first if statement in which you check the request type. But the else case with the count should be the else case to your if statement that checks the number of rows ($count).
Furthermore you need to concatenate strings in your echo because your JS code doesnt know about variables or values from your PHP script like this:
echo "<script type='text/javascript'>alert('" . $message . "');</script>";
Then try this
}else {
$message = "Credenciales incorrectas";
echo "<script type='text/javascript'>alert('$message');</script>";
header('Refresh: 0; URL=index.php');
}
Try this one. Probably you have an extra bracket } or is wrongly positioned and you are echoing $message as a string which is wrong. Use concatenation in this way to print your message
$message = "Credenciales incorrectas";
echo "<script type='text/javascript'>alert('" . $message . "');</script>";
header('Refresh: 0; URL=index.php');

Pass array from javascript to page in wordpress

I have a page in wordpress, that uses an jquery and ajax to get information from an external api. The form sends the array generated in javascript back to the same page with another variable that the php in the page uses to determine which page to display. Outside of wordpress, the code works fine. Inside Wordpress the first portion runs, but then instead of loading the same page again it goes to a search page and says nothing found.
The url on the output is:
http://kltools.net/?s=&post_type%5B%5D=portfolio&post_type%5B%5D=post&post_type%5B%5D=page
Which seems odd considering I'm using post not get.
The javascript that generates the array and submits the form:
function submitchans(){
for (var i=0;i<chans.length;i++)
{ var newHidInp = document.createElement('input');
newHidInp.type = 'hidden';
newHidInp.name = 'chans[]';
newHidInp.value = chans[i];
form.appendChild(newHidInp);
}
}
function livearray(input){
if (input != null) {
chans.push(input);
}
if (Y === cSize){
submitchans();
document.forms[0].submit();
}
}
Previously the array was outArray[] instead of chans[], I changed it thinking that may be triggering the result, but no luck.
This is the PHP portion of the code:
<?php
$page_to_load = $_POST[view];
switch($page_to_load) {
case '':
echo "<script src=\"../scripts/jquery-3.2.0.min.js\"></script>";
echo "<script type=\"application/javascript\" src=\"../scripts/raid.js\"></script>";
echo "<font size=\"+3\" color=\"#FFFFFF\">Who should I host?<br>Please wait while channel is selected<br></font>";
echo "<font size=\"+2\">";
echo "<br><br>";
echo "<img src=\"../_images/ajax_loader_blue_350.gif\">";
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
$chanarray[] = null;
$offline = 0;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT `TwitchNames` FROM TK_Members WHERE Validated='1' AND RaidMe='1'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
array_push($chanarray, $row['TwitchNames']);
}
} else {
echo "0 results";
}
array_splice($chanarray, 0, 1);
$conn->close();
echo "<script type=\"application/javascript\">";
echo "var channels = ". json_encode($chanarray);
echo "</script>";
echo "</font>";
echo "<form id=\"form\" method=\"post\">";
echo "<input type=\"hidden\" name=\"view\" value=\"page2\">";
echo "</form>";
break;
case 'page2':
echo "<font size=\"+3\" color=\"#FFFFFF\">Who should I host?<br>";
echo "Your channel to host is:<br></font>";
echo "<font size=\"+2\">";
echo "<br><br>";
$chans[] = null;
$test = $_POST['chans'];
foreach ($test as $chan) {
$temparray = array(rand(),$chan);
array_push($chans, $temparray);
}
array_splice($chans,0,1);
sort($chans);
echo "".$chans[0][1]."";
echo "<br><br><br>";
echo "See All Live Channels";
echo "</font>";
break;
}
?>
After working with what blokeish has suggested I've modified the javascript file working out where the problem is.
The new javascript file is:
// JavaScript Document
var chans = ["test1","test2","test3"];
function submitchans(){
for (var i=0;i<chans.length;i++)
{ var newHidInp = document.createElement('input');
newHidInp.type = 'hidden';
newHidInp.name = 'chans[]';
newHidInp.value = chans[i];
document.getElementById('chansform').appendChild(newHidInp);
}
}
jQuery(function ($) {
submitchans();
document.getElementById('chansform').submit();
});
Using only the javascript clicking submit, it passes to the next page. When adding in the array pass is when it fails. This is the page log that is returning during the execution. !!--CORRECTION--!! there was a typo in the code, after correcting ID to Id the code is working as intended.
document.forms[0].submit() is likely submitting the wp search form as that could be the first form in the DOM. I see "http://kltools.net/?s=" in the URL where "s" is the search term.
Using document.getElementById('idOfForm').submit() should get you around that problem if there are multiple forms in a page and you cant be sure of its index.

Insert an paragraph with jQuery in an PHP 'If' statement

I've written a simple login script that connects to a db, and now I want to insert a paragraph with jQuery in my #loginbox which says 'Login failed' when
if (!$row = mysqli_fetch_assoc($result))
is true.
My thought was:
[function.js]
function loginfailed() {
$('#loginbox').html("<p>Login failed.</p>");
}
[login.php]
<head>
<script type="text/javascript" src="functions.js"></script>
</head>
<?php
include '../config.php';
include 'dbh.php';
session_start();
$uid = $_POST['uid'];
$pw = $_POST['pw'];
$sql = "SELECT * FROM user WHERE uid='$uid' AND pw='$pw'";
$result = mysqli_query($conn, $sql);
if (!$row = mysqli_fetch_assoc($result))
{
header('Location: ../index.php');
echo '<script> loginfailed(); </script>';
}
else
{
header('Location: ../index.php');
}
?>
But it doesn't work.
DON'T EVER STORE PASSWORDS IN PLAIN TEXT!!
Regarding your question.
The header function redirects to index.php and does not execute the echo. One solution can be to add a $_GET parameter and after the redirect check if it exists and echo the message or append it with JS.
if (!$row = mysqli_fetch_assoc($result))
{
header('Location: ../index.php?status=fail');
}
In the index.php file at the bottom (if you want to use JS/jQuery to show message)
<script>
var status = "<?php echo (!empty($_GET['status']) && $_GET['status'] === 'fail') ? 0 : 1; ?>";
if(!status) loginfailed();
</script>
Thanks guys, but i've found my own solution with the help of Allkin.
My header now redirects to
header('Location: ../index.php?status=fail');
and my #loginbox checks if status is set and then executes my loginfailed() function.
if(isset($_GET['status'])) {
echo '<script> loginfailed(); </script>';
}
Nothing easy like that!
Thanks for your help everyone.

Reload page in PHP after form submission

I have one page where i can Approve or Delete comments which user submitted on my blog (I built the blog without Wordpress with PHP and MySQL) Now everything is working fine and i just need help with one question.
I'm deleting and approving comments from one page means i have separate queries but both are on same page and i want to auto-refresh page only once after submitting of form, below is code which i has.
For approving comment -
<?php
if(isset($_POST['approve_cmt'])) {
$id = $_POST['id'];
$sql = "UPDATE `blog_comments` SET `status` = '1' WHERE comment_id = '$id'";
$res = mysql_query($sql) or die(mysql_error());
if ($res == 1) {
echo "<script type='text/javascript'>alert('Comment approved!') window.location.reload(); </script>";
} else {
echo "<script type='text/javascript'>alert('Failed to approve comment') window.location.reload(); </script>";
}
}
;?>
for deleting comment
<?php
if(isset($_POST['delete_cmt'])) {
$id = $_POST['id'];
$sql = "DELETE FROM `blog_comments` WHERE `comment_id` = '$id'";
$res = mysql_query($sql) or die(mysql_error());
if ($res == 1) {
echo "<script type='text/javascript'>alert('comment deleted') window.location.reload(); </script>";
} else {
echo "<script type='text/javascript'>alert('unable to delete comment') window.location.reload(); </script>";
}
}
;?>
Use redirect('Location: the_same_page_name');

Two questions about possible mysql and php functionalities (maybe javascript?), and where I should look to learn more

First, is it possible for when I insert a record onto my mysql table, a page is automatically generated using the new record in some way. EXAMPLE: My column "image" is on autoincrement, so my image names are always numbers. Furthermore, is it possible for when I insert a record, I automatically generate a page with my image name. So basically, I submit record 367, the image name is 367, and my site will automatically generate mysite.com/367? I want to go in more details but you get the point. Is it possible? If not, what's the closest thing possible?
Also, is there someway to automatically update my page periodically. Such as I set it so at 5pm, it'll automatically insert a code. 5:30pm, it'll insert a different code, which I preprogrammed to do. This is useful, for say I'm on vacation but I still want to update my site regularly.
Can you guys point me to any specific tutorial/terminology/methods/programs/codes/anything? All help would be appreciated!
EDIT: Code I have so far (just want to show to Nick)
<html>
<head>
<title>tgh</title>
</head>
<body>
<?php
$objConnect = mysql_connect("localhost","root","") or die(mysql_error());
$objDB = mysql_select_db("thegoodhumor");
$strSQL = "SELECT * FROM gallery";
if (!isset($_GET['Page'])) $_GET['Page']='0';
$objQuery = mysql_query($strSQL);
$Num_Rows = mysql_num_rows($objQuery);
$Per_Page = 16; // Per Page
$Page = $_GET["Page"];
if(!$_GET["Page"])
{
$Page=1;
}
$Prev_Page = $Page-1;
$Next_Page = $Page+1;
$Page_Start = (($Per_Page*$Page)-$Per_Page);
if($Num_Rows<=$Per_Page)
{
$Num_Pages =1;
}
else if(($Num_Rows % $Per_Page)==0)
{
$Num_Pages =($Num_Rows/$Per_Page) ;
}
else
{
$Num_Pages =($Num_Rows/$Per_Page)+1;
$Num_Pages = (int)$Num_Pages;
}
$strSQL .=" order by GalleryID ASC LIMIT $Page_Start , $Per_Page";
$objQuery = mysql_query($strSQL);
$cell = 0;
echo '<table border="1" cellpadding="2" cellspacing="1"><tr>';
while($objResult = mysql_fetch_array($objQuery))
{
if($cell % 4 == 0) {
echo '</tr><tr>';
}
if($cell == 2) {
echo '<td>RESERVED</td>';
} elseif ($cell == 3) {
echo '<td>The other cell</td>';
} else {
echo '<td><img src="https://s3.amazonaws.com/imagetitle/' . $objResult["Picture"] . '" />' .
$objResult["GalleryName"] . '</td>'; }
$cell++;
}
echo '</tr></table>';
?>
<br>
view more:
<?php
if($Prev_Page)
{
echo " <a href='$_SERVER[SCRIPT_NAME]?Page=$Prev_Page'>prev</a> ";
}
{
echo "|";
}
if($Page!=$Num_Pages)
{
echo " <a href ='$_SERVER[SCRIPT_NAME]?Page=$Next_Page'>next</a> ";
}
?>
</body>
</html>
<?php
mysql_close($objConnect);
?>
It sounds like you want a dynamic web page. To make a dymaic webpage I'd suggest using PHP which would interact with the mysql server.
For example, a user would visit 'mysite.com/info.php?image=367' and the php script would get the information 'image=367'. Your PHP script could do a select query against the mysql database 'SELECT paragraph FROM table WHERE image_id = 367' and then write that data out to the user's web browser.
As far as the user is concerned they just visited 'mysite.com/info.php?image=367', but in the background, PHP dynamically created the webpage content after it got that request.
More basic info about dynamic webpages: http://way.clicktracks.com/help/en/pr650/index.html?dynamicwebsiteshowtheywork.htm
Simple Intro to PHP:
http://www.tizag.com/phpT/
http://www.w3schools.com/php/php_intro.asp
Here is a head start I wrote for you, feel free to use it.
<?php
if (!isset($_GET['imageNumber']))
die("You must specify an image number");
$image_requested = mysql_real_escape_string($_GET['imageNumber']); //sanitizes input
$dbhost = 'localhost'; //TODO: Set this to the ip address of your mysql server if it is not on the same machine
$dbuser = 'root'; //TODO: Set the username you use to access your mysql db here
$dbpass = 'password'; //TODO: Set the password you use to access your mysql db here
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
$dbname = 'database_name_here'; //TODO: Set the database name here
mysql_select_db($dbname);
$query = "SELECT paragraph FROM table_name WHERE image_id = " . $image_requested; //TODO: Set table_name, column to get, and image_id to the correct column name
$result = mysql_query($query);
$row = mysql_fetch_array($result) or die(mysql_error());
echo "Here is the paragraph of text" . $row['paragraph']; //TODO: Set paragraph to the same column you retrieved 3 lines above.
mysql_close($conn);
?>
As for the second part of your question, it can also be done with PHP
<?php
$specifictime = strtotime("tuesday 3pm");
if (time("now") > $specifictime)
{
echo " its after 3pm on tuesday";
}
else {
echo " not 3pm on tuesday yet";
}
?>

Categories