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

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

Related

how to store php variable passed as id to javascript in a javascript variable

I am trying to pass div id to javascript and print it out on console as :
<?php echo 67;?>
The 67 is id here. I was wondering how can I store this value in my javascript variable storeid as var storeid = 67?
My code:
echo "<h2 class='editme' id='<?php echo $id;?>' contentEditable='true'> Hello</h2>";
echo "<script>
$('h2.editme').click(function(){
console.log(this.id);
var storeid;
});
</script>";
Also, I want to use that id value to update the values in my sql. I can only test my code once I could somehow get the value of that id. How can I store the value of the id to javascript variable?
My code (This is to update sql once I get the id) - Not sure if it's right I can test it after getting id value:
echo "<h2 class='editme' id='<?php echo $id;?>' contentEditable='true'> Hello</h2>";
echo "<script>
$('h2.editme').click(function(){
var content2 = $(this).html();
console.log(this.id);
var storeid;//once I get the id
$.ajax({
url: 'updateDescription(storeid, content2)',
success: function(respon) {
$('.editme').html(respon);
}
});
});
</script>";
function updateDescription($user_unique_id, $content2)
{
try {
require "testing.php";
$sql = "UPDATE icecream SET
desc = :desc
WHERE id = :id";
$stmt->bindParam(':desc', $content2, PDO::PARAM_STR);
$stmt->bindParam(':id', $user_unique_id);
$stmt->execute();
echo 'Record updated';
} catch (PDOException $e) {
echo 'Connection failed ' . $e->getMessage();
}
}
this way:
echo '<script>
var storeid = '. $id .'
</script>';
more readable way:
// somefile.php
<?php
$id = 67;
?>
<h2 class='editme' id='<?php echo $id;?>' contentEditable='true'> Hello</h2>
<script>
var storeid = <?php echo $id; ?>
// rest of javascript code
</script>
<?php
// rest of the php code

Alert() javascript function not working in php

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);
}
}
?>

How to avoid the new line and extra space issue? Because I have contionously getting this error "unterminated string literal"

This is my onchange function, But i keep getting this error SyntaxError: unterminated string literal
function OrganizationPrefill(type){
if(type == 'org' ){
var orgdts = "<?php echo $orgDets['state']; ?>";
var myStr = "<?php echo $orgDets['address']; ?>";
var newStr = myStr.replace('\n', '');
$('#states option[data='+orgdts+']').prop('selected','selected');
$("#address").val(newStr);
$("#zip").val("<?php echo $orgDets['zip']; ?>");
$("#city").val("<?php echo $orgDets['city']; ?>");
}else if(type == 'orguser'){
var myStr1 = "<?php echo $doctorDets['address']; ?>";
var newStr1 = myStr.replace('\n', '');
$("#address").val(myStr1);
$("#zip").val("<?php echo $doctorDets['zip']; ?>");
$("#city").val("<?php echo $doctorDets['city']; ?>");
$('#states').val("<?php echo $doctorDets['state']; ?>");
}
}
This is the address that I have in my database
Al Ameen
CCNA street
uzbaskistan
I want these 3 things in a single line, I already tried trim,str_replace but cant get the correct solution can anyone please assit me
What I need is ==>
Al Ameen CCNA street uzbaskistan
Thanks Everyone, Now its Working. This is my answer
function OrganizationPrefill(type){
if(type == 'org' ){
var orgdts = "<?php echo $orgDets['state']; ?>";
<?php $orguserAddr = str_replace(array("\n", "\r"), ' ', $orgDets['address']); ?>
$("#address").val("<?php echo $orguserAddr; ?>");
$('#states option[data='+orgdts+']').prop('selected','selected');
$("#zip").val("<?php echo $orgDets['zip']; ?>");
$("#city").val("<?php echo $orgDets['city']; ?>");
}else if(type == 'orguser'){
<?php $userAddr = str_replace(array("\n", "\r"), ' ', $doctorDets['address']); ?>
$("#address").val('<?php echo $userAddr; ?>');
$("#zip").val("<?php echo $doctorDets['zip']; ?>");
$("#city").val("<?php echo $doctorDets['city']; ?>");
$('#states').val("<?php echo $doctorDets['state']; ?>");
}
}

Send data from both php and js to php

