Ajax not calling alert - javascript

im successfuly inserted data to my db with ajax.. but somehow it does not pop up my success alert message. here is a sample of my jquery code.
$('button[name="submitmsgd"]').click(function(e){
var categorysupAr = [];
var unitsgdAr=[];
var idsgdAr=[];
var idsgdlength= $("input[name='idsgd[]']").val().length;
var namesgdAr= [];
var namesgdlength= $("input[name='namesgd[]']").val().length;
var detailsgdAr = [];
var qtysgdAr = [];
var pricesgdAr = [];
var totalsAr = [];
var datefield= $("input[name='datetime']").val();
$("select[name='categorysup[]']").each(function(){
categorysupAr.push(this.value);
});
$("select[name='unitsgd[]']").each(function(){
unitsgdAr.push(this.value);
});
$("input[name='idsgd[]']").each(function(){
idsgdAr.push(this.value);
});
$("input[name='namesgd[]']").each(function(){
namesgdAr.push(this.value);
});
$("textarea[name='detailsgd[]']").each(function(){
detailsgdAr.push(this.value);
});
$("input[name='qtysgd[]']").each(function(){
qtysgdAr.push(this.value);
});
$("input[name='pricesgd[]']").each(function(){
pricesgdAr.push(this.value);
});
$("input[name='totals[]']").each(function(){
totalsAr.push(this.value);
});
if ($.inArray("defaultc", categorysupAr)>-1){
e.preventDefault();
alert("Please choose the right category in all fields");
}
else if ($.inArray("defaultu", unitsgdAr)>-1){
e.preventDefault();
alert("Please choose the right unit in all fields");
}
else if ($.inArray("", idsgdAr)>-1||idsgdlength<=2){
e.preventDefault();
alert ("ID can't be empty, and must be more than 2 characters in all fields");
}
else if ($.inArray("", namesgdAr)>-1||namesgdlength<=2){
e.preventDefault();
alert ("Name can't be empty, and must be more than 2 characters");
}
else if ($.inArray("", totalsAr)>-1||$.inArray("0", totalsAr)>-1){
e.preventDefault();
alert ("Please make sure all quantity and all prices are filled with correct format(Only number allowed)");
}else{
$.ajax({
url: "include/insertmsgd.php",
method: "POST",
data:{category:categorysupAr, unitsgd:unitsgdAr, idsgd:idsgdAr, namesgd:namesgdAr, detailsgd:detailsgdAr, qtysgd:qtysgdAr, pricesgd:pricesgdAr, totals:totalsAr, datefield:datefield},
success: function (data) {
alert(data);
}
});
}
});
here is my php code:
<?php
include "myconfiguration.php";
if (isset($_POST["idsgd"])) {
$idsgd = $_POST["idsgd"];
$category = $_POST["category"];
$unitsgd = $_POST["unitsgd"];
$namesgd = $_POST["namesgd"];
$detailsgd = $_POST["detailsgd"];
$qtysgd = $_POST["qtysgd"];
$pricesgd = $_POST["pricesgd"];
$totals = $_POST["totals"];
$date = date('Y-m-d H:i:s', strtotime($_POST["datefield"]));
for($index=0; $index<count($idsgd); $index++) {
$idsgd_unstring = mysqli_real_escape_string($conn, $idsgd[$index]);
$category_unstring = mysqli_real_escape_string($conn, $category[$index]);
$unitsgd_unstring = mysqli_real_escape_string($conn, $unitsgd[$index]);
$namesgd_unstring = mysqli_real_escape_string($conn, $namesgd[$index]);
$detailsgd_unstring = mysqli_real_escape_string($conn, $detailsgd[$index]);
$qtysgd_unstring = mysqli_real_escape_string($conn, $qtysgd[$index]);
$pricesgd_unstring = mysqli_real_escape_string($conn, $pricesgd[$index]);
$totals_unstring = mysqli_real_escape_string($conn, $totals[$index]);
$query= '
INSERT INTO msgeneralgoods
VALUES("'.$idsgd_unstring.'", "'.$category_unstring.'", "'.$unitsgd_unstring.'", "'. $namesgd_unstring.'",
"'.$detailsgd_unstring.'", "'.$qtysgd_unstring.'", "'.$pricesgd_unstring.'", "'.$totals_unstring.'", "'.$date.'");
';
mysqli_query($conn, $query);
}
if (mysqli_query($conn, $query)) {
echo '<script language="javascript">';
echo 'alert("Data Inserted")';
echo '</script>';
} else {
echo '<script language="javascript">';
echo 'alert("Error")';
echo '</script>';
}
}
?>
i did try this code for my if condition inside my php page
if (mysqli_query($conn, $query)) {
echo 'Data Saved';
} else {
echo 'Error'
}
but still no alert message.... im very new to ajax, can some1 please tell me what did i do wrong here?

