Alert() javascript function not working in php - javascript

I know this is frequently asked question however I have tried using :
script language='javascript'
placed header in else after alert
script type='text/javascript'
Still I don't get alert box, while else parts executes perfectly.
Here's my code:
<?php
/* header('Content-Type: application/json');
$response = array(); */
if (isset($_GET['sid'])){
$con = mysqli_connect("localhost", "root", "", "kaemiphk_greivance");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$checkdata=mysqli_query($con,"SELECT * FROM officer_master WHERE pf_no = '".$_GET['sid']."'");
$query_data=mysqli_num_rows($checkdata);
if ($query_data == 0) {
//echo alert "welcome";
echo '<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js">';
echo "alert('PF No. Does not exist. Please Contact Admin!!!');";
echo '</script>';
}
else{
header('Content-Type: application/json');
$response = array();
$select="SELECT m.officer_name,m.email,m.department,m.mobile_no,m.designation,n.quarter_no,n.address,n.colony,n.blueprint_quarter,n.type_of_quarter, n.area FROM officer_master m, quarter_master n WHERE n.pf_no='".$_GET['sid']."' AND m.pf_no = n.pf_no";
$result = mysqli_query($con, $select); //mysql_query($qry);
while ($row = mysqli_fetch_assoc($result)) {
array_push($response, $row);
}
}
echo json_encode($response);
}
?>
What am I missing here.
Thanks

You have your js files mixed up.
Include jquery and then your script, inside separate tags:
echo '<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js" ></script>';
echo '<script type="text/javascript">';
echo "alert('PF No. Does not exist. Please Contact Admin!!!');";
echo '</script>';
By the way, you do NOT need jquery for a simple alert, as it is plain javascript. Try to avoid including external library if not needed, you will end up with a bloated code.
And printing js with php it's a bit of a hack. Why not just print it into your html or js file?

Javascript inside a script tag that has an src attribute does not get executed, you have to create a second script tag after the jquery one.
<?php
/* header('Content-Type: application/json');
$response = array(); */
if (isset($_GET['sid'])){
$con = mysqli_connect("localhost", "root", "", "kaemiphk_greivance");
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$checkdata=mysqli_query($con,"SELECT * FROM officer_master WHERE pf_no = '".$_GET['sid']."'");
$query_data = mysqli_num_rows($checkdata);
if ($query_data == 0) {
//echo alert "welcome";
echo '<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.0.min.js">';
echo '</script>';
echo "<script>alert('PF No. Does not exist. Please Contact Admin!!!');</script>";
} else {
header('Content-Type: application/json');
$response = array();
$select="SELECT m.officer_name,m.email,m.department,m.mobile_no,m.designation,n.quarter_no,n.address,n.colony,n.blueprint_quarter,n.type_of_quarter, n.area FROM officer_master m, quarter_master n WHERE n.pf_no='".$_GET['sid']."' AND m.pf_no = n.pf_no";
$result = mysqli_query($con, $select); //mysql_query($qry);
while ($row = mysqli_fetch_assoc($result)) {
array_push($response, $row);
}
}
echo json_encode($response);
}
}
?>

Related

How to show alert box after successful or not data deletion in mssql

I want to show JavaScript alert after successful or not data deletion in MSSQL. How to do this? I have written this code but it shows only the message=success part alert everytime, even when the deletion dont work becasue of errors like "conflict with reference(foreign_key)" So when i click on this link.
echo "<a class='activater' href='ma_QualiOverviewloeschen.php?TestaufstellungID=".$row['TestaufstellungID'] ."&QualiID=".$row['QualiID'] ."' title='Qualitest löschen' data-toggle='tooltip' onclick='confirm_delete()'> <span class='glyphicon glyphicon-trash'></span></a>";
It calls the following php Page, which handle the SQL Part:
$QualiDelete =("DELETE FROM MyDB.dbo.Testaufstellung WHERE MyDB.dbo.Testaufstellung.TestaufstellungID = :TestaufstellungID");
$QualiDelete .=("DELETE FROM MyDB.dbo.AllgemeineAngaben WHERE MyDB.dbo.AllgemeineAngaben.QualiID = :QualiID");
$sth = $connection->prepare($QualiDelete);
$sth->execute(array(':TestaufstellungID' => $TestaufstellungID, ':QualiID:' => $QualiID));
if($sth)
{
header("location: ma_QualiOverview.php?message=success");
}
else
{
echo sqlsrv_errors();
header("location: ma_QualiOverview.php?message=failed");
}
$connection = null;
Back to the main page where the link is clicked the following ifelseconsider on messageshould Show me the right alert.
<?php
if($_GET['message']=='success'){
echo '<script language="javascript">';
echo 'alert("Erfolgreich gelöscht.");';
echo '</script>';
} elseif($_GET['message']=='failed'){
echo '<script language="javascript">';
echo 'alert("Nicht gelöscht, da Quali "ongoing" ist.");';
echo '</script>';
}
?>
What do i miss?
$sth will never be falsy, you have to check the return value of $sth->execute
Also, you should echo the errors after sending out the header.
Since $sth is always defined, you always get the success result
See the modified code here
$QualiDelete =("DELETE FROM MyDB.dbo.Testaufstellung WHERE MyDB.dbo.Testaufstellung.TestaufstellungID = :TestaufstellungID");
$QualiDelete .=("DELETE FROM MyDB.dbo.AllgemeineAngaben WHERE MyDB.dbo.AllgemeineAngaben.QualiID = :QualiID");
$sth = $connection->prepare($QualiDelete);//Check the value returned instead of $sth
$result = $sth->execute(array(':TestaufstellungID' => $TestaufstellungID, ':QualiID:' => $QualiID));
if($result )
{
header("location: ma_QualiOverview.php?message=success");
}
else
{
header("location: ma_QualiOverview.php?message=failed");
echo sqlsrv_errors();//Echo must be after header
}
$connection = null;

