javascript alert in an if else statement not triggering - javascript

If the first part of the statement fails I am trying to send an alert. But I cannot figure out why the alert is not triggering. Yes, I have forced the statement to fail.
$("#btnSubmit").click(function (e)
{
if (<?php echo $browser; ?> >= 1)
{
var user = $("#ownerPost input").val();
var oid = <?php echo $Owner; ?>;
$.ajax(
{
type: 'POST',
url: 'follow.php',
data: "oid="+oid,
dataType: 'json',
success: function(data)
{
var id = data[0];
var name = data[1];
$('#output2').html("<b>id: </b>"+id+"<b> name: </b>"+name);
}
}
);
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
}
else
{
alert("You must log in to follow");
}
}
);
Here is the output from view source:
The actual number is 56 and makes the statement true and that is correct. It is when the statement is false that it will not trigger the else and hence the alert.
If I place an alert right before the else it will show the alert because first part is true.
$("#btnSubmit").click(function (e)
{if (56 >= 1){
var user = $("#ownerPost input").val();
var oid = 56;
$.ajax({
type: 'POST',
url: 'follow.php',
data: "oid="+oid,
dataType: 'json',
success: function(data){
var id = data[0];
var name = data[1];
$('#output2').html("<b>id: </b>"+id+"<b> name: </b>"+name);} });
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
}else{alert("You must log in to follow");}});

I think you have a syntax error. I was going to suggest a try/catch, but that will not help with a syntax error. Please edit your question and put in the "view > page source" as the others have suggested. Also, can you use Firebug, or equivalent to view the console?
EDIT:
I do get the alert with this code. Note that I set browser to 0.
blah = function(e) {
if (0 >= 1) {
var user = $("#ownerPost input").val();
var oid = 56;
$.ajax({
type : 'POST',
url : 'follow.php',
data : "oid=" + oid,
dataType : 'json',
success : function(data) {
var id = data[0];
var name = data[1];
$('#output2')
.html("<b>id: </b>" + id + "<b> name: </b>" + name);
}
});
$("#output").html("<b>You are now following: </b>" + user);
e.preventDefault();
} else {
alert("You must log in to follow");
}
};
blah.call();

Related

Check any data after confirmation message using JSON

I want to make the data alert successfully saved or fail after the user selects on the confirmation message. In this case data checking occurs after the user confirms the message I made.
This is my Javascript Code :
$('#add-btn').on('click', function(event){
var confirmation = confirm("Do you want to save ?");
if (confirmation == true) {
var code = $('#code').val();
var name = $('#name').val();
var unit = $('#unit').val();
var price_code = $('#price_code').val();
var type = $('#type').val();
var final = $('#final').val();
var dataString = 'code=' +code+ '&unit=' +unit+ '&price_code=' +price_code+ '&type=' +type;
if (code != '' && name != '' && unit != '' && price_code != '' && type != '' && final != ''){
event.preventDefault();
$.ajax({
type: "POST",
url: "../public/process/add_data.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
if(data.status == 'success'){
alert("Success !");
}
else if(data.status == 'error'){
alert("Data already used !");
}
}
});
}
else{
alert('Please fill all fields !');
}
}
});
All input success to save but the alert cannot show.
I think problem in your php file. your JOSN data is not in correct format that you received in success.Please try this in your add_data.php file
//All code goes here and after insert try this
$array = array();
if(if data insert successfully) {
$array['status '] = 'success';
} else {
$array['status '] = 'error';
}
header('Content-Type: application/json');
echo json_encode($array);
The success function is only executed if everything went well. If there has been any error, you need to add the Ajax failure function as follows:
$.ajax({
type: "POST",
url: "../public/process/add_data.php",
data: dataString,
dataType: "json",
cache: false,
success: function(data){
alert("Success !");
}
}).fail(function () {
alert("Data already used !");
});
finally I find my solution. I'm sorry for my carelessness.
That happened because my variable dataString did not complete.
It should be :
var dataString = 'code=' +code+ '&name=' +name+ '&unit=' +unit+
'&price_code=' +price_code+ '&type=' +type+ '&final=' +final;
Thank you all for your kindness :-)

Check the value of a text input field with ajax