add error to the ajax call to return error if there is one
$.ajax({
url: "include/insertmsgd.php",
method: "POST",
data:{category:categorysupAr, unitsgd:unitsgdAr, idsgd:idsgdAr, namesgd:namesgdAr, detailsgd:detailsgdAr, qtysgd:qtysgdAr, pricesgd:pricesgdAr, totals:totalsAr, datefield:datefield},
success: function (data) {
alert(data);
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});

after thorough search in console and googling, i found out that my ajax call was canceled because my save button is
button type="submit"
so i change it to
button type="button"
that way i can see my alert pop up..
hope this help to whoever have the same problem as me

Related

Why is my alert not being displayed on success call

I am trying to work out why my alert in the 'function processResponse(data)' part of the code, is not being displayed. I have tried various return; options, but still, refuses to display.
I would be grateful if someone could point out my error. Many thanks.
PS. I am aware of security issues in the code posted such as mysql_escape_string, but all security issues will be inserted before the site goes live.
jQuery code
<script type="text/javascript">
$(function() {
$('#srcsubmit').click(function(e) {
e.preventDefault();
if ($('#srcBox').val() == '') {
notif({
type: "error",
msg: "<b>ERROR:<br /><br />You must enter a search term</b><p>Click anywhere to close</p>",
height: 99,
multiline: true,
position: "middle,center",
fade: true,
timeout: 3000
});
return false;
}
$("#submit").prop("disabled", true);
$("#submit2").prop("disabled", true);
$("#submit3").prop("disabled", true);
var value = $('#srcBox').val();
var dept = '<?php echo $_GET['dept ']; ?>';
var qString = 'sub=' + encodeURIComponent(value) + '&dept=' + encodeURIComponent(dept);
$.post('sub_db_handler.php', qString, processResponse);
});
function processResponse(data) {
if (data === 'true') {
alert('That box is not on the system'); <--- this is the problem
return;
}
$('#srcBoxRslt').val(data);
};
});
</script>
PHP backend
<?php session_start(); ?>
<?php
$con = mysql_connect("localhost","root","");
if(!$con) { die('Could not connect: ' . mysql_error()); }
mysql_select_db("sample", $con);
$dept = trim($_POST['dept']);
$custref = trim($_POST['sub']);
$result = mysql_query("SELECT * FROM boxes WHERE custref = '".$custref."'");
$found = mysql_num_rows($result);
if ($found == 0)
{
echo trim('true');
} else {
$query = "SELECT * FROM boxes WHERE department = '".$dept."' AND status = 1 AND custref = '".$custref."'";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
$r = $row['custref'];
$str = json_encode($r);
echo trim($str, '"');
}
?>
The data value is not equal to true because of extra space to get rid of extra use .trim()

How to add php form validation with ajax error handling

How can I add validation and php error handling with ajax. Now the success message come correctly but how can I implement error message on it? I might need to add some php validation please help.
Here is my JS.
$('#edit_user_form').bind('click', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function () {
$(".msg-ok").css("display", "block");
$(".msg-ok-text").html("Profile Updated Successfully!!");
},
error: function() {
//Error Message
}
});
});
PHP
<?php
require_once 'db_connect.php';
if($_POST) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$index_no = $_POST['index_no'];
$contact = $_POST['contact'];
$id = $_POST['id'];
$sql = "UPDATE members SET fname = '$fname', lname = '$lname', index_no = '$index_no', contact = '$contact' WHERE id = {$id}";
if($connect->query($sql) === TRUE) {
echo "<p>Succcessfully Updated</p>";
} else {
echo "Erorr while updating record : ". $connect->error;
}
$connect->close();
}
?>
ajax identifies errors based of status code, your php code will always return status code 200 which is success, even when you get error in php code unless its 500 or 404. So ajax will treat response as success.
if you want to handle php error, make following changes in your code
<?php
require_once 'db_connect.php';
if($_POST) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$index_no = $_POST['index_no'];
$contact = $_POST['contact'];
$id = $_POST['id'];
$sql = "UPDATE members SET fname = '$fname', lname = '$lname', index_no = '$index_no', contact = '$contact' WHERE id = {$id}";
if($connect->query($sql) === TRUE) {
echo "true";
} else {
echo "false";
}
$connect->close();
}
?>
$('#edit_user_form').bind('click', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function (res) {
if(res == 'true') {
//success code
} else if(res == 'false') {
//error code
}
},
error: function() {
//Error Message
}
});
});

