How to show alert box after successful data insertion in mysql? - javascript

I want to show JavaScript alert after successful data insertion in MySQL. How to do this? I have written this code but it shows JavaScript alert everytime I open this page and as soon as i click on OK of JavaScript alert it redirects me to finalmem.php, without the action of taking values from users!
$sql="INSERT INTO members VALUES ('$name', '$email', '$ybr', '$ach')";
if(!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo '<script language="javascript">';
echo 'alert("Successfully Registered"); location.href="finalmem.php"';
echo '</script>';
}
Thanks in advance.

Use is set isset($_POST['submit']) to check whether user submits the form or not
<?php
include 'SQLIDB.php';
if(isset($_POST['submit'])){
$name=$_POST['name'];
$email=$_POST['email'];
$ybr=$_POST['ybr'];
$ach=$_POST['ach'];
$sql="INSERT INTO members VALUES ('$name', '$email', '$ybr', '$ach')";
if(!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
else
{
echo '<script language="javascript">';
echo 'alert("Successfully Registered"); location.href="finalmem.php"';
echo '</script>';
}
}
?>
<form action="" method="post">
<input type="text" name="name">
<input type="text" name="email">
<input type="text" name="ybr">
<input type="text" name="ach">
<input type="submit" name="submit" value="Submit">
</form>

You need to know two things, one of them it's to confirm if your data it's saved succefully.
For this you can play with
mysql_affected_rows()
and this function will return the number of rows affected by your query. If zero, it was not inserted. If >= 1, it was.
So:
if ( mysql_affected_rows() >= 1 ){ /* inserted! now do something... */ }
If you are using an auto-incrementing column for row ID, you can use mysql_insert_id() as well:
if ( mysql_insert_id() > 0 ) { /* inserted! now do something... */ }
Then you can work with jQuery UI for show a dialog like this:
[https://jqueryui.com/dialog/][1]
You need tot load the .css and .js files to run jQuery and inside your code put this:
<script>
$(function() {
$( "#dialog" ).dialog();
});
</script>
And this in your view:
<div id="dialog" title="Basic dialog">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
Normally this it's super ugly to do for me, because the best way it's doing this by AJAX.

You can try like this
<?php session_start();
//Include database detail here
if(isset($_POST['name'])){
$name = mysqli_real_escape_string($_POST["name"]);
$ybr = mysqli_real_escape_string($_POST["ybr"]);
email = mysqli_real_escape_string($_POST["email"]);
$ach = mysqli_real_escape_string($_POST["ach"]);
//Do your data validation here
$_SESSION['sname'] = $name;
$_SESSION['sybr'] = $ybr;
$_SESSION['semail'] = email;
$_SESSION['sach']= $ach;
$sql="INSERT INTO members VALUES ('$name', '$email', '$ybr', '$ach')";
if(!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
} else {
echo '<script language="javascript">';
echo 'alert("Successfully Registered"); location.href="finalmem.php"';
echo '</script>';
}
}
?>

Related

Passing a PHP variable with fetched data to a JavaScript variable returns NULL or empty

I have an issue with returning the value of a PHP variable in JS. It returns NULL or empty instead of returning the age.
Approach:
Passing PHP variable with data to a JS variable in a separate file. Display JS variable in an alert(). Data was fetched from the database using fetch_assoc() in a while loop. Without using Ajax!
Proposed plan:
Enter a name.
Submit.
PHP fetches the age associated with that name.
age is stored in a PHP variable dbage.
Passed into JS variable to alert user what their age is.
I am trying to pass $dbage from sampletest.php to user in sample.php which will onsubmit display an alert saying: "Your age is blah".
blah is $dbage, which contains the age. This is for testing. Once I understand why this isn't working, I can move on to sending these JS variables to functions that will do calculations and return back to the DB.
What I have tried so far..
Trying to catch echo using ob_start() but that returned NULL as well.
Example:
ob_start();
echo $dbage;
$output = ob_get_contents();
ob_end_clean();
Making $dbage a global variable. Returns empty.
Echo variable outside the while loop but that returned NULL.
Example:
$dbage = '';
while( $row = $result->fetch_assoc()) {
$dbage = $row['age'];
}
echo $dbage;
Any suggestions, corrections are appreciated.
sample.php (index file)
<?php
include 'sampletest.php';
session_start();
?>
<!DOCTYPE html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<body>
<div id="id03">
<form class="modal-content" action="sampletest.php" method="post" onsubmit="myFunction()">
<div class="container">
<input type="text" id="name" placeholder="Enter name" name="name">
<div class="clearfix">
<button type="submit" class="loggedinbtn" name="load"/>Load
</div>
</div>
</form>
</div>
<script>
function myFunction() {
var user = '<?php echo(json_encode($dbage)); ?>';
alert("This is a php varible " + user);
}
</script>
</body>
</html>
sampletest.php
if(isset($_POST['load'])){
require 'config.php';
$name = $_POST['name'];
$age = $_POST['age'];
if(empty($name)) {
echo "Enter a number";
}elseif(!preg_match('/^[a-z ]+$/i', $name)){
echo "Enter a letter, no numbers";
}else{
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
header("location: sample.php?Connect-database=failed");
exit();
}
$sql = "SELECT name, age FROM results WHERE name= '$name';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while( $row = $result->fetch_assoc()) {
$dbage = $row['age'];
}
}
else{
echo "0 results";
}
$conn->close();
}
}
your action in the form should be set to sample.php, i think is the first problem. then get rid of the javascript all together.
<form class="modal-content" action="sample.php" method="post">
then change:
<script>
function myFunction() {
var user = '<?php echo(json_encode($dbage)); ?>';
alert("This is a php varible " + user);
}
</script>
to just
<script>
var user = <?php echo $dbage; ?>;
alert("This is a php varible " + user);
</script>
submitting html forms to PHP does not require javascript at all.
From what I can see is that the actual query that you're sending is { name= '$name' }, try { name=' " . $name . " ' }.

