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");
}
}
Related
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);
?>
I make this jquery to call a php file via post. I put a console.log to see the return of the Ajax. At moment return 00.
I'm not sure what it is the problem?
The code is:
$('input[type="submit"]').click(function(event){
event.preventDefault();
// Get the value of the input fields
var inputvalue = $(this).attr("value");
$.ajax({
url:"updateEstado2.php",
type:"POST",
data:{"codigo": inputvalue},
dataType:"text",
success:function(data){
console.log(data);
alert(inputvalue);
}
});
});
The PHP code:
<?php
session_start();
if(isset($_SESSION['username']) and $_SESSION['username'] != ''){
include("db_tools.php");
$conn = dbConnect("localhost", "5432", "dbname", "dbuser", "dbpass");
$estado = $_POST["estado"];
$codigo = $_POST["codigo"];
$query = "UPDATE produccion.ma_producto SET estado={$estado} WHERE codigo={$codigo}";
$result = pg_query($conn, $query);
if ($result == TRUE) {
header('Location: produccio.php');
} else {
echo "Error updating record: " . pg_last_error($conn);
}
pg_close($conn);
} else{
?><p>La sessió no està activa, si us plau ingresa aquí</p>
The alert window show the value of the variable correctly but the console.log show 0. I do not understand well...
Please Could you help me.
Please edit statement after if condition.
if ($result == TRUE) {
echo 'Done';
} else {
echo "Error updating record: " . pg_last_error($conn);
}
I have a remove page where it can remove an entry from my database which is pre loaded into the option box. However, it redirects to my 'remove-module-complete.php' page when I type in any random text. I only want it to direct to the 'remove-module-complete.php' if their is that actual entry from the database. My javascript doesn't seem to be working.
I currently have some validation to say that the entry 'didnt match any item' from jQuery but it still directs me to 'module remove complete' if I press submit.
Any help?
Here is my PHP
<?php
if (isset($_POST['submit'])){
$moduleCode = $_POST['moduleCode'];
$moduleCodeLen = strlen($moduleCode);
if ($moduleCodeLen=6){
$sqlTwo = "DELETE FROM MODULES WHERE id = '$moduleCode'";
mysql_query($sqlTwo);
$resTwo =& $db->query($sqlTwo);
if(PEAR::isError($res)){
$errorVar = ($res->getMessage());
echo "<script type='text/javascript'>alert('Invalid entry, please try again. Error code: $errorVar');</script>";
die;
}
else echo "<script> location.replace('http://project.ac.uk/remove-module-complete.php'); </script>";
}
else echo "<script type='text/javascript'>alert('Invalid entry, please try again');</script>";
}
?>
Seems like you have some errors(commented lines):
if (isset($_POST['submit'])) {
$moduleCode = $_POST['moduleCode'];
$moduleCodeLen = strlen($moduleCode);
// '==', not '='
if ($moduleCodeLen==6) {
$sqlTwo = "DELETE FROM MODULES WHERE id = '$moduleCode'";
mysql_query($sqlTwo);
$resTwo =& $db->query($sqlTwo);
// there is no $res variable in the given part of the code
// maybe you need to use $resTwo variable here?
if (PEAR::isError($res)) {
$errorVar = ($res->getMessage());
echo "<script type='text/javascript'>alert('Invalid entry, please try again. Error code: $errorVar');</script>";
die;
}
else echo "<script> location.replace('http://project.ac.uk/remove-module-complete.php'); </script>";
}
else echo "<script type='text/javascript'>alert('Invalid entry, please try again');</script>";
}
Im trying to do a recover password system with jQuery messages and Im having a problem.
The code below is working fine, when I click in the button to recover my username and password I get the message <p class="sucess">Email sent with your data..</p>.
But I want to put the email of the user in the message. Like this:
<p class="sucess">Email sent with your data for email#example.com!</p>
Im trying like this in my php
else {
echo 'sucess'; //here I show the jQuery message
echo $result['email']; //and then I want to show my $result['email']
return;
}
I already try like this:
echo 'sucess'.$result['email'].'';
But I have always the same problem, Im entering here in my jQuery:
else
{
alert('Error in system');
}
And if I dont put this echo in $result['email'] the sucess message works fine, but when I try to echo my $result['email'] Im always entering in this jQuery condition.
Somebody there have any idea why this is happening?
My php:
switch ($action){
case 'recover':
$email = $_POST['email'];
if($email == ''){
echo 'errorempty';
}else{
$searchEmail = $pdo->prepare("SELECT * FROM admins WHERE email=:email");
$searchEmail->bindValue(":email", $email);
$searchEmail->execute();
$num_rows = $searchEmail->rowCount();
$result = $searchEmail->fetch(PDO::FETCH_ASSOC);
if($num_rows <=0 )
{
echo 'erroremail';
return;
}
else {
echo 'sucess';
echo $result['email'];
return;
}
}
break;
default:
echo 'Error';
}
}
My jQuery:
$('#recover').submit(function(){
var login = $(this).serialize() + '&action=recover';
$.ajax({
url: 'switch/login.php',
data: login,
type: 'POST',
success: function(answer){
if(answer== 'erroempty'){
$('.msg').empty().html('<p class="warning">Inform your email!</p>').fadeIn('slow');
}
else if (answer == 'erroemail'){
$('.msg').empty().html('<p class="error">Email dont exist!</p>').fadeIn('slow');
}
else if(answer == 'sucess'){
$('.msg').empty().html('<p class="sucess">Email sent with your data..</p>').fadeIn('slow');
window.setTimeout(function(){
$(location).attr('href','dashboard.php');
},1000);
}
else{
alert('Error in system');
}
},
beforeSend: function(){
$('.loginbox h1 img').fadeIn('fast');
},
complete: function(){
$('.loginbox h1 img').fadeOut('slow');
},
error: function(){
alert('Error in system');
}
});
return false;
});
you can simple echo the $email like this
$email=$result["email"];
echo $email;
then in ajax success function
if(answer.email)
{
$('.msg').empty().html('<p class="sucess">Email sent with your data..'+answer.email+'</p>').fadeIn('slow');
}
The problem is, that you server side is returning just unstructured data and the client side part will just receive a plain string like sucessdummy#example.com in the answer variable.
This answer variable is compared with strings that do not match thought your script ends in the error case. I would go for a solution by returning some kind of structured data like json.
Your server side code could look something like
$result = array('msg'=>'success','mail'=>$result['email']);
header('Content-type: application/json');
echo json_encode($result);
You have to pass the dataType:'json' option in your jquery ajax call to make it work and can access the data in the call back function like answer.msg, answer.mail
How can I have an alert that the form has been submitted successfully? I have already tried to look at the page of the plugin still come up empty handed.
This is the code I have tried so far maybe there is something wrong with my syntax:
<script type="text/javascript">
$(document).ready(function(){
$('#f1').ajaxForm({
success: function(){
alert("Form successfully submitted");
}
});
});
</script>
The code above works and successfully inserted all the data in the forms but the alert that suppose to appear after successfully submitted the form is missing for some reason.
This is the script that the form uses when submitting:
<?php
$title=$_REQUEST['articletitle'];
$articlemore=$_REQUEST['editor1'];
include "connection.php";
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0)
{
$type=$_FILES['image']['type'];
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO blog(articletitle, articleimage, articlemore) VALUES ('$title', '$data', '$articlemore')";
$results = mysqli_query($link, $query);
if(!$results)
{
echo "Saving Post Failed";
}
else
{
echo "You have a new Post!";
}
}//end if that checks if there is an image
else
{
echo "No image selected/uploaded";
}
// Close our MySQL Link
mysqli_close($link);
?>
Here is the Syntax
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
I hope this will help you
Change this:
$('#f1').ajaxForm({
to
$('#f1').ajaxForm(function(){