issue in preventing user from entering empty string in ajax post - javascript

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

Related

e.PreventDefault and ajx submit not working together [return true] is not working

I have a function to check whether email exist, but I want to submit the form only if the email doesn't exist
So I wrote following function:
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
return true;
$(this).submit();
}
}
});
});
Now if it return true also i cant submit the form . Please help.
i saw this question and answer e.preventDefault doesn't stop form from submitting . But no effect
Notes
even i tried
if(response.status=='true') { $("#form-1").submit(); } .
But this also not working
The return statement is returning before the form is submitted
if(response.status == 'true') {
//return true; // returns before the form is submitted
$(this).submit();
return true; // move return after submit
}
Suggestion
You are thinking about this, the wrong way, let PHP handle the checking and insert in the backend.
First Solution
In your PHP do something like
$querycheck = mysqli_query($con,"SELECT * FROM Persons");
$countrows = mysqli_num_rows($querycheck );;
if($countrows == '1')
{
echo json_encode(['message' => 'Sorry This Email Already Used']);
}
else
{
// insert statement here
echo json_encode(['message' => 'Submitted']);
}
In your JS
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
alert(response.message); // display the message here to the user.
}
});
});
Second Solution
save the form in a variable.
$("#form-1").on("submit",function(e){
e.preventDefault();
const form = $(this); // get the current form
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
form.submit(); // submit the form here
return true;
}
}
});
});

editing input fields together instead of separately

Current Scenario :
Right now I have a form in which you can edit and save each records of input fields. i.e. firstName, lastName, email etc..
I do not get any errors and everything is working fine.
Requirement :
Now what I want to save & edit firstName and lastName input fields together instead is to edit and save firstName and lastName input field separately.
Right now they are all different input id's.
Question :
How can I achieve this by calling the same class for firstName and lastName if I want to edit them at the same time with a button ?
Is this a way to do it ? Thanks...
Code :
$("#inputFirstName,#inputLastName,#inputEmailAddress,#inputPassword,#inputZipCode").on('keypress',function(e){
if(e.which == 13) {
var field = $(this).attr("id");
var data = {};
data['ajax']=true;
data[$('#'+field).attr('name')]=$('#'+field).val();
$.ajax({
method: "POST",
url: this.form.action,
data: data
})
.done(function( msg ) {
if(msg['status']=='fail'){
$('#errormsg span').html(msg['msg']);
$('#errormsg').show();
}
if($('#'+field).attr('name')=='game_user_profile[userinfo][firstName]') {
$('#userfirstname').text($('#'+field).val());
}
if($('#'+field).attr('name')=='game_user_profile[userinfo][lastName]') {
$('#userlastname').text($('#'+field).val());
}
});
$('#'+field+'-edit').show();
$('#'+field+'-save').hide()
$('#'+field).attr('disabled',true);
}
});
first of all. save on every keypress is bad and will exhaust your server.
I recommennd you use onChange or make a submit button
submit button is a better solution.
lets assume that we have this html:
<form id="updateForm">
<input type="text" id="firstN" name="firstName" data-val="Ris" value="Ris">
.
.
.
<input type="button" value="submit" id="goBtn">
</form>
first set a data-val equal to the value
then in your javascript
$("#goBtn").click(function(){
var data = {};
data["ajax"] = true;
$("#updateForm input").each(function(){
var $this = $(this);
var type = $this.attr('type');
if(type != "button" && $this.val() != $this.attr("data-val"))
data[$this.attr("name")] = $this.val();
});
if(data.length > 0){
$.ajax({
method: "POST",
url: this.form.action,
data: data
})
.done(function( msg ) {
if(msg['status']=='fail'){
$('#errormsg span').html(msg['msg']);
$('#errormsg').show();
} else {
$.each(data, function(index, value){
$('updateForm input[name="'+index+'"]').attr("data-val", value);
});
}
// then do things
});
}
});
first it checks every input for changes (data-val is holding the original value) and it adds it to data if there is any changes at all it calls the ajax and if it was successful it updates the data-vals of each changed value else it leave it for another submission

Email Validation in Javascript Before AJAX

So I got this js code for a form submission, and everything is working fine, however, I don't know where and what to write in the code so the email gets a validation check. What and where should I write to validation check the email?
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#fullname2").val();
var email = $("#fullemail2").val();
var state = $("#selectstate").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'FullName=' + name + '&email=' + email + '&SovereignState=' + state;
if (name == '' || email == '' || state == '') {
$('#required_fields').show();
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "demo.php",
data: dataString,
cache: false,
success: function(phpSays) {
if (phpSays == "OK") {
$('#email_error').show();
$('#required_fields').hide();
} else {
$('#sinatra2').hide();
$('#thanks').fadeIn(1000);
$('#spreading_message').delay(1800).fadeIn(1500);
$('#by_social').delay(3000).fadeIn(1500);
$('#email_error').hide();
$('#required_fields').hide();
}
}
});
}
return false;
});
});
Looking at your code I can suggest the below approach to say where you can do email validation
if(name==''||email==''||state=='')
{
$('#required_fields').show();
}//this is fine
else if(!valid(email))//call a function which validates email and returns true or false
{
//Display the message either with same $('#required_fields') changing the text or
//Add one more field to display invalid email message
}
else
{
//Your ajax call here
}
Now your valid function will look like
function valid(email)
{
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
return emailReg.test(email); //this will either return true or false based on validation
}
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#fullname2").val();
var email = $("#fullemail2").val();
var state = $("#selectstate").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'FullName='+ name + '&email='+ email + '&SovereignState='+ state;
if(name==''||email==''||state=='')
{
$('#required_fields').show();
}
else
{
// AJAX Code To Submit Form.
// <-- email address should be here
...........
}
return false;
});
});
Better place to validate is where you have 'fullemail2' input field. Even in the javascript file, you should do it before create the dataString. In that way you could validate before submit.

Passing variable from a function into submit function

$('.report_filter input') get value of selected radio box sending the variable to function report_operation, from there on I hide some fields based on the selection
$(".js-ajax-php-json") ajax form submission, I want to get inside the .submit the var value. There I could do some if empty field return false to stop the form from submitting. For instance if field name="number" is empty and the var value is 1 return false; This can't be made by a simple form validator, its a quite dynamic form.
I just have no idea how to do that
$('.report_filter input').on('ifChecked', function(event){
var val = $(this).val();
raport_operation(val);
});
$(".js-ajax-php-json").submit(function(){
var data = {
"action": "test1"
};
data = $(this).serialize() + "&" + $.param(data);
alert(raport_operation());
// if ($("#number").val() == "" and val == 1) {
// alert('you did not fill out one of the fields');
// return false;
// }
$.ajax({
type: "POST",
dataType: "json",
url: "api/response.php",
data: data,
success: function(data) {
draw_graph(data);
$(".the-return").html(data);
//alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
function raport_operation(query){
//alert(val);
if(query==1){ //number
//alert(1);
$('#segment_optional').hide('slow');
$('#segment_number').show('slow');
$('#segment_optional').show('slow');
$('#segment_customer').hide('slow');
$('#segment_listType').hide('slow');
$('#segment_customer').val('');
$('#reportdate_to').val('');
$('#reportdate_from').val('');
// $('#segment_general').hide();
}
}

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

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

Categories

Resources