I have a website where the log ins are screen names. On the create user form I want to be able to have ajax check if a screen name exists already as it is typed into the form.
This is the HTML form input field
<label for="screenName">Screen Name:
<input type="text" class="form-control" name="screenName" id="screenName" size="28" required>
<div class="screenNameError"></div>
A message should be displayed in the <div class="screenNameError"></div>line if the username matches the database.
This is my Jquery code for this.
$(document).ready(function(){
if ($('#screenName').length > 0){
var screenName = $("input").keyup(function(){
var value = $(this).val();
return value;
})
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
This is the PHP file that gets called to make the DB query
$screenName = $_POST['Screen_Name'];
$screenNameSQL = "SELECT Screen_Name FROM Users WHERE Screen_Name = '$screenName'";
$result = $my_dbhandle->query($screenNameSQL); //Query database
$numResults = $result->num_rows; //Count number of results
$resultCount = intval($numResults);
if($resultCount > 0){
echo "The username entered already exists. Please a different user name.";
}
For some reason my Jquery is not firing when I type the username in the form :/
Thanks in advance
Try changing your jQuery to this -
$(document).ready(function() {
$('#screenName').keyup(function() {
var value = $(this).val();
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
});
});
However you probably want to minimise the number of ajax requests being made so I would advise putting your ajax request into a setTimeout functon and clearing it with each subsequent keypress. -
$(document).ready(function() {
var ajaxRequest;
$('#screenName').keyup(function() {
var value = $(this).val();
clearTimeout(ajaxRequest);
ajaxRequest = setTimeout(function(sn) {
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + value,
success: function(r) {
$('.screenNameError').html(r);
}
});
}, 500, value);
});
});
if ($('#screenName').length > 0){
You should change it with
if ($('#screenName').val().length > 0){
OR
var name = $('#screenName').val();
if(name.length >0) {...
not sure about the syntax...
Add an event on keyup like this :
Edit
$("#screenName").on("keyup",function(){
var screenName=$(this).val();
if(screenName!='')
{
$.ajax({
type: 'post',
url: 'screenNameCheck.php',
data: 'Screen_Name=' + screenName,
success: function (r) {
$('.screenNameError').html(r);
}
})
}
});
JsFiddle
Your ajax call should be inside the keyup handler.

Ajax not working well

I'm trying to submit a form using Ajax , but it doesn't work here is my Ajax :
$(document).ready(function(){
$("#submit").click(function(event){
var ad1 = $("#ad1").val();
var ad2 = $("ad2").val();
var city = $("city").val();
var state = $("state").val();
var zip = $("zip").val();
var country = $("country").val();
var mm = $("mm").val();
var dd = $("dd").val();
var yy = $("yy").val();
var lname = $("lname").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name1='+ name + '&ad11='+ ad1 + '&ad21='+ ad2 + '&city1='+ city + '&state1='+ state + '&zip1='+ zip + '&country1='+ country + '&mm1='+ mm + '&yy1='+ yy + '&dd1='+ dd + '&lname1=';
if(name=='')
{
alert("");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
and it's not giving any result just giving data in header
the result is like :
I copied the javascript to the form page it's now working ,but the ajax is returning a blank alert while it should be "Form Submitted Succesfully"
I guess that it's an error of inclusion of the file , but i'm using the right directories.
here is action.php :
<?php
$con = mysqli_connect("server","user","pass","db");
$name=$_POST['name1'];
$ad1=$_POST['ad11'];
$ad2=$_POST['ad21'];
$city=$_POST['city1'];
$state=$_POST['state1'];
$zip=$_POST['zip1'];
$country=$_POST['country1'];
$mm=$_POST['mm1'];
$dd=$_POST['dd1'];
$yy=$_POST['yy1'];
$dob=$dd."/".$mm."/".$yy;
$mm=$_POST['mm1'];
$name=$_POST['name1'];
$lname=$_POST['lname1'];
$r2=rand(10000,90000);
$query = mysqli_query($con,"insert into users values('$r2','$name','$lname','$ad1','$ad2','$city','$state','$zip','$country','$dob')");
mysqli_close($con);
echo "Form Submitted Succesfully";
?>
This name variable is not have defined in ajax file var dataString = 'name1='+ name + so name would be an empty string
=> if(name=='')
{
alert("");
} executed. Please add string into alert and check again :)

when fast cliking on like button getting unknown likes

i am working on project which have like unlike function look like facebook but i am getting stuck when i click multiple time at once on like button or unlike button then its work like firing and if i have 1 or 2 like and i click many time fast fast then my likes gone in -2 -1. how i solve this issue ? if when click many time always get perfect result. below my jquery script
$(document).ready(function () {
$(".like").click(function () {
var ID = $(this).attr("idl");
var REL = $(this).attr("rel");
var owner = $(this).attr("owner");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL + '&owner=' + owner;
$.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false,
success: function (html) {
if (REL == 'Like') {
$('.blc' + ID).html('Unlike:').attr('rel', 'Unlike').attr('title', 'Unlike');
$('.spn' + ID).html(html);
} else {
$('.blc' + ID).attr('rel', 'Like').attr('title', 'Like').html('Like:');
$('.spn' + ID).html(html);
}
}
});
});
});
It is because of the async nature of ajax request.... when you click on the element continuously... the click event will get fired before the response from previous request come back and the link status is updated to next one
Case:
Assume the rel is unlike, then before the response came back again another click happens so the rel is not yet updated so you are sending another unlike request to server instead of a like request
Try below solution(Not Tested)
$(document).ready(function () {
var xhr;
$(".like").click(function () {
var ID = $(this).attr("idl");
var REL = $(this).attr("rel");
var owner = $(this).attr("owner");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL + '&owner=' + owner;
if (REL == 'Like') {
$('.blc' + ID).html('Unlike:').attr('rel', 'Unlike').attr('title', 'Unlike');
} else {
$('.blc' + ID).attr('rel', 'Like').attr('title', 'Like').html('Like:');
}
//abort the previous request since we don't know the response order
if (xhr) {
xhr.abort();
}
xhr = $.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false
}).done(function (html) {
$('.spn' + ID).html(html);
}).always(function () {
xhr = undefined;
});
});
});
Set a variable, we'll call it stop and toggle it.
$(document).ready(function () {
var stop = false;
$(".like").click(function () {
if (!stop)
{
stop = true;
var ID = $(this).attr("idl");
var REL = $(this).attr("rel");
var owner = $(this).attr("owner");
var URL = 'box_like.php';
var dataString = 'msg_id=' + ID + '&rel=' + REL + '&owner=' + owner;
$.ajax({
type: "POST",
url: URL,
data: dataString,
cache: false,
success: function (html) {
if (REL == 'Like') {
$('.blc' + ID).html('Unlike:').attr('rel', 'Unlike').attr('title', 'Unlike');
$('.spn' + ID).html(html);
} else {
$('.blc' + ID).attr('rel', 'Like').attr('title', 'Like').html('Like:');
$('.spn' + ID).html(html);
}
}
}).always(function() { stop = false; });
}
});
});

my javascript code will not proceed to delete my data from jqGrid

just want to ask regarding my javascript code. I have a function that will delete and edit a data in my jqgrid. But everytime i run my code, it will not delete and edit if I dont put an alert in some portion of the code. Why is it happening? How can i make my program run without the alert?
Below is my delete function:
function woodSpeDelData(){
var selected = $("#tblWoodSpe").jqGrid('getGridParam', 'selrow');
var woodID='';
var woodDesc='';
var codeFlag = 0;
var par_ams = {
"SessionID": $.cookie("SessionID"),
"dataType": "data"
};
//this part here will get the id of the data since my id was hidden in my jqgrid
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'getData/woodSpecie',json:JSON.stringify(par_ams)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$.each(data['result']['main']['rowdata'], function(rowIndex, rowDataValue) {
$.each(rowDataValue, function(columnIndex, rowArrayValue) {
var fldName = data['result']['main']['metadata']['fields'][columnIndex].name;
if (fldName == 'wood_specie_id'){
woodID = rowArrayValue;
}
if (fldName == 'wood_specie_desc'){
woodDesc = rowArrayValue;
alert($('#editWoodSpeDesc').val() +' '+ woodDesc); //program will not delete without this
if(selected == woodDesc){
codeFlag =1;
alert(woodID); //program will not delete without this
};
}
});
if (codeFlag == 1){
return false;
}
});
if (codeFlag == 1){
return false;
}
}
}
});
alert('program will not proceed without this alert');
if (codeFlag == 1) {
var datas = {
"SessionID": $.cookie("SessionID"),
"operation": "delete",
"wood_specie_id": woodID
};
alert(woodID);
alert(JSON.stringify(datas));
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'delete/woodSpecie',json:JSON.stringify(datas)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$('#tblWoodSpe').trigger('reloadGrid');
}
}
});
}
}
EDIT
My main purpose of putting an alert was just to know if my code really get the right ID of the description, and if would really go the flow of my code... But then i realized that it really wont work with it.

Categories

Resources