I want to send data from php to php and in same time I also want to send data from js to php. I have one index.php which contains php and js part. In enrolled.php I want to collect my data. SQL injection or other security problems are not important. I do not get any error but it does not save to database.
Small part of index.php
<!DOCTYPE html>
<html lang="en">
<head>
//smt....Not important
</head>
<body>
//smt....Not important
<div id="dom-target" style="display: none;">
<?php
include_once "connection.php";
session_start();
$username = $_SESSION['username'];//coming from previous page.
echo htmlspecialchars($username); //for sending variable from php to js.
?>
</div>
<script type = "text/javascript">
$('#addmore').click(function(){
var subjectone = $('#selectedsubjectone :selected').val();
var courseone = $('#courseListone').val();
var gradeone = $('#selectedGradeOne :selected').val();
var div = document.getElementById("dom-target");
var username = div.textContent;//these lines help to gett data from php
document.getElementById("usernamee").innerHTML = username;//for checking
$.ajax({
type: "POST",
url: "addenrolled.php",
data: {
// Send the username (js, not php)
username: username,
subject: subjectone,
course: courseone,
grade: gradeone
}, success: function(data) {
alert("sucess");
}
});
});
</script>
</body>
</html>
enrolled.php
<?php
include_once "connection.php";
$nick = $_POST['username'];
$subject=$_POST['subject'];
$course=$_POST['course'];
$grade=$_POST['grade'];
echo "$nick -- $subject -- $course -- $grade"; //for checking
$prep = $con->prepare("INSERT INTO enrolledtable ('nickname', 'subject', 'course', 'grade') VALUES(?,?,?,?)");
$prep->bind_param("ssss", $nick, $subject, $course, $grade);
$send = $prep->execute();
if ($send == TRUE) {
echo "Courses added successfully";
header('Location: index.php');
exit();
} else {
echo "Error: " . $con->error;
header('Location: index.php');
exit();
}
?>
Change your jQuery to this
<script>
$(document).ready(function(){
$('#addmore').click(function(){
var subjectone = $('#selectedsubjectone :selected').val();
var courseone = $('#courseListone').val();
var gradeone = $('#selectedGradeOne :selected').val();
$.post('enrolled.php', {subjectone: subjectone, courseone: courseone, gradeone: gradeone, addmore: "yes"}, function(response){
console.log(response);
})
});
});
</script>
Then in your PHP modify the prepare statement to the following
$prep = $conn->prepare("INSERT INTO enrolledtable (`nickname`, `subject`, `course`, `grade`) VALUES(?,?,?,?)");
$prep->bind_param("ssss", $nick, $subject, $course, $grade);
$send = $prep->execute();
enrolled.php
<?php
session_start();
include_once "connection.php";
if (isset($_POST['addmore'])) {
$nick = $_SESSION['username'];
$subject=$_POST['subjectone'];
$course=$_POST['courseone'];
$grade=$_POST['gradeone'];
// //echo "$nick -- $subject -- $course -- $grade"; //for checking
$prep = $conn->prepare("INSERT INTO enrolledtable (`nickname`, `subject`, `course`, `grade`) VALUES(?,?,?,?)");
$prep->bind_param("ssss", $nick, $subject, $course, $grade);
$send = $prep->execute();
if ($send == TRUE) {
echo "Courses added successfully";
// header('Location: index.php');
exit();
} else {
echo "Error: " . $con->error;
//header('Location: index.php');
exit();
}
}
?>

Javascript error message not showing in php

First time posting here so be kind!
For some reason when my php script reaches the
if ($beds == 'nopref')
the only way I can get the message to display is with echo $message.
The following line with javascript won't display it like my other pages.
Any ideas?
CODE:
<?php
$beds = $_POST['beds'];
$orientation = $_POST['orientation'];
$checkin = $_POST['checkin'];
$checkout = $_POST['checkout'];
$conn = mysqli_connect("localhost", "user", "password", "name");
if(!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
if ($beds == 'nopref')
{
$message = "Please select how many beds you'd like";
echo $message;
echo "<script type='text/javascript'>alert('$message');</script>";
}
?>
You have broken text because of ' in you'd. Try this:
$message = htmlspecialchars("Please select how many beds you'd like", ENT_QUOTES);
You can escape a ' in JavaScript like \'
if ($beds == 'nopref')
{
$message = "Please select how many beds you\'d like";
echo $message;
echo '<script>alert("'.$message.'");</script>';
}
try this
print "<script type='text/javascript'>window.alert('$message');</script>";
or
print "<script type='text/javascript'>window.alert('Please select how many beds you had like');</script>";
Try this code:
<?php
$message=htmlspecialchars("Hello World's",ENT_QUOTES);
echo "<script>alert('$message')</script>";
?>

Categories

Resources