How to make javascript prompt box cancel button to do nothing? - javascript

How can I make cancel button in javascript prompt box to do nothing like the cancel button on confirmation box instead of sending "null" values?
Or is it possible to remove the cancel button from the prompt box so there is only "ok" button left?
This is what I have tried but it still sends the null to value to my PHP file.
function AskQuestion(data)
{
var id = getUrlVars()["id"];
console.log(data);
if(data.key[0].status == "ok") {
var reply = prompt(data.key[0].REPLY, "");
var index = data.key[0].IND;
if(reply != "" && reply !== null) {
//do nothing
}else{
jQuery.ajax({ type: "POST",
url: serviceURL + "message.php",
data: 'id='+id+'&arvo='+reply+'&index='+index,
cache: false,
success: AskQuestion});
}
} else {
window.location = "page.html"
}
}

You've got your test on the return value the wrong way around. As it is you // do nothing when the user enters text, and call ajax when they don't. Change
if(reply != "" && reply !== null) {
// do nothing
to
if(reply == null || jQuery.trim(reply).length == 0) {
// do nothing

A few ideas:
reply = jQuery.trim( prompt(...) || "" );
if( reply ){
jQuery.ajax(...)
}

You can just return to exit the function

Related

javascript code sends and receives data only once

Welcome,
I am weak in javascript
I created code that does the following work:
When clicking on the preferred product icon, the data (product number, user, etc.) will be sent to the database
Everything is working fine.
The problem is that when I click on the heart sign again, it does not send again (delete favorite).
I hope the problem is clear.. I want the JavaScript code to run more than once and not stop at one use
if($('#shopping-form').length){
var o = new Object();
var form = '#shopping-form';
var authintication_us = $('#shopping-form .authintication_us').val();
var authintication_tbs = $('#shopping-form .authintication_tbs').val();
var p_id = $('#shopping-form .p_id').val();
var typ = $('#shopping-form .typ').val();
$('#AddPv').click(function(){
event.preventDefault();
var fybtn=document.getElementById("AddPv");
if(authintication_us == '' || authintication_tbs == '' || p_id == '' || typ == '')
{ return false; }
$.ajax({
url:"like.php",
method:"POST",
data: $(form).serialize(),
success:function(data){
$('#AddPv').addClass('active');
fybtn.setAttribute("id","RemPv");
},
error:function(){
return false;
}
});
});
$('#RemPv').click(function(){
event.preventDefault();
var fybtn=document.getElementById("RemPv");
if(authintication_us == '' || authintication_tbs == '' || p_id == '' || typ == '')
{ return false; }
$.ajax({
url:"like.php",
method:"POST",
data: $(form).serialize(),
success:function(data){
$('#RemPv').removeClass('active');
fybtn.setAttribute("id","AddPv");
},
error:function(){
return false;
}
});
});
}
When it sends data (send favourite) it switches the identifier to the one with which I can delete the data (delete favourite
this is my html code:
<span class="fav-btn" id="AddPv" > <i class="fas fa-heart"></i> </span>
As for the rest of the data, it will receive it from pre-existing inputs
The code really works..but the problem is that I couldn't make it work more than once..you can give me an example of how likes and dislikes work like on Facebook so that I can solve the problem myself

typeof isn't working as expected with ajax response

I'm trying to create simple form validation with AJAX and PHP but the usage of typeof is not working as expected.
It works well unless I'm getting an empty response which means all fields have passed the validation.
In that case, nothing happens and the last input remains with its error classes and Cart div is not changing to the Success div as intended upon a successful request.
A typical response in JSON:
{
last_name: "The Last name is required",
email: "The Email is required",
city: "The City is required",
np_branch: "The Np branch is required"
}
Obviously, if one of the values passed the PHP validation its not added to the array. Please note that the error values might change for each key depending on the error thus checking for the error message is not an option.
Code:
$.ajax({
type: "POST",
dataType:"json",
data: {
last_name: l_name.val(),
email: email.val(),
city: city.val(),
np_branch: np_branch.val()
},
success: function(data) {
console.log(data);
// If all fields passed validation we hide the Cart div and show the Success div
if (typeof(data['last_name']) == "undefined" && typeof(data['email']) == "undefined" && typeof(data['city']) == "undefined" && typeof(data['np_branch']) == "undefined") {
$('.cart').css({ "display":"none" });
$('.success').css({ "display":"block" });
}
// Checking whether the response contains a last_name error
if (typeof(data['last_name']) != "undefined" && data['last_name'] !== null) {
l_name.addClass("error");
$('#l_name-err').css({ "display":"block" });
} else if (l_name.hasClass('error')) {
l_name.removeClass("error");
$('#l_name-err').css({ "display":"none" });
}
// Checking whether the response contains a email error
if (typeof(data['email']) != "undefined" && data['email'] !== null) {
email.addClass("error");
$('#email-err').css({ "display":"block" });
} else if (email.hasClass('error')) {
email.removeClass("error");
$('#email-err').css({ "display":"none" });
}
// Checking whether the response contains a city error
if (typeof(data['city']) != "undefined" && data['city'] !== null) {
city.addClass("error");
$('#city-err').css({ "display":"block" });
} else if (city.hasClass('error')) {
city.removeClass("error");
$('#city-err').css({ "display":"none" });
}
// Checking whether the response contains a np_branch error
if (typeof(data['np_branch']) != "undefined" && data['np_branch'] !== null) {
np_branch.addClass("error");
$('#branch-err').css({ "display":"block" });
} else if (np_branch.hasClass('error')) {
np_branch.removeClass("error");
$('#branch-err').css({ "display":"none" });
}
}
});
Is there a better way of doing that?
Maybe you could just check (unless I misunderstood the logic):
// If data.last_name is defined and has some value show error message, else remove it
if(data['last_name']) {
l_name.addClass("error");
$('#l_name-err').show();
} else {
l_name.removeClass("error");
$('#l_name-err').hide();
}
Also, typeof should not be written the way you have it remove the "()". It should be:
typeof data['np_branch'] !== "undefined" instead of typeof(data['np_branch']) != "undefined"

JS fires twice confirm-box onchange MVC

I have a problem, on the Telerik dropdownlist i have a function onchange selection. This function save a value with ajax call if an item from list is selected. If selection is not OK will show a confirm box, if the user press OK will be redirected on another page. If press Cancel need to populate a field with empty string.
The problem is: if the user press CANCEL button, the confirm-box fires twice...I tried to put return false after $('#Assessment').val(''); but does not work..
Any solutions please?
DropDownlist:
#(Html.Kendo().DropDownListFor(m => m)
.Name("Assessment").HtmlAttributes(new { #style = "text-align:center", onchange = "saveAssessment()" })
.OptionLabel("Select an assessment")
.DataTextField("DisplayName")
.DataValueField("Value")
.Value("DisplayName")
JS Function
function saveAssessment() {
var assessmentId = $('#Assessment').val();
var grid = $('#_gridProjectCheckList').data('kendoGrid');
var selectedItem = grid.dataItem(grid.select());
var ciId = selectedItem.Id;
var ciText = $("#Assessment").data("kendoDropDownList").text();
if (assessmentId !== null && (ciText === 'Ok' || ciText === 'NotApplicable')) {
$.ajaxSetup({ cache: false });
$.ajax({
url: 'UpdateProjectCheckItemAssessment',
type: "POST",
data: { assessmentId: assessmentId, id: ciId },
success: function (response) {
$('#Assessment').val(response.assessmentVal);
$('#_gridProjectCheckList').data('kendoGrid').dataSource.read();
}
});
}
else {
var msgRedir = confirm("You will be redirected to Assessment Page");
if (msgRedir) {
window.location.href = 'UpdateProjectCheckItem' + '/' + selectedItem.Id;
}
$('#Assessment').val('');
}
}

issue in preventing user from entering empty string in ajax post

I have a jquery ajax post and when a user inputs some text and presses enter in a textbox this ajax will trigger and show the value of text box in a <pre> html element. http://jsfiddle.net/LQg7W/2133/ obviuosly this jsfiddle does not show anything because I haven't put the ajax post inside it. But when the user writes nothing and presses enter this ajax is triggered and returns something. But how can I catch the empty strings from user?
This is located in my view:
if(e.keyCode == 13) {
var currentLine = $('#terminal').text();
var inputData = $(e.currentTarget).val();
$('#terminal').text(currentLine + "\r\n" + inputData + "\r\n"); //show the current and previous value
$("#textInput").val(" $> ");
AjaxPost(inputData);
}
and this ajax post is in model:
AjaxPost : function(dataAttribute, view, cacheId) {
console.log(cacheId);
var that = this;
if(dataAttribute === ""){
view.showMessage( " " , true);
}
$.ajax({
type : "POST",
url : "/api/user" ,
datatype : "application/json",
contentType: " text/plain",
data : dataAttribute,
success : function(data) {
console.log(data);
},
error : function(error) {
},
My problem is that my input data has default value of "$>" so I cannot check this condition if (inputdata === "" ) because it is always full! Have any ideas?
if the input value defaults to "$>" then you only need to check that too, and return to avoid the ajax call:
if(dataAttribute === "" || dataAttribute === "$>") {
view.showMessage( " " , true);
return;
}
var m = inputdata.match(/\s*\$\>\s*/)
if (inputdata === m[0]){
console.log('empty')
}
else{
console.log('not empty')
}

How to save var value outside ajax success function?

I am trying to make some form validation functions. Here is what I have:
<script>
$(document).ready(function() {
var myObj = {};
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
$.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
if (data.ok == true) {
$(myObj).data("username","ok");
} else {
$(myObj).data("username","no");
}
}
});
} // end validateusername function
$('#submit').click(function(){
if (myObj.username == "ok") {
alert("Username OK");
} else {
alert("Username BAD");
}
});
}); // end doc ready
So you can see, when a key is pressed in the textbox, it checks if it's valid. The "data.ok" comes back correctly. The problem is based on the response, I define $(myObj).username. For some reason, I can't get this value to work outside the validateusername function. When clicking the submit button, it has no idea what the value of $(myObj).username is.
I need to use something like this, because with multiple form fields on the page to validate, I can do something like:
if (myObj.username && myObj.password && myObj.email == "ok")
... to check all my form fields before submitting the form.
I know I must just be missing something basic.... any thoughts?
EDIT: SOLVED
All I had to do was change var myObj = {}; to myObj = {}; and it's working like a charm. I think I've been staring at this screen waaaaay too long!
You're not accessing the data that you stored properly. Access the username value this way:
$(myObj).data("username")
Resources:
Take a look at jQuery's .data() docs.
Very simple jsFiddle that shows how to properly set and retrieve data with jQuery's .data() method.
I would store the promise in that global variable and then bind an event to the done event within your submit button click.
$(document).ready(function() {
var myObj = false;
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
myObj = $.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
$('#username').removeClass('valid invalid');
if (data.ok == true) {
$('#username').addClass('valid');
}
else {
$('#username').addClass('invalid');
}
}
});
} // end validateusername function
$('#submit').click(function(){
// if myObj is still equal to false, the username has
// not changed yet, therefore the ajax request hasn't
// been made
if (!myObj) {
alert("Username BAD");
}
// since a deferred object exists, add a callback to done
else {
myObj.done(function(data){
if (data.ok == true) {
alert("Username BAD");
}
else {
alert("Username OK");
}
});
}
});
}); // end doc ready
you may want to add some throttling to the keyup event though to prevent multiple ajax requests from being active at once.

Categories

Resources