How to make a cookie for a link to a php but different output

Im using mysql database. I want to make a link that link to a php page.
<?php
$connection = mysql_connect("localhost","root","");
mysql_select_db("scratchdisk",$connection);
$sql = "SELECT * FROM note";
$result = mysql_query($sql);
echo "<table>";
echo "<tr><td>#</td><td>Title</td><td>Action</td></tr>";
while($row=mysql_fetch_assoc($result)){
echo "<tr><td>".$row['#']."</td><td>".$row['Title']."</td><td><a href='view.php' id='view'>View</a></td></tr>"; }
echo "</table>";
?>
I want to display the next page base on my $row['#'] but the same view.php file.
You can use this code:
<?php
$connection = mysql_connect("localhost","root","");
mysql_select_db("scratchdisk",$connection);
$sql = "SELECT * FROM note";
$result = mysql_query($sql);
echo "<table>";
echo "<tr><td>#</td><td>Title</td><td>Action</td></tr>";
while($row=mysql_fetch_assoc($result)){
echo "<tr><td>".$row['#']."</td><td>".$row['Title']."</td><td><a href='view.php?id=" . $row['#'] . "' id='view'>View</a></td></tr>"; }
echo "</table>";
?>
In view.php
if(isset($_GET['id']) && !empty($_GET['id'])){
//Write logic here
$id = $_GET['id'];
}

How to call bootstrap modal in php

I'm trying to call a modal that I have in a html file which is hidden alongside another modal. One of them appears as the button is clicked but the other one is to be called by php as part of a verification process.
Here is my php code:
$File = include("index2.html");
$Msg = 'Welcome ';
$search=$_POST['search'];
$query = $pdo->prepare("SELECT * FROM students WHERE IDs LIKE '%$search%' LIMIT 0 , 10"); //OR author LIKE '%$search%'
$query->bindValue(1, "%$search%", PDO::PARAM_STR);
$query->execute();
// Display search result
if (!$query->rowCount() == 0) {
echo '<script type="text/javascript">';
echo 'alert("Verification Complete");';
echo '</script>';
while ($results = $query->fetch()) {
$Studname = $results['Studentname'];
echo '<script type="text/javascript">';
echo 'alert("'.$Msg.$Studname.'")';
echo '</script>';
echo '<script type="text/javascript">';
echo '$(File).ready(function() {';
echo '$("#myAdvert").modal("show");';
echo '});';
echo '</script>';
}
} else {
echo '<script language="javascript">';
echo 'alert("Sorry your ID was not found");';
echo 'window.location.href = "/Koleesy/index.html";';
echo '</script>';
}
?>
After the user is welcomed I want the hidden modal from my index.html to be called so the user can continue submitting the advert.
I've tried using the include function but that doesn't seem to work in my favor.
How do I do this?
Every answer is appreciated.
Try this:
echo "<script type='text/javascript'>
$(document).ready(function(){
$('#myAdvert').modal('show');
});
</script>";

how to show sql error message in a javascript alert box?

