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.
Related
i was coding a delete function called deleteProgram() inside a class and everything is working fine but i want to add some javascript code.
<?php
include_once 'db.inc.php';
class DeleteProgram extends Dbh{
public function deleteProgram(){
if(isset($_GET['deleteid'])){
$id = $_GET['deleteid'];
$sql = "DELETE FROM tblprogram WHERE id='$id';";
$result = $this->connect()->query($sql);
header("Location: ../php/program.php");
exit();
}
}
}
$delete = new DeleteProgram;
$delete->deleteProgram();
?>
So, this is what i did. I created a try/catch inside my deleteProgram() function inside the if statement and there i use an echo to run the javascript code. But it didn't display anything so that is where got stuck.
<?php
echo '<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>';
include_once 'db.inc.php';
class DeleteProgram extends Dbh{
public function deleteProgram(){
if(isset($_GET['deleteid'])){
$id = $_GET['deleteid'];
$sql = "DELETE FROM tblprogram WHERE id='$id';";
try{
$result = $this->connect()->query($sql);
echo '<style>.swal-text{
text-align: center;
}</style>';
echo '<script>swal("Deleted Successfully!", "Program has been deleted", "success");</script>';
header("Location: ../php/program.php");
exit();
}catch(PDOException $e){
echo '<style>.swal-text{
text-align: center;
}</style>';
echo '<script>swal ( "Delete failed!" , "'.$e->getMessage().'" , "error" );</script>';
exit();
}
}
}
}
$delete = new DeleteProgram;
$delete->deleteProgram();
?>
As suggested in comments, your code is open to SQL injections, try using parameterized prepared statements instead.
The header() function is redirecting the user before the page is loaded, so the script is written but never shown as the new page is now loaded right after.
One solution is to use the $_SESSION. It can go like this:
On your DeleteProgram class PHP file:
# [...]
session_start();
# [...]
if(isset($_GET['deleteid'])){
$id = $_GET['deleteid'];
$sql = "DELETE FROM tblprogram WHERE id='$id';";
try{
$result = $this->connect()->query($sql);
echo '<style>.swal-text{
text-align: center;
}</style>';
$_SESSION['swal'] = [
'title' => "Deleted Successfully!",
'message' => "Program has been deleted",
'status' => "success"
];
header("Location: ../php/program.php");
exit();
}catch(PDOException $e){
# [...]
}
}
# [...]
In the ../php/program.php file (somewhere in the <body>):
# [...]
session_start();
# [...]
<?php if(isset($_SESSION['swal'])) {
$title = $_SESSION['swal']['title'];
$message = $_SESSION['swal']['message'];
$status = $_SESSION['swal']['status'];
echo "<script>swal($title, $message, $status);</script>";
} ?>
May I also suggest you to not put CSS style in your code like that. It's not very reliable on where its gonna be written. As your swal() function requires you to place a <script> tag to be used, consider placing you <style> tag next to it or so.
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>';
}
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.
Well For Start I Want To Tank You All For The Help
The Script now it create a table but send empty info
so i have try to do like this:
http://mediaads.eu/villageop/back/savepoints.php?user_id=abcdefghijklm
Now The script wen i call it give me this error:
So I Have Edit The Script code to clean it
so now my code is:
<?php
header('Access-Control-Allow-Origin: *');
error_reporting(E_ALL);
ini_set('display_errors',1);
$servername = "localhost";
$username = "publiadd_publix";
$password = "1a3g7893fsh";
try {
$conn = new PDO("mysql:host=$servername;dbname=publiadd_registervillageop", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
echo "Connected successfully";
}
catch(PDOException $e){
echo "Connection failed: " . $e->getMessage();
}
if(isset($_GET['user_id'])){
//$user_id = intval($_GET['user_id']);
//Lightly sanitize the GET's to prevent SQL injections and possible XSS attacks
try {
$dbh = new PDO("mysql:host=$servername;dbname=publiadd_registervillageop", $username, $password);
$user_id = #$_GET['user_id'];
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // <== add this line
$sql = "INSERT INTO users (user_id) VALUES ('".$_POST["user_id"]."')";
if ($dbh->query($sql)) {
echo "<script type= 'text/javascript'>alert('New Record Inserted Successfully');</script>";
}
else{
echo "<script type= 'text/javascript'>alert('Data not successfully Inserted.');</script>";
}
$dbh = null;
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
$sql->execute(array($user_Id));
if($sql){
//The query returned true - now do whatever you like here.
echo 'Your ID was saved. Congrats!';
}else{
//The query returned false - you might want to put some sort of error reporting here. Even logging the error to a text file is fine.
echo 'There was a problem saving your points. Please try again later.';
}
}else{
echo 'Your id wasnt passed in the request.';
}
// close MySQL connection
$conn = null;
?>
<html>
<head>
</head>
<body>
<body bgcolor="#ffffff">
</body>
</html>
The method you are using in your forms is GET so use $_GET not $_POST as it goes in your if condition. So replace $_POST with $_GET and second error is your table name it is users table not publiadd_registervillageop so your sql query looks like,
$sql = "INSERT INTO users (user_id) VALUES ('".$_GET["user_id"]."')";
I'd appreciate some help in getting a simple demo working of the Twitter typeahead.js library as I've struggled with it over the last two days.
I'm using a MAMP development server on my Macbook, and have a (large) MySQL database table that I'd like to query to use with a typeahead field on a Web page.
This is my main HTML file that I'm using. It literally has one field in it.
type-ahead.php
<?php
// HTML5 Header stuff
echo '<!DOCTYPE html>'.PHP_EOL;
echo '<html>'.PHP_EOL;
echo '<head><meta charset="UTF-8">'.PHP_EOL;
echo '<title>Typeahead Example</title>'.PHP_EOL;
// include the two libraries for typeahead to work
echo '<script src="../jQuery/jquery-2.0.3.min.js" type="text/javascript"></script>'.PHP_EOL;
echo '<script src="../typeahead.js/typeahead.min.js" type="text/javascript"></script>'.PHP_EOL;
echo '</head>'.PHP_EOL;
echo '<body>'.PHP_EOL;
echo '<h2 class="myclass">Typeahead testing</h2>'.PHP_EOL;
echo 'Type in a search: <input type="text" name="user_search">'.PHP_EOL;
echo "<script type='text/javascript'>".PHP_EOL;
echo "$('#user_search').typeahead({".PHP_EOL;
echo " name: 'user_search',".PHP_EOL;
echo " remote: './type-ahead-ajax.php?query=%QUERY',".PHP_EOL;
//echo " minLength: 3,".PHP_EOL;
//echo " limit: 10".PHP_EOL;
echo "});".PHP_EOL;
echo "</script>".PHP_EOL;
echo '</body></html>'.PHP_EOL;
?>
The source of this from the browser looks OK, but I'll paste it here too just in case.
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8">
<title>Typeahead Example</title>
<script src="../jQuery/jquery-2.0.3.min.js" type="text/javascript"></script>
<script src="../typeahead.js/typeahead.min.js" type="text/javascript"></script>
</head>
<body>
Type in a search: <input type="text" name="user_search">
<script type='text/javascript'>
$('#user_search').typeahead({
name: 'user_search',
remote: './type-ahead-ajax.php?query=%QUERY',
});
</script>
</body></html>
I've tested my call back script separately, and it is definitely connecting to the database and pulling back some results. For example if I use '/type-ahead-ajax.php?query=bleach' as a URL, I get all the products containing the word 'bleach'
type-ahead-ajax.php
<?php
// Connect to the database
try {
$dbh = new PDO('mysql:host=localhost; dbname=menu;', 'root', 'root');
$query = '%'.$_GET['query'].'%'; // add % for LIKE query later
//$query = '%milk%'; //debug
echo $query.PHP_EOL;
// do query
$stmt = $dbh->prepare('SELECT title FROM waitrose WHERE title LIKE :query');
$stmt->bindParam(':query', $query, PDO::PARAM_STR);
$stmt->execute();
// populate results
$results = array();
foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $row) {
$results[] = $row;
echo strtolower($row).PHP_EOL; //debug
}
$dbh = null;
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
// and return to typeahead
return json_encode($results);
?>
Basically, when you type into the input field nothing happens. It's as though either the callback isn't being called, it's returning nothing, or it's not registered properly in the first place.
Any suggestions?
When you do $('#user_search'), you're referring to an element with id user_search. You haven't, however, given your input any id. Add it:
<input type="text" name="user_search" id="user_search">
If that doesn't work, make sure you get the data you assume by accesssing ./type-ahead-ajax.php?query=%QUERY manually with some query, and check for JavaScript errors in your browser console.