Prevent ajax call if input is blank - javascript

What is the correct way of preventing an ajax call if someone where to enter a blank space in an input field?
The code I am trying to do would look something like this (obviously this does not work)
$(document).ready(function() {
$(document).on('click', '#insert_btn', function() {
if ($("#first_name").val().length > 0)) {
$.ajax({
type: 'POST',
url: 'add.php',
datatype: "json",
data: {
first_name: $("#first_name").val(),
last_name: $("#last_name").val(),
position: $("#position").val(),
date: $("#date").val(),
updated: $("#updated").val(),
},
success: function(result) {
if (result == ADD_OK) {
alert('OK')
} else {
alert('wrong');
}
}
})
});
});

Since you're using jQuery already you can go for something like the code below where I've added the use of jQuery.trim before checking for the length
$(document).ready(function() {
$(document).on('click', '#insert_btn', function () {
// Utilizing https://api.jquery.com/jQuery.trim/
var first_name = $.trim($("#first_name").val());
if (first_name.length > 0) {
$.ajax({
type: 'POST',
url: 'add.php',
datatype: "json",
data: {
first_name: $("#first_name").val(),
last_name: $("#last_name").val(),
position: $("#position").val(),
date: $("#date").val(),
updated: $("#updated").val(),
},
success: function (result) {
if (result == ADD_OK) {
alert('OK')
} else {
alert('wrong');
}
}
})
}
});
});
jQuery Trim:
jQuery.trim(' ') // returns ""
jQuery.trim(' ') // returns ""
jQuery.trim(' this is my search text ') // returns "this is my search text"

Related

get the notification length depends on ReadFlag

JS:
function getJSON(){
$.ajax({
url: "getgroupednotification.json",
type: "GET",
crossDomain: true,
success:function(res){
$.each(res,function(index, value){
//console.log(res);
//console.log(value);
$.each(value.Notifications, function(index_, value_){
if(value.Source == 'CIRIS'){
var i = value.Notifications.length;
if(value_.ReadFlag != 1){
}
}
});
});
});
i want to get the notification.length if ReadFlag == 0. Im using Source == CIRIS for this example.
This is the link to my JSON
https://api.myjson.com/bins/navph
You could use something like this:
function getJSON() {
$.ajax({
url: "https://api.myjson.com/bins/navph",
type: "GET",
crossDomain: true,
success: function(res) {
var lens = res.filter(function(item) {
// filter by source
return item.Source === 'CIRIS';
}).map(function(item) {
// get only Notifications
return item.Notifications;
}).map(function(notification){
// get lengths of notifications which have at least 1 RedFlag not 0
return (notification.filter(function(item){
return item.RedFlag !== 0;
}).length)
})
console.log(lens[0]);
}
})
}
getJSON();

Jquery autocomplete and enter key pressed

I have a jQuery autocomplete which reads from a database.
Everything works well, but when I press enter I need to go the database and check if the entered text exists in the table so I can select it - else I will alert invalid input.
My Attempt
I implemented the source and select method and also implemented the onkeypress method of the textbox. I am getting the result I need but even after I press enter the autocomplete is still searching for the values from the database.
How do I stop this because it is slowing my page.
Code:
$("#<%=txtSearch_Doc.ClientID%>").autocomplete({
delay:1000,
source: function (request, response) {
var m_Subtype = $("#<%=hdn_Subtype_Doc.ClientID%>").val();
var m_ConSocStr = $("#<%=hdn_ConSocStr_Doc.ClientID%>").val();
var jsonObjects = { "prefixText": request.term, "m_Subtype": m_Subtype, "m_ConSocStr": m_ConSocStr };
var jsonString = JSON.stringify(jsonObjects);
$.ajax({
url: '<%=ResolveUrl("AutoCompleteForFile.asmx/AutoSelectDoc")%>',
data: jsonString,
dataType: "json",
delay: 0,
autoFocus: true,
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('|')[0],//show key
val: item.split('|')[1], //documentnumber
}
}))
}
,
error: function (response) {
if (response.responseText != "") {
alert(response.responseText);
}
},
failure: function (response) {
if (response.responseText != "") {
alert(response.responseText);
}
}
});
},
//begin select event
select: function (e, i) {
$("#<%=hdn_Number_Doc.ClientID%>").val(i.item.val);
$("#<%=txtSearch_Doc.ClientID%>").val(i.item.val.trim());
if (i.item.val == "") {
$("#<%=hdn_Number_Doc.ClientID%>").val("0");
$("#<%=txtSearch_Doc.ClientID%>").val("");
}
return false;
},
//end select event
minLength: 1,
autoFocus: false //IF TRUE IT WILL SELECT THE FIRST ROW BY DEFAULT, IF FALSE IT WILL NOT SELECT THE FIRST ROW
})
//end autocomplete
//key press event to handle enter pressed added by chahid on 12-jan-2016
.keypress(function (e) {
$("#<%=hdn_key_pressed.ClientID%>").val(e.keyCode);
if (e.keyCode == 13) {
e.preventDefault();
var x = $("#<%=txtSearch_Doc.ClientID%>").val();
var m_Subtype = $("#<%=hdn_Subtype_Doc.ClientID%>").val();
var m_ConSocStr = $("#<%=hdn_ConSocStr_Doc.ClientID%>").val();
var jsonObjects = { "prefixText": x, "m_Subtype": m_Subtype, "m_ConSocStr": m_ConSocStr };
var jsonString = JSON.stringify(jsonObjects);
$("#<%=hdn_is_alert.ClientID%>").val("1");
$.ajax({
url: '<%=ResolveUrl("AutoCompleteForFile.asmx/CheckForDocExistance")%>',
data: jsonString,
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (dat) {
var json = JSON.stringify(dat);
obj = JSON.parse(json);
if (obj.d == "2") { // if it is empty
$("#<%=txtSearch_Doc.ClientID%>").val("");
$("#<%=hdn_Number_Doc.ClientID%>").val("0");
}
else {
if (obj.d.split('|')[0] == "1") {
$("#<%=txtSearch_Doc.ClientID%>").val(obj.d.split('|')[1].trim());
$("#<%=hdn_Number_Doc.ClientID%>").val(obj.d.split('|')[1]);
return false;
} else {
alert("Invalid input");
$("#<%=txtSearch_Doc.ClientID%>").val("");
$("#<%=txtSearch_Doc.ClientID%>").focus();
$("#<%=hdn_Number_Doc.ClientID%>").val("0");
}
}
},
error: function (response) {
if (response.responseText != "") {
alert(response.responseText);
}
},
failure: function (response) {
if (response.responseText != "") {
alert(response.responseText);
}
}
});
$("#<%=txtSearch_Doc.ClientID%>").autocomplete('close');
}
})
OK I manage to found a solution : I added the search event to the autocomplete where I am checking the keypresscode and returning false when it is the enter key:
search: function (event, ui) {
var key = $("#<%=hdn_key_pressed.ClientID%>").val();
if (key == 13)
return false;
else
return true;
},