I have a code which insert some values into a database table. It is working properly. I wont to get errors like database connecting errors,duplicate entry. Here is my code.
Untitled Document
<body>
<?php
require '../classes/dbconnect.php';
$PId=$_POST["PatientId"];
$pName=$_POST["NameOfPatient"];
$age=$_POST["AgeOfPatient"];
$lId=$_SESSION['username'];
$fbs=$_POST["FBS"];
$sc=$_POST["Serum"];
$bu=$_POST["urea"];
$sgot=$_POST["sgot"];
$sgpt=$_POST["sgpt"];
$sa=$_POST["SAP"];
$sp=$_POST["protein"];
$sea=$_POST["albumin"];
$globulin=$_POST["globulin"];
$date=$_POST["date"];
$_SESSION['FBS'] = $fbs;
$db = new Database("localhost", "root", "", "mlab");
$x = $db->insert("INSERT INTO blood_report VALUES
('$PId','$lId','$date','$pName','$age','$fbs','$sc','$bu','$sgot','$sgpt','$s a','$sp','$sea','$globulin')");
if($x == 1){
header("Location:../bloodreport.php");
}else{
$str = "error :" . $db->err();
?>
<script>
var erro= '<?php echo "error :" . $db->err(); ?>';
</script>
<?php
//echo $str;
echo '<script type="text/javascript">alert("Duplicate entry");history.go(-1);</script>';
}
echo $x;
?>
try this way
......
if($x == 1){
header("Location:../bloodreport.php");
}else{
$str = "error :" . $db->err();
?>
<script>
var erro= <?php echo '"error : ' . $db->err() . '"'; ?>;
</script>
......
You can wrap each critical statement in try...catch block and logging error.
try {
$db = new Database("localhost", "root", "", "mlab");
} catch (Exception $e) {
$errString = $e->getMessage();
}
try {
$x = $db->insert("INSERT INTO blood_report VALUES
('$PId','$lId','$date','$pName','$age','$fbs','$sc','$bu','$sgot','$sgpt','$s a','$sp','$sea','$globulin')");
} catch (Exception $e) {
$errString = $e->getMessage();
}
EDIT
Later do :
<?php if (isset($errString) && $errString !== '') { ?>
<script>
var error = "<?php echo 'error : ' . $errString; ?>";
alert(error);
</script>
<?php } ?>
Also validate post before insertion http://php.net/manual/en/function.filter-input.php

how to fetch data from sql using form $_Post id in where clause

I am using a form with javascript which is used to add n numbers of rows dynamical and post data to mysql.
now i want to post more information to mysql using where clause (form data) in sql statement.
This is my code to submit and post data.
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;
$('#addNew').live('click', function() {
$('<p><select name="stockid[]' + i +'" onchange="showUser(this.value)"> <?php echo $item; ?></select> <select name="desc[]' + i +'" id="txtHint"> <?php echo $description; ?></ </select>Remove </p>').appendTo(addDiv);
i++;
return false;
});
$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>
<body>
<?php if (!isset($_POST['submit_val'])) { ?>
<h1>Add your Hobbies</h1>
<form method="post" action="">
<div id="container">
<p id="addNew"><span>Add New</span></p>
<div id="addinput">
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php } ?>
<?php
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description) VALUES ('$stockid[$a]','$desc[$a]')", $connection );
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
its working fine now when am trying to use a select statement and post data to mysql its not working
here is code
<?php
$con=mysqli_connect("localhost","root","","inventory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
}
mysqli_close($con);
?>
then i modify the post code of above file like this
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$price = $row['price'];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection);
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
but nothing is inserted in to database in price column
Change your code to store the price value in a new variable:-
<?php
$con=mysqli_connect("localhost","root","","inventory");
$price = array(); //declare
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
$price = $row['price']; //initiate
}
mysqli_close($con);
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid','$desc','$price')", $connection);
}
?>
Your $row['price'] variable will only exist within the while loop so you have to store it in something that is present beforehand and use that variable instead.
Assuming that both code snippets are in the same file, that is. Take a look over the code and see the changes on line 3 and line 27.
Also, as the other guys have said remove the double $$ and just use one on this line:-
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
Hope this is of some help to you :)
As said by aconrad in comments, replacing $$_POST by $_POST would probably solve your problem.
But I suggest you to change mysqli_query() to mysqli_prepare (and to change all mysql_* by the equivalent mysqli_* function)
I suggest you to transform all into mysqli_ and use prepared statements instead of direct query like this :
Change this:
<?php
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
to this:
<?php
$stmt = mysqli_prepare($con,"SELECT price FROM 0_stock_master where id = ?");
mysqli_stmt_bind_param($stmt, 'i', $_POST['stockid']);
$result = mysqli_stmt_execute($stmt);
if (!$result)
echo 'Mysql error : '.mysqli_stmt_error($stmt);
mysqli_stmt_bind_result($stmt, $price); // values will
mysqli_stmt_fetch($stmt); // this call send the result in $price
mysqli_stmt_close($stmt);
Change this:
<?php
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection );
to this :
<?php
$stmt = mysqli_prepare($connection, "INSERT INTO 0_stock_master (stock_id,description,price) VALUES (?, ?, ?)");
// I assume stock_id must be int, desc must be string, and price must be float
mysqli_stmt_bind_param($stmt, 'isf', $stockid[$a],$desc[$a],$price[$a]);
$query = mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
EDIT :
Some documentation:
MySQLi
mysqli_prepare (sql queries more protected from sql injection)
mysqli_stmt_bind_param
mysqli_stmt_execute
mysqli_stmt_bind_result
mysqli_stmt_fetch

Categories

Resources