How to skip a field when its value is null with SweetAlert? - javascript

I am using the sweetAlert library, I have a Dropdown where it shows a list of elements associated to the ID #references, it happens that this Dropdown is not a mandatory field, it may or may not be empty and the following happens:
when this Dropdown has no validation when I press the save button the record is saved fine.
However when I press the save button and the Dropdown is empty (it has as null value) it does not show the msj but it saves the changes, and I need the msj to be shown.
I am trying to validate that if the field is null or has content, it passes validation but I have no result I have the following code:
function modifyRecord(){
let content = tinymce.get("description").getContent();
let sinSaltos = content.replace(/(?:\r\n|\r|\n)/gm, '');
if($('#place').val()== null){
sweetAlert("Attention", "Select the place", "warning");("Attention", "fill empty", "error");
return;
}
if($('#observation').val().trim().length<1){
sweetAlert("Attention", "Write the observation", "warning");("Attention", "fill empty", "error");
return;
}
if (sinSaltos === '')
{
sweetAlert("Attention", "The record has no content", "warning");("Attention", "fill empty", "error");
return;
}
if($('#references').val() == null || $('#references').val().length > 1 ){
var form_data = new FormData();
form_data.append("action","modifyRecord");
form_data.append("place",$('#place').val());
form_data.append("#references",$('#references').val());
form_data.append("observation",$('#observation').val());
form_data.append("description",sinSaltos);
form_data.append("num",$('#idRecord').val());
$.ajax({
url: 'api_record.php',
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
var datar = data[0];
if(datar[0].result==1){
swal({title: "<div style='color:#636262'>Registry modified successfully</div>",html: true,confirmButtonText: "continue"},function(){
reload();
});
}else {
swal({title: "<div style='color:#636262'>Registry has not been modified correctly, try again</div>",html: true,confirmButtonText: "continue"},function(){
reload();
});
}
}
}).error(function(r){
console.log("Error-->",r.responseText);
});
}
}
function reload(){
location.reload();
}

Related

Is there a way to prevent Enter key from returning a response in json from another page? Codeigniter Ajax

I am using ajax for my operations Create and Update
I can already create and update, but if I press or hit Enter key then this shows from another page which is kinda not look good to see, and it suddenly also create blank data after hitting Enter key.
{"success":false,"type":"update"}
For visual representation, here it what it looks like after hitting the Enter key on input fields
this is what my input is in my View
<input type="text" name="group[]" id="group" placeholder="Enter your Choice" class="form-control" />
in my Controller
public function addGroup(){
$result = $this->group_model->addGroup();
$msg['success'] = false;
$msg['type'] = 'add';
if($result){
$msg['success'] = true;
}
echo json_encode($msg);
}
public function updateGroup(){
$result = $this->group_model->updateGroup();
$msg['success'] = false;
$msg['type'] = 'update';
if($result){
$msg['success'] = true;
}
echo json_encode($msg);
}
And in Model
public function updateGroup(){
$id = $this->input->post('txtId');
$field = array(
'group_name'=>$this->input->post('group')
);
$this->db->where('id', $id);
$this->db->update('groups', $field);
if($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
public function addGroup(){
$field = array(
'group_name'=>$this->input->post('group'),
);
$this->db->insert('groups', $field);
if($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
Ajax
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var group = document.getElementById('group').value;
if(group.replace(/\s/g, "").length <=0 ) {
swal("Submission fail!", "Enter the required field", "error");
return false;
}
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type = 'updated'
}
swal("Success!", "You delete a Question!", "success");
showGroups();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
});
$('#myForm').submit(function(e){
$('#btnSave').attr('disabled',true); //disable the button
//.Your other code
success: function(response){
if(response.success){
$('#btnSave').attr('disabled',false); //enable the button
}
}
}
On CLicking the button disable the click event of submnit button which is default behaviour if you press Entern and enable it back if u get successfuly response.
In addition if you just want to disable enter key then u cn do it like this:
var keyCode = e.keyCode || e.which;
if (keyCode === 13) {
e.preventDefault();
return false;
}
Change
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var group = document.getElementById('group').value;
if(group.replace(/\s/g, "").length <=0 ) {
swal("Submission fail!", "Enter the required field", "error");
return false;
}
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type = 'updated'
}
swal("Success!", "You delete a Question!", "success");
showGroups();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
});
});
into
$('#myForm').submit(function(e){
e.preventDefault();
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//validate form
var group = document.getElementById('group').value;
if(group.replace(/\s/g, "").length <=0 ) {
swal("Submission fail!", "Enter the required field", "error");
return false;
}
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
beforeSend: function(){
$('#btnSave').attr('disabled',true);
},
success: function(response){
if(response.success){
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if(response.type=='add'){
var type = 'added'
}else if(response.type=='update'){
var type = 'updated'
}
swal("Success!", "You delete a Question!", "success");
showGroups();
}else{
alert('Error');
}
},
error: function(){
alert('Could not add data');
}
$('#btnSave').attr('disabled',false);
return false;
});
});
Change button into Submit
Hope this Helps !!

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 :-)

How to pass file data with AJAX and jQuery?

