how to show the single alert message for multiple mysql queries? - javascript

i have a small doubt.. i posted my delete.php page coding here.
if(isset($_GET["id"]))
{
$meal_query = mysql_query("DELETE FROM ebmealplans WHERE MealPlanID = '$id'");
echo mysql_error();
$room_query = mysql_query("DELETE FROM ebroomtypes WHERE RoomTypeID = '$id'");
echo mysql_error();
$tariff_query = mysql_query("DELETE FROM ebvouchertariffs WHERE VoucherID_Fk = '$id'");
echo mysql_error();
$query = mysql_query("DELETE FROM ebvouchers WHERE VoucherID = '$id'");
echo mysql_error();
if($query)
{
echo "<script> alert('Voucher deleted successfully'); </script>";
}
else
{
echo "<script> alert('Failed to delete this voucher'); </script>";
}
mysql_close($link);
echo "<script> location.href='managevouchers.php'; </script>";
}
here i am delete some user datas using this php coding. it worked perfectly. i created four separate tables for store the records. if deletion function was successfully completed i want to show the alert message to users "Deleted Successfully". you can see in my coding i'm just show the alert message for only one $query. i tried another method..
if($query)
{
alert function
}
else
{
alert function
}
if($meal_query)
{
alert function
}
else
{
alert function
}
if($room_query)
{
alert function
}
else
{
alert function
}
if($tariff_query)
{
alert function
}
else
{
alert function
}
it show the alert message four times. i know multiple alert functions annoying the users. my question is how to show the single alert message for mysql multiple queries?

Just store the msg pieces in some variable, and alert them all finally.
$msgs = array ();
if ($query) {
$msgs [] = '.....';
} else {
$msgs [] = '...';
}
if ($meal_query) {
$msgs [] = '....';
} else {
$msgs [] = '...';
}
//....
if ($msgs) {
//join the msgs with line break
$alert = join ( "\n", $msgs );
//json encode will make sure it's like "..string..", no quotes problem
echo '<script> alert(', json_encode ( $alert ), '); </script>';
}

Related

Refresh page without form resubmit

