I have the following code.
if(isset($_POST['save'])){
$descript = $_POST{'descript'};
$type = $_POST{'type'};
$c_max = $_POST{'c_max'};
$status = $_POST{'status'};
$queryInsert = "INSERT INTO `item_master` (`Item`, `Descript`, `Type`, `C_max`, `Exist`, `Status`) VALUES ('$item', '$descript', '$type', '$c_max', '0', '$status');";
try{
$resultInsert = mysqli_query($conn, $queryInsert);
if($resultInsert)
{
if(mysqli_affected_rows($conn) > 0)
{
echo '<script type="text/javascript">alert("Item Inserted");</script>';
header ("Location: Insertion.php");
}else{
echo '<script type="text/javascript">alert("The item could not be inserted ");</script>';
}
}
} catch (Exception $ex){
echo 'Error Delete '.$ex->getMessage();
}
}
My code works fine my query actually can insert new data in my DB but as the title said my "confirmation" alert is not displaying and I don't understand why. Before my if(isser($_POST['save'])) a JS function runs and ask me if I really want to insert a new data. So obviously I have the pop alerts activated in my browser. So... Im I doing somthing wrong?
Thanks for your comments!
you can use window.location(or other related options like:window.location.href).
if(mysqli_affected_rows($conn) > 0)
{
echo '<script type="text/javascript">alert("Item Inserted");window.location="Insertion.php";</script>';
}else{
echo '<script type="text/javascript">alert("The item could not be inserted ");</script>';
}
Related
I want to get variable rating_idex in my php file so if is user click button #add-review it should pass in ajax variable and it will get array in php file and send review to the database, but it is not working and I don't see solution
$('#add-review').click(function(){
var user_name = $('#reviewer-name').val();
var user_review = $('#review').val();
console.log(user_name);
console.log(rating_index);
console.log(user_review);
if(user_name == '' || user_review == '')
{
alert("Please Fill Both Field");
return false;
}
else
{
$.ajax({
url:"rating-data.php",
method:"GET",
data:{
rating_index: rating_index,
user_name: user_name,
user_review: user_review
},
success:function(data)
{
$('#review_modal').modal('hide');
load_rating_data();
console.log(data);
}
})
}
});
This is my php code when I can get the variable and send them to the database:
<?php
include 'connection.php';
echo ($rating_index);
if(isset($_GET["rating_index"]))
{
$data = array(
':user_name' => $_GET["user_name"],
':user_rating' => $_GET["rating_index"],
':user_review' => $_GET["user_review"],
':datetime' => time()
);
$query = "
INSERT INTO review_table
(user_name, user_rating, user_review, datetime)
VALUES (:user_name, :user_rating, :user_review, :datetime)
";
$query_run = mysqli_query($conn, $query);
if($query_run){
echo "Your Review & Rating Successfully Submitted";
} else{
echo '<script type="text/javascript"> alert("Something went wrong") </script>';
echo mysqli_error($conn);
}
}
?>
When I am trying to echo ($rating_index) it give me feedback that variable does not exist so it is something with ajax but can't find solution, thanks in advance for any solutions
Instead of echo ($rating_index); try echo ($_GET["rating_index"]); reason being you didn't actually declared $rating_index
if I'm not wrong you want to pass the PHP variable in javascript?
if yes you cant pass the PHP variable in js like this.
var x = " < ? php echo"$name" ? >";
you can pass your PHP variable like this but in only the .php file not in the .js
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'];
}
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.
I am using an anchor tag to run the JS function confirm(), and if the user clicks okay it adds "deltopic=id", and use the $_GET method to get 'deltopic' to delete that specific item, but it seems to not be finding the $_GET['deltopic']
<script language="JavaScript" type="text>
function deltopic(title, tid) {
if(confirm("Are you sure you want to delete '" + title + "'")){
window.location.href = "?viewtopic.php&deltopic=" + tid;
}
}
</script>
<?php
if(isset($_GET['deltopic'])){
if($_GET['deltopic'] !=='1'){
$query = "DELETE FROM `bkg`.`bkg_topics` WHERE `bkg_topics`.`topic_id` = :topicid";
$query_params = array(':topicid' => $_GET['deltopic']);
try{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
header('Location: index.php?forums&action=deleted');
exit;
} catch(PDOException $e) {
$error[] = "An error has occured. Please try again later.";
}
}
echo "deltopic is set";
}
I added the last echo just to see if its checking if deltopic isset, or if it was an error in my SQL that I was just not seeing. However I do not see "deltopic is set".
I am not sure what I am doing wrong and/or what I am forgetting. I have code similar to this, that does work, and double checked it closely.
EDIT: I saw the error I was doing in my 'window.location.href' string, where I was adding .php to the end of ?viewtopic, making it ?viewtopic.php. Removing the .php fixed my issue as well.
window.location.href = "?viewtopic.php&deltopic=" + tid;
will result in URL where "viewtopic.php" is a part of URL QUERY. Perhaps you want it in the PATH:
window.location.href = "viewtopic.php?deltopic=" + tid;
Well the title says it all. I want to get any php error, warning, notice and alert them via JavaScript in my own format. Is that possible? If yes then how? I have tried this but it won't catch warnings or notices i guess.
try{
$result = oci_parse($conn, $query);
oci_execute($result);
}catch(Exception $e){
echo 'Caught exception: ', $e->getMessage(), "\n";
///////////or anything to alert with JavaScript///////////
}
Try this piece of code :
<?php
try{
$result = oci_parse($conn, $query);
oci_execute($result);
}
catch(Exception $e){
echo '<script language="javascript">';
echo 'alert("Caught exception")';
echo '</script>';
}
?>
Updated based on your comment
<?php
session_start();
//set this in your catch block
$_SESSION['flash'] = 'message';
//check for it in everypage.
if(isset($_SESSION['flash']) && !empty($_SESSION['flash']))
{
echo '<div id="flash_container">'.$_SESSION['flash'].'</div>';
unset($_SESSION['flash']);
}
?>
Or try this
http://mikeeverhart.net/php-flash-messages/
I just used JavaScript and got the error text. For those who have faced similar problem:
$('.xdebug-error').find("th:first").text();
It will get the error text. If its a warning then just changing the class to 'xe-warning' would do the work! Now its possible to format the text and alert it as the user requires.