I'm trying to create a form that allows a user to fill out data and if an option is checked a div opens up and the user has the option to upload a file along with their submission.
The issue I am having is getting the file to pass thru ajax correct. I can't quite mesh it together properly to get the results that I am looking for which is the file posting to my php script. Here's my code for passing the data:
$(document).ready(function() {
$("#submit_btn").click(function() {
var proceed = true;
//simple validation at client's end
//loop through each field and we simply change border color to red for invalid fields
$("#contact_form input[required=true], #contact_form textarea[required=true]").each(function(){
$(this).css('border-color','');
if(!$.trim($(this).val())){ //if this field is empty
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
//check invalid email
var email_reg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
});
if(proceed) //everything looks good! proceed...
{
//get input field values data to be sent to server
var search_array = $('input[name="donation"]').map(function(){
return $(this).val();
}).get();
post_data = {
'user_name' : $('input[name=full_name]').val(),
'user_email' : $('input[name=email]').val(),
'address' : $('input[name=address]').val(),
'address2' : $('input[name=address2]').val(),
'city' : $('input[name=city]').val(),
'state' : $('input[name=state]').val(),
'zip' : $('input[name=zip]').val(),
'ccnum' : $('input[name=ccnum]').val(),
'expmonth' : $('select[name=expmonth]').val(),
'expyear' : $('select[name=expyear]').val(),
'cardname' : $('input[name=cardname]').val(),
'ccvcode' : $('input[name=ccvcode]').val(),
'donation' : $('input[name=donation]:checked').val(),
'donation_other' : $('input[name=donation_other]').val(),
'contact_phone' : $('input[name=contact_phone]').val(),
'attached_file' : $('input[name=attached_file]').val(),
'donatecomments' : $('textarea[name=donatecomments]').val()
};
//Ajax post data to server
$.post('https://www.xxxxxx.org/catch.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
//reset values in all input fields
$("#contact_form input[required=true], #contact_form textarea[required=true]").val('');
$("#contact_form #contact_body").slideUp(); //hide form after success
window.top.location.href = "https://www.xxxxxxxxx.org/thank-you";
}
$("#contact_form #contact_results").hide().html(output).slideDown();
}, 'json');
}
});
//reset previously set border colors and hide all message on .keyup()
$("#contact_form input[required=true], #contact_form textarea[required=true]").keyup(function() {
$(this).css('border-color','');
$("#result").slideUp();
});
});
And my line for file selection:
<input id="attached_file" name="attached_file" style="width:220px;" placeholder="Enter an amount - No $ sign" type="file" value="" onfocus="jQuery(this).prev("input").attr("checked", true); if(jQuery(this).val() == "Other") { jQuery(this).val(""); }" onblur="if(jQuery(this).val().replace(" ", "") == "") { jQuery(this).val("Other"); }" tabindex="18">
How can I get the actual file data to pass as well?
You'll need to store the file as FormData. You can still send the form data along with your file attachment by append your form data to the FormData object See below example:
NOTE: This example is assuming it's an xml file. If it's not an xml file, don't use the xml portion (last 3 lines in the if statement).
JavaScript
// #fileUpload is to a input element of the type file
var file = $('#fileUpload')[0].files[0]
var fd = new FormData();
fd.append('theFile', file);
$.ajax({
url: '...',
type: 'POST',
processData: false,
contentType: false,
data: fd,
success: function (data, status, jqxhr) {
//success code
},
error: function (jqxhr, status, msg) {
//error code
}
});
C#
protected void Page_Load(object sender, EventArgs e)
{
try
{
foreach (string file in Request.Files)
{
var fileContent = Request.Files[file];
if (fileContent != null && fileContent.ContentLength > 0)
{
Stream stream = fileContent.InputStream;
BinaryReader br = new BinaryReader(stream);
byte[] binaryData = br.ReadBytes(fileContent.ContentLength);
string xml = System.Text.Encoding.Default.GetString(binaryData);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(xml);
}
}
}
catch (Exception ex)
{
}
}
var formData = new FormData($("#formid")[0]);
$.ajax({
url:'url',
type: 'POST',
data: formData,
processData: false,
contentType: false,
async: false,
success:function(response){
if(response == '100'){
swal({
title: "Blog Added",
text: "Blog Added Successfully",
type: "success",
confirmButtonText: "OK",
showCancelButton: false,
}, function(){
/*location.reload();*/
window.location.href = 'redirect link';
});
}else{
toastr.error(response);
}
}
});
you can do this using FormData. try this
$("form#data").submit(function() {
var formData = new FormData($(this)[0]);
$.post($(this).attr("action"), formData, function(data) {
alert(data);
});
return false;
});
// HTML
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
There are two ways to do it, one is pass parameters if you have less variables in you form..
$post('url',{param1:$("#name").val(),param2:$("#middle").val()},function(data){
//Action as per data returned from php code
});
Another method is serialize() method.
$post('url',{param1:$("form").serialize()},function(data){
//Action as per data returned from php code
});

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 display Text just next to the Text Box using jQuery in MVC

I am using the Pop up window to enter the value of "Subject" field and this field is mandatory, So how to display the Text just next to the "Subject" field without using validation and using just simple jQuery, i.e. "Please enter the Subject". The below code is working but if I want to add another Subject for some Task then the Text "Please enter the Subject" is shown on that pop up. So how to remove it.
if ($("#subject").val().length > 0)
{
$.ajax({
url: '/Task/QuickSave',
type: 'post',
dataType: 'json',
data: $('form#quickSaveTask').serialize(),
success: function (data) {
alert('data');
}
});
$('#Subject').val('');
$('#lean_overlay').fadeOut();
$('#Add').hide();
if (refreshTaskGrid != '') refreshTaskGrid();
return false;
}
else
{
var msg = $('#subject-message');
if (msg.length == 0) {
msg = $('<div id="subject-message"></div>')
$('#subject').after(msg);
}
$("#subject").focus();
msg.html('Please enter the Subject !');
return false;
}
msg.html('');
May be the below code will help
$('text-box').change(function(){
var textEntered=$(this).val();
if(textEntered.length>0){
//construct logic to show message
if($('#msg-container').size()==0)
{
$('<div id="msg-container">Please enter message</div>').css('float','left').appendTo($(this));
}
}
else
{
//remove the message div
$('#msg-container').remove();
}
});

Categories

Resources