this is probably very simple but im really new to php and js
i made a comment system for my site but i have an issue that i cant figure out
//comment section
$commentsArray = array();
$commentQuery_run = mysqli_query($con, "SELECT * FROM comments WHERE PostID='$userPostId'");
if (mysqli_num_rows($commentQuery_run) > 0) {
echo "<b id='commcount'>Comments:".mysqli_num_rows($commentQuery_run).
"</b>";
while ($commentRow = mysqli_fetch_assoc($commentQuery_run)) {
$commentID = $commentRow['id'];
$commentUsername = $commentRow['username'];
$commentUserPfpPath = $commentRow['path'];
$commentContent = $commentRow['text'];
$commentDate = $commentRow['date'];
$commentsArray[] = $commentContent;
echo "html for displaying the comments";
}
} else {
echo "<b id='commcount'>No comments! Be the first one to comment!</b>";
}
if ($isLoggedIn === true) {
echo "<form id='commForm' method='POST' action=''> <
input id = 'commTextInp'
type = 'text'
placeholder = 'Your comment...'
name = 'commentText' > < br >
<
input id = 'commSubmInp'
type = 'submit'
name = 'commentSubmit'
value = 'Post Comment' >
<
/form>";
} else {
echo "<b id='commcount'>Please Login In to comment!</b>";
}
//comment section
//coment process
if (isset($_POST['commentSubmit'])) {
if (isset($_POST['commentText']) && !empty($_POST['commentText'])) {
$postCommentUsername = $_SESSION['username'];
$postCommentPfpImg = $_SESSION['pfpimg'];
$postCommentContents = mysqli_real_escape_string($con, htmlentities($_POST['commentText'], ENT_QUOTES));
$postCommentDate = date("d/m/Y H:i");
if (!in_array($postCommentContents, $commentsArray)) {
$postCommentQuery_run = mysqli_query($con, "INSERT INTO comments VALUES('','$userPostId','$postCommentUsername','$postCommentPfpImg','$postCommentContents','$postCommentDate')");
if ($postCommentQuery_run === true) {
echo "<script> window.location.reload() </script>";
} else {
echo "<b style='color:red;'>Error while submitting comment!</b>";
}
} else {
echo "<b style='color:red;'>Please don't repeat yourself/other users!</b>";
}
} else {
echo "<b style='color:red;'>Please write something in your comment and try again</b>";
}
}
echo "</center>";
//comment process
every time i submit the form i get the "please dont repeat yourself/other users" error. why? does the window.location.reload() function also re-submit the form? or im I doing something completely wrong? and is there any better method for reloading the site? as it might be obvious i need to reload the page so that the new comment shows up. again, im really new to php/js/html so please explain why my code isnt working the way its supposed to. my guess is that the reload() method resubmits the form (excuse my bad english)
You better should place your POST-processing code in header of file, and you will be able to use header() redirect. To show error, you can use some flag; see:
// here we store all our comments
$commentsArray = [];
$commentQuery_run = mysqli_query($con,"SELECT * FROM comments WHERE PostID='$userPostId'");
while($commentRow = mysqli_fetch_assoc($commentQuery_run)){
$commentsArray[] = $commentRow;
}
//coment process
if(isset($_POST['commentSubmit'])){
if(isset($_POST['commentText']) && !empty($_POST['commentText'])){
$postCommentUsername = $_SESSION['username'];
$postCommentPfpImg = $_SESSION['pfpimg'];
$postCommentContents = mysqli_real_escape_string($con, htmlentities($_POST['commentText'], ENT_QUOTES));
$postCommentDate = date("d/m/Y H:i");
if(! array_search($postCommentContents, array_column($commentsArray, 'text')) ){
$postCommentQuery_run = mysqli_query($con,"INSERT INTO comments VALUES('','$userPostId','$postCommentUsername','$postCommentPfpImg','$postCommentContents','$postCommentDate')");
if($postCommentQuery_run === true){
header("Location: " . $_SERVER['PHP_SELF']);
}
else {
$is_error = 'ERROR';
}
}
else{
$is_error = 'DUPLICATE';
}
}
else{
$is_error = 'NO_DATA';
}
}
and next, in the old place (in the middle of page) you can show error:
if(isset($is_error)) {
switch($is_error) {
case 'DUPLICATE':
echo "<b style='color:red;'>Please don't repeat yourself/other users!</b>";
break;
case 'NO_DATA':
echo "<b style='color:red;'>Please write something in your comment and try again</b>";
break;
default:
echo "<b style='color:red;'>Error while submitting comment!</b>";
}
}
// ...........
// PRINT ALL COMMENTS HERE
if(count($commentsArray)>0){
echo "<b id='commcount'>Comments:" . count($commentsArray) . "</b>";
foreach($commentsArray as $comment){
// $comment contains all your db-fields
echo "html for displaying the comments";
}
}
else{
echo "<b id='commcount'>No comments! Be the first one to comment!</b>";
}
every time i submit the form i get the "please dont repeat yourself/other users" error. why?
if(! in_array($postCommentContents, $commentsArray))
for first comment is true because:
if(mysqli_num_rows($commentQuery_run) > 0)
for first comment is false and commentsArray is empty.

ALERT ,when searched word not found in mysql database