Ajax/JS Does not go

The script is nothing back what this could be?
Here a link to the page Test Link
$(document).ready(function() {
// Anmeldung des Namens
$("#startfrom").submit(function() {
if($("#yourname").val() == "") {
$("#response").html("Bitte gebe einen Namen an!");
} else {
name = $("#yourname").val();
$("#submit").attr("disabled", "disabled");
$("#response").html("Lade...");
$.ajax({
type: "POST",
url: "chat.php"
data: "name=" + name
success: function(msg) {
$("main").html(msg);
$("#response").html("");
$("message").focus();
}
});
}
return false;
});
});
The code is intended to provide an issue who was entering no name.
The problem is you missed commas at the end of these lines:
url: "chat.php"
data: "name=" + name
These both lines need , in the end. They are objects. Corrected code:
$.ajax({
type: "POST",
url: "chat.php",
data: "name=" + name,
success: function(msg) {
$("main").html(msg);
$("#response").html("");
$("message").focus();
}
});
The other mistake is: Change your form id: Your form id is 'startform' not 'startfrom'.
Update
Hope this above one helps you.
Works for me after putting the comma:
Your form id is 'startform' and you wrote is 'startfrom'.
So, first of all correct you id name which you wrote in jquery and then try it.
After this if you got any error then try this code :
$(document).ready(function() {
// Anmeldung des Namens
$("#startform").submit(function() {
if($("#yourname").val() == "") {
$("#response").html("Bitte gebe einen Namen an!");
} else {
var name = $("#yourname").val();
$("#submit").attr("disabled", "disabled");
$("#response").html("Lade...");
$.ajax({
type: "POST",
url: "chat.php",
data: { name: name},
success: function(msg) {
$("main").html(msg);
$("#response").html("");
$("message").focus();
}
});
}
return false;
});
});
I hope you will get your solution.