I have to refresh my php page after form submission to execute the code and display output

Form Submission Code
<form action="search.php" method="POST" id="form2">
<input type="text" name="Sr_no" required="true" placeholder="Enter Serial Number"><br>
<input type="submit" value="Check Status" name="ss">
</form>
My search.php
<?php
$connect=mysqli_connect("localhost","root", "" ,"mydatabase");
$Sr_no = $_POST["Sr_no"];
$status_check = "SELECT verified FROM r_concession_forms WHERE id = '$Sr_id' LIMIT 1";
$s_check = $connect->query($status_check);
$s_value = $row = $s_check->fetch_assoc();
if($s_value["verified"] == "0")
{
echo "<script>
alert('Not Issued/Verified');
window.location.href='index.php';
</script>" ;
}
elseif($s_value["verified"] == "1"){
echo "<script>
alert('Issued and Verified');
window.location.href='index.php';
</script>";
}
else{
echo "<script>
alert('No Such Form Exists');
window.location.href='index.php';
</script>";
}
?>
Output:
My Input first to check if that "id" exists in database
There is no alert box as expected, but the URL shows search.php, but no alert box displayed
After refreshing the page, the alert box starts working
The designing of page is by JavaScript
I think you are using a variable $Sr_id in the query which is not defined earlier. Also first check if the form is posted or not.
The code working fine when you refresh the page because, when you refresh the page there is no post data, so the query return empty value and it show "No such form exist". But when you post the page, the post value you given in query is wrong i guess.
<?php
if(!empty($_POST['ss'])) {
$connect=mysqli_connect("localhost","root", "" ,"mydatabase");
if(!empty($_POST['Sr_no'])) {
$Sr_no = $_POST["Sr_no"];
$status_check = 'select verified FROM r_concession_forms WHERE id = '.$Sr_no.' LIMIT 1';
$s_check = $connect->query($status_check);
$s_value = $row = $s_check->fetch_assoc();
if($s_value["verified"] == "0")
{
echo "<script>
alert('Not Issued/Verified');
window.location.href='index.php';
</script>" ;
}
elseif($s_value["verified"] == "1"){
echo "<script>
alert('Issued and Verified');
window.location.href='index.php';
</script>";
}
else{
echo "<script>
alert('No Such Form Exists');
window.location.href='index.php';
</script>";
}
}
}
?>
Also i personally don't prefer to use Script code inbetween PHP as you mentioned. Try to seperate the codes for better understanding.