JQUERY & PHP POST - show 00 in console.log

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

Using Ajax code to display a popup message when data get inserted in to the database

When submitting my form I need to check in the database whether chassis and pin exists. If it exists i need to display a pop up message through Ajax. This is my code. But i am not getting any pop up message if the data has been inserted or if there is any error.Can you guys help me figure out where I am going wrong? Thanks in advance for your help.
AJAX CODE :
<script type="text/javascript">
$(document).ready(function () {
$("#user_submit_form").submit(function () {
var user_data = $("#user_submit_form").serialize();
if ($('#chassis').val() == '') {
alert('Please enter chassis');
} else if ($('#pin').val() == '') {
alert('Please enter pin');
} else
{
$.ajax({
type: "post",
url: "validate_user.php",
data: user_data,
dataType: "json",
success: function (user_data) {
if (user_data == "Data inserted") {
alert("Data inserted");
} else {
alert("fail!");
}
}
}); // End ajax method
}
});
});
</script>
PHP CODE:
<?php
session_start();
$hostname = '*****';
$database = '****';
$username = '****';
$password = '*****';
$conn = mysql_connect($hostname,$username,$password);
if(!$conn){
die("Unable to Connect server!".mysql_error());
}
mysql_select_db($database) or die("Unable to select database!".mysql_error());
$sql = mysql_query('SELECT chassis,pin FROM checking_chassis WHERE chassis="'.$chassis.'" && pin="'.$pin.'" ');
if(mysql_num_rows($sql) == 1)
{
echo "Data inserted";
}
else
{
echo "Error";
}
?>
first do this after submitting and check
$("#user_submit_form").submit(function(e){
e.preventDefault();
});
and when alerting return false;
OR
pass data like this
$data = array(
'status' => 1,
'message' => 'Data inserted'
);
echo json_encode($data);
and in success function use
var json = $.parseJSON(user_data);
alert(json.message);
I am trying this now but I don't think that the value is getting returned. It is just printing the content of the else statement
<script type="text/javascript">
$(document).ready(function (){
$("#user_submit_form").submit(function(){
var user_data = $("#user_submit_form").serialize();
var mobile = new Array();
mobile = $('#mobile').val().split("");
var pincode = new Array();
pincode = $('#pincode').val().split("");
if($('#chassis').val() =='')
{
alert('Please enter chassis');
}
else if($('#pin').val() =='')
{
alert('Please enter pin');
}
else
{
$.post("validate_user.php",{"chassis":$('#chassis').val(),"pin":$('#pin').val(),"title":$('#title').val(),"fname":$('#fname').val(),"lname":$('#lname').val(),"email":$('#email').val(),"mobile":$('#mobile').val(),"dob":$('#dob').val(),"anniversary":$('#anniversary').val(),"company":$('#company').val(),"designation":$('#designation').val(),"home_business":$('#style').val(),"add1":$('#add1').val(),"add2":$('#add2').val(),"city":$('#city').val(),"state":$('#state').val(),"pincode":$('#pincode').val()},function(data) {
if(data == true)
{
alert("Error");
}
else
{
alert("Success");
}
});
}
});
});
</script>

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