Issues with jquery html()

Having some issues properly getting the manipulated data from an element.
Everywhere on the internet doesn't seem to cover such a simple question with a simple answer. Please help.
I have manipulated an element with a returning ajax request:
$("#last_comment_added").html("1457856458")
now my function on the page:
jQuery(document).ready(function($) {
var post_slug = $("#post_slug").html();
var last_comment_added = $("#last_comment_added").text();
if (post_slug && last_comment_added) {
setInterval(function() {
$.ajax({
type: "POST",
url: "ajax_comments.php",
data: {
"task": "updates",
"post_slug": post_slug,
"last_comment_added": last_comment_added
},
cache: false,
success: function(html) {
eval(html)
}
});
}, 10000);
}
});
I get the old data from the element, not the new ajax "1457856458" data.
Please help.
If I understand your problem right it's just that you create this variable called last_comment_added and expect it to be continually updated, you set it once to be the text of the last_comment_added, it's never updated in your interval function. Here's a change that should make it work better for you.
jQuery(document).ready(function($) {
var post_slug = $("#post_slug").html();
if (post_slug && last_comment_added) {
setInterval(function() {
$.ajax({
type: "POST",
url: "ajax_comments.php",
data: {
"task": "updates",
"post_slug": post_slug,
"last_comment_added": $("#last_comment_added").text()
},
cache: false,
success: function(html) {
eval(html)
}
});
}, 10000);
}
});
Don't use eval.
Try
$(document).ready(function() {
var post_slug = $("#post_slug").html();
var last_comment_added = $("#last_comment_added").html();
if (post_slug && last_comment_added) {
setInterval(_update, 10000);
}
});
function _update() {
$.ajax({
type: "POST",
url: "ajax_comments.php",
data: {
"task": "updates",
"post_slug": post_slug,
"last_comment_added": last_comment_added
},
cache: false,
success: function(data) {
$("#last_comment_added").html(data)
}
});
}
and you return from PHP only NEW data. (something like: echo '1457856458';)

Jquery textarea.val('') adds line break on FIRST enter press?

I have a little chat setup, and on enter press if the text area is in focus I have it set to submit the chat to my database and clear the text area. Unfortunately though, the first time one presses enter it adds a linebreak in the text area, in any browser. If you type and press enter again, there's still only one line break there. Am I missing something?
Thanks!
$(document).keypress(function(keyPress) {
if (keyPress.which == 13) {
if ($('#chatText').is(':focus')) {
if ($('#chatText').val().length > 0) {
chatValue = $('#chatText').val();
$('#chatText').val($('#chatText').val().substring(0,0));
$.ajax({
type: 'POST',
url: 'submitChat.php',
data: { chatText: chatValue },
success: function(result) {
$('#chat_text').html(result);
document.getElementById('chat_text').scrollTop = 9999999;
}
});
}
}
}
});
Why don't you just clear it?
$('#chatText').keypress(function(e) {
if (e.which == 13) {
var value = $(this).val();
if (value.length > 0) {
$(this).val('');
$.ajax({
type: 'POST',
url: 'submitChat.php',
data: {
chatText: value
},
success: function(result) {
$('#chat_text').html(result);
this.scrollTop = 9999999;
}
});
}
}
});
Try this,
$(document).keypress(function(keyPress) {
if (keyPress.which == 13) {
keyPress.preventDefault();
if ($('#chatText').is(':focus')) {
if ($('#chatText').val().length > 0) {
chatValue = $('#chatText').val();
$('#chatText').empty();
$.ajax({
type: 'POST',
url: 'submitChat.php',
data: { chatText: chatValue },
success: function(result) {
$('#chat_text').html(result);
document.getElementById('chat_text').scrollTop = 9999999;
}
});
}
}
}
});
$(document).keypress(function(keyPress) {
if (keyPress.which == 13) {
keyPress.preventDefault();// Add this line
if ($('#chatText').is(':focus')) {
if ($('#chatText').val().length > 0) {
chatValue = $('#chatText').val();
$('#chatText').val($('#chatText').val().substring(0,0));
$.ajax({
type: 'POST',
url: 'submitChat.php',
data: { chatText: chatValue },
success: function(result) {
$('#chat_text').html(result);
document.getElementById('chat_text').scrollTop = 9999999;
}
});
}
}
}
});

Categories