actual code for xferring javascript variable to post variable

I have looked at this site for three days. I admit I am new to using javascript. But I have used the many different solutions offered and none have worked. Please help.
I am trying to do something that should be simple: save a user choice of country from a dropdown box on an html5 page to a hidden post variable (using javascript onchange.) That is used in a post array on the same form for a php operation that sends the input to a mysql database. This is my code:
The hidden post variable doesn't update. From there I can't test the code logic. But my onchange code came from this site and is suppose to work.
References:
<script type="text/javascript" src="../../js/jquery-2.1.4.min_prod.js"> </script>
<script type="text/javascript" src="../../js/respond.min.js"> </script>
<script type="text/javascript" src="../../js/bootstrap.min.js"> </script>
form information:
<form name="form1" method="post" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" />
</form>
form element
$query="SELECT * from country ";
$query=$query."ORDER BY country asc";
$data = mysqli_query($conn,$query);
//or die('could not connect to db:'. mysqli_connect_error() );
mysqli_error($conn);
If ($data) {
echo '<select id="country" onchange="send_name(this)">';
echo '<option value="204">United States</option>';
while ($row = mysqli_fetch_array($data)) {
echo '<option value="'.$row['country_id'].'">'.$row['country'].'</option>';
}//while
echo '</select>';
}//if
mysqli_close($conn);
?>
<input type="hidden" id="c_php_value" name="c_php_value" value="">
Javascript
function send_name(selectObjectI) {
var value = selectObjectI.value;
$.ajax({
type: "POST",
url: "http://localhost/php/protected/form_addnews.php",
data:{c_php_value: value}
});
Post Submit Code
$country_id1 = trim($_POST['c_php_value']);
Thanks to a coder on utube, speaking german I might add, I discovered I don't need javascript, ajax or anything complicated to accomplish what I am trying to do.
I simply needed to do the following:
(1) Add a name="" to the dynamically created SELECT flag(name="country_id2").
(2) user chooses input with drop down box created.
(3) gather the $_POST after the form submit is set.
($country_id = $_POST['country_id2'])
$data = mysqli_query($conn,$query);
//or die('could not connect to db:'. mysqli_connect_error() );
mysqli_error($conn);
If ($data) {
echo '<select name="country_id2" id="country_id2">';
echo '<option value="204">United States</option>';
while ($row = mysqli_fetch_array($data)) {
echo '<option value="'.$row['country_id'].'">'.$row['country'].'</option>';
}//while
echo '</select>';
}//if
mysqli_close($conn);

On the same page, can we retrieve different values from php by using on.change function in jquery

The dropdown box have different account id, I used Jquery on change function to get different account id every time I select, and then get first_name from database using that account id I selected. I couldn't get $web_account_number from javascript. $web_account_number=$_POST['web_account_number'] is empty. is there any other way I can make it works. Thanks in advance for helping me.
<?php
error_reporting(0);
session_start();
require_once("connect.php");
echo '<body bgcolor="#F8E9CE">';
$web_account_number=$_POST['web_account_number'];
////////////////////////////////////////////////////////////////////////////
///////////////////////////////////get dropdown web number number/////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
$dsn='mysql:host='.$hostname.';dbname=recipe_uploads';
try{
$dbh=new PDO($dsn,$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo '<div align="center"><h1><span style="color:#854513">Please Select Account</span><h1></div>';
$stmt2=$dbh->prepare("SELECT DISTINCT web_account_number FROM recipe_typist WHERE email_sent=0 AND recipes_saves=1 ORDER BY web_account_number ASC");
$stmt2->execute();
$accounts2=$stmt2->fetchAll(PDO::FETCH_ASSOC);
$web_account_number2=$accounts2[0]['web_account_number'];
echo '<p><div> Send to: <select class="ui-widget select ui-state-default ui-corner-all" id="email_select" style="width:140px;font-size:12px;text-align:center;color:black;margin:6px 0 6px 6px">';
echo '<option value="View_All_Accounts" >View All Accounts</option>';
foreach($accounts2 as $data2){
echo '<option value="'.$data2['web_account_number'].'" >'.$data2['web_account_number'].'</option>';
}
echo '</select></div></div>';
}
catch(Exception $e){
}
////////////////////////////////////////////////////////////////////////////
///////////////////////////////////get Email content/////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
try{
$dsn='mysql:host='.$hostname.';dbname=newsql_contact_section';
$dbh=new PDO($dsn,$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stm=$dbh->prepare("SELECT first_name,organization,email FROM primary_contact WHERE web_account_number=:web_account_number LIMIT 1 ");
$stm->execute(array('web_account_number'=>$web_account_number));
$foundResult= $stm->fetchAll(PDO::FETCH_ASSOC);
$first_name=$foundResult[0]['first_name'];
$organization=$foundResult[0]['organization'];
$email=$foundResult[0]['email'];
print_r($foundResult);
}
catch(Exception $e){
}
echo '<div id="name"><p>Dear: <input class="ui-widget select ui-state-default ui-corner-all"type="text" id="first_name" value="'.$first_name.'"></p></div>';
?>
<script>
$('#email_select').on('change',function(){
web_account_number=$('#email_select').val();
displayemail(web_account_number)
});
function displayemail(web_account_number){
if(web_account_number=='View_All_Accounts'){
loademail(web_account_number);
}else{
loademail(web_account_number);
}
}
function loademail(web_account_number){
//// If web_account_number is not empty the we will only load the records from that number /////
$.ajax({
url:'show_email.php',
dataType:'text',
type:'POST',
data:{'web_account_number':web_account_number},
success:function(result){
$("#first_name").val(web_account_number);
},
error:function(result){
}
});
}
</script>
//////////////////////////////////////////////
You have a lot of errors in your code.
At the end of your code, you do not close the PHP with ?>
You have an opening <script> tag in your on change function, what is no valid there.
You have no closing </script> tag at the and of the on change function.
You have no document.ready function.
Where is your displayemail javascript function?
So fix it like this, and come back if you have also errors:
echo '<div id="name"><p>Dear: <input class="ui-widget select ui-state-default ui-corner-all"type="text" id="first_name" value="' . $first_name . '"></p></div>';
?> <!-- ADD THIS CLOSING -->
<script type="text/javascript">
$(function() { //Add this
$('#email_select').on('change', function() {
web_account_number = $('#email_select').val();
displayemail(web_account_number);
});
});
</script> <!-- Remove the <script> inside your function and add a closing here -->

Alert function not working

I have a really silly issue i am trying to sort out. I have made this script that displays and deletes users from a database. however my alert function is not working. it performs the action of deleting the content in the database regardless of what I press when the alert appears. here is my code:
<?php include_once "includes/scripts.php"; ?>
<?php include_once "includes/connect.php";?>
<?php include_once "includes/cms_page_security.php";?>
<div id="cms_container"><br>
<br>
<h1>MANAGE USERS<img src="images/three_column_grid_line.png" alt="line"></h1>
<p class="logout_btn">Back</p>
<?php
$tbl="users";
$sql = "SELECT * FROM users";
$result = mysql_query($sql, $connect);
while($rows = mysql_fetch_array($result)){
echo $rows['user_name'];
echo ' ';
echo $rows['user_id']
?>
delete
<?php
} mysql_close();
?>
<script>
function alertFunction()
{
var r=confirm("Do you want to delete this user?");
if (r==true)
{
}
else
{
return (false);
}
}
</script>
</div><!--cms_container-->
</body>
</html>
I would just like the alert function to stop then process of deleting the content when i press cancel.
Change:
onClick="alertFunction()"
to:
onClick="return alertFunction()"
and in the function itself, change the false return to return false;. BTW, since a confirm returns true/false, you can change the first part of the condition to if (r)

Categories