my coding is all about
1)fetch the data from mysql thro php
2)get data from php to d3 based on input by using PHP URL
I want to set alert when the text in the input field is not found in mysql database..
now when I try with the word other than mysql data, it shows
this console
how can i alert when wrong word(other than mysql database value) is submitted
HTML FORM
<form name="editorForm">
<input type="text"name="editor" id="editor"
onchange="document.getElementById('editorForm').submit();">
<input type="submit"value="butn">
</form>
JQUERY TO FETCH THE DATA FROM PHP BASED ON URL
$(function () {
$('form').submit(function (e) {
e.preventDefault();
var t=$('form').serialize();
var u='http://localhost:8888/saff/indexi.php?'+t;
if(u==null){
alert("not found");
}
else{
funn();
}
D3 CODES
function funn(){
d3.json(u, function(treeData) {
//D3 CODES
});
}
my php code
<?php
$con=mysqli_connect("localhost","root","admin","data");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name=$_GET['editor'];
$sql="SELECT * FROM phptab where value LIKE '%".$name."%'";
$r = mysqli_query($con,$sql);
$data = array();
while($row = mysqli_fetch_assoc($r)) {
$data[] = $row;
}
function buildtree($src_arr, $parent_id = 0, $tree = array())
{
foreach($src_arr as $idx => $row)
{
if($row['parent'] == $parent_id)
{
foreach($row as $k => $v)
$tree[$row['id']][$k] = $v;
unset($src_arr[$idx]);
$tree[$row['id']]['children'] = buildtree($src_arr, $row['id']);
}
}
ksort($tree);
return $tree;
}
function insertIntoNestedArray(&$array, $searchItem){
if($searchItem['parent'] == 0){
array_push($array, $searchItem);
return;
}
if(empty($array)){ return; }
array_walk($array, function(&$item, $key, $searchItem){
if($item['id'] == $searchItem['parent']){
array_push($item['children'], $searchItem);
return;
}
insertIntoNestedArray($item['children'], $searchItem);
}, $searchItem);
}
$nestedArray = array();
foreach($data as $itemData){
//$nestedArrayItem['value'] = $itemData['value'];
$nestedArrayItem['id'] = $itemData['id'];
$nestedArrayItem['name'] = $itemData['name'];
$nestedArrayItem['parent'] = $itemData['parent'];
$nestedArrayItem['tooltip'] = $itemData['tooltip'];
$nestedArrayItem['color'] = $itemData['color'];
$nestedArrayItem['level'] = $itemData['level'];
$nestedArrayItem['children'] = array();
//$data[]=$dat;
insertIntoNestedArray($nestedArray, $nestedArrayItem);
}
header('Content-Type: application/json');
$json= json_encode($nestedArray,JSON_UNESCAPED_UNICODE);
echo $json = substr($json, 1, -1);
?>
works as expected when the word used is exist in the database
and the page looks like this
getting correct json format in the mozilla console.but design is not shown in the page...but in chrome ,everything works fine..
You need to test if the page is empty in the json function of the d3
function funn(){
d3.json(u, function(treeData) {
if(!treeData.length){
alert("not found");
}else {
//D3 CODES
}
});
}
Make sure that you return a empty object from the page when not found

ajax php post with sessions wont give results

I am trying to get pre set session variables through ajax and display in my modal. its like a cart. But when i try to get them there is no result at all when i read the ajax result from chrome inspect network or the modal. below is my code. what am i doing wrong here?
<script>
$("#cart-button").click(function(){
$.ajax({
url: "includes/cart-read.php",
success: function(data){
console.log(data);
alert(data);
$('#modal-body').empty().append(''+data+'');
}
});
});
</script>
and in cart-read.php
if(isset($_SESSION['dices'])){
foreach ($_SESSION['dices'] as $dice){
$msg = $dice;
echo json_encode($msg);
}
}
session dices is an array with simple numbers. such as 4, 5, 6.
Make sure you have the following things in your code
Check if you have added session_start(); below after
Try putting an else case to your session check,
Try using an array to store and display the results.
<?php
session_start();
$result = array();
$msg = array();
if(isset($_SESSION['dices'])){
foreach ($_SESSION['dices'] as $dice){
array_push($msg,$dice);
}
if(sizeof($msg) > 0)
{
$result['status'] = true;
$result['message'] = $msg;
}
else
{
$result['status'] = false;
$result['message'] = 'No values';
}
}
else
{
$result['status'] = false;
$result['message'] = 'Session not set';
}
echo json_encode($result);
?>

Javascript inside php not working

I've create a code that check if a variable is empty or not.
If the variable is empty I execute a javascript alert, in particular:
if($verbo_name == NULL)
{
echo "
<script>
alert('no record available in the database');
</script>";
exit();
}
If I insert a message inside the echo, the message appears correctly, but I want show the alert in javascript. What's the error? Thanks..
UPDATE more details:
$results = $con->query("SELECT verbo, descrizione FROM verbo WHERE verbo = '$verbo'");
$verbo_name = NULL;
while($row = $results->fetch_array())
{
$verbo_name = $row['verbo'];
}
Check below codes are working fine for me.
<?php
$verbo_name = NULL;
if(is_null($verbo_name))
{
echo "
<script>
alert('no record available in the database');
</script>";
exit();
}
?>
Check this one
if(empty($verbo_name))
{
echo "
<script>
alert('no record available in the database');
</script>";
exit();
}
This should trigger an alert:
<html>
<body>
<?php
if($verbo_name == NULL)
{
$msg = enter code here'no record available in the database';
} else {
$msg = 'not set';
}
echo "
<script>
alert('". $msg ."');
</script>";
?>
</body>
</html>
If the message is not set the problem is just the variable.
This is Pravat Kumar Sahoo's answer,
This must work fine.
If you are testing on google chrome, you might have prevented the alert dialog message mistakenly. Please try clearing the cache/cookie or test on any other browser.
<?php
$verbo_name = NULL;
if(is_null($verbo_name))
{
echo "<script>alert('no record available in the database');</script>";
exit();
}
?>
Update:
Instead of alerting the message inside PHP, echo a message, like "NoData". And in the ajax calling Javascript, receive response "success".
echo "NoData"; // In PHP file.
In your Javascript, get the response,
success:function(response)
{
if(response == "NoData");
{
alert("No data in the Database");
}
}

If statement not working in javascript/ajax

Ok so this is driving me mad. I've got 2 modal forms - login and register. Javascript does the client side validation and then an ajax call runs either a registration php file or a login php file which returns OK if successful or a specific error message indicating what was wrong (incorrect password, username already taken,etc). There is an If Then statement that checks if the return message is OK and if it is then a success message is displayed and the other fields hidden.
The register form works perfectly. I get my OK back and fields get hidden and the success message displays.
The login form however doesn't work. A successful login returns an OK but the if statement fails and instead of a nicely formatted success message I just get the OK displayed without the username and password fields being hidden which is what makes me think the IF is failing although I cannot see why it would.
I've been staring at this code for hours now and all I can see is the same code for both and no idea why one is working and one is not ....
On to the code...Here is the Login javascript:
$("#ajax-login-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/login.php",
data: str,
success: function(msg) {
$("#logNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">You have succesfully logged in.</div>';
$("#ajax-login-form").hide();
$("#swaptoreg").hide();
$("#resetpassword").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
and here is the register javascript:
$("#ajax-register-form").submit(function(){
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "php/register.php",
data: str,
success: function(msg) {
$("#regNote").ajaxComplete(function(event, request, settings) {
if(msg == 'OK') {
// Display the Success Message
result = '<div class="alertMsg success">Thank you! Your account has been created.</div>';
$("#ajax-register-form").hide();
} else {
result = msg;
}
// On success, hide the form
$(this).hide();
$(this).html(result).slideDown("fast");
$(this).html(result);
});
}
});
return false;
});
I don't think I need to add the php here since both just end with an echo 'OK'; if successful and since I'm seeing the OK instead of the nicely formatted success message I'm confident that it is working.
Any suggestions?
EDIT: Here's the login php:
<?php
require("common.php");
$submitted_username = '';
$user = stripslashes($_POST['logUser']);
$pass = stripslashes($_POST['logPass']);
if(!empty($_POST))
{
$query = "
SELECT
id,
username,
password,
salt,
email
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $user
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query ");
}
$login_ok = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $pass . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password === $row['password'])
{
$login_ok = true;
}
}
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?>
if($login_ok)
{
unset($row['salt']);
unset($row['password']);
$_SESSION['user'] = $row;
echo 'OK';
}
else
{
echo '<div class="alertMsg error">Incorrect username or password</div>';
$submitted_username = htmlentities($_POST['username'], ENT_QUOTES, 'UTF-8');
}
}
?> <!------- There is a space here! -->
There is a space after the closing ?> which is being sent to the user. The closing ?> is optional, and it is highly recommended to NOT include it, for just this reason. Get rid of that ?>.

Categories

Resources