How to prompt a sweetalert on submit button click php - javascript

enter image description hereI was working on the php laravel framework. I need to prompt a sweet alert showing the terms and conditions on clicking the submit button. I have no clue to use sweet alert. I just used some of the templates and wrote the following code. It's not working. Can anyone help me with this
#extends('layouts.app')
#section('maincontent')
<div class="login-form">
<div class="container">
<div class="row ">
<div class="innerpage-box">
#include('layouts.errors')
<div class="innerpage-box-header text-center">
<h3></b>Products to Buy</h3>
</div>
<div class="register-box-body">
<!-- <p class="login-box-msg">REGISTRATION FORM</p> -->
<form role="form" id="myForm" action="/chemOrderSave" method="Post" class="bidDetailSave">
#csrf
<input type="hidden" name="product_id" value="{{$pro[0]->id}}">
<div class="row">
<div class="col-md-6">
<label> <b> Price: </b>
{{$pro[0]->price * 1.02}}
</label> </br>
<div class="form-group">
<label for="buyer_quantity"><b> Quantity </b> <star>*</star></label>
<input type="text" class="form-control" id="buyer_quantity" name="buyer_quantity" placeholder="Enter the Quantity" value="{{$pro[0]->quantity}}">
</div>
<div class="form-group">
<label for="chem_shipping">Shipping</label>
<select name="chem_shipping" class="form-control" required>
<option value="">Please select one of the following Shipping Addresses</option>
#foreach($us as $uss)
<option value="{{$uss->id}}" > {{$uss->address}} {{$uss->city}} {{$uss->state}} {{$uss->zipcode}} {{$uss->country}} </option>
#endforeach
</select>
</div>
</div>
<button type="submit" class="btn btn-success updateOrder" ><i class="fa fa-save"></i> Submit</button>
<i class="fa fa-close"></i> Cancel
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
In the custom.js I wrote the following code
$('.container').on('click', '.updateOrder', function() {
//e.preventDefault();
var id = $(this).attr('id');
var title = "Are you sure, By Clicking accept you agree to Farmerce's user agreement and are agreeing to follow through on this transaction !";
swal({
title: title,
type:'warning',
showConfirmButton: true,
showCancelButton: true,
allowOutsideClick: false,
confirmButtonText:'Confirm',
}).then((result) => {
if (result.value) {
$.ajax({
type: 'post',
url: '/chemBuyer',
data: {'_token': $('input[name=_token]').val(), 'id':id},
success: function(data) {
if(data == 'success'){
var title= 'Successfully Order Placed!!!';
var type='success';
}else{
var title= 'Some thing went wrong with the '+name+' !!!';
var type='error';
}
swal({
title: title,
type:type,
showConfirmButton: true,
confirmButtonText:'OK',
}).then(function(){
window.location.reload();
});
}
});
}
})
});

Related

Javascript/jquery to validate the form in button click?

Hi i have a class using needs validate in form is there a way for me to validate this on button submit onclick ? or a better way to improve the coding for this ?
Where i can even call the invalid feedback ?
and also when button click it will check the valdiation first before call the database
As this code got some problem later in the end where i couldnt validate anything when button click as it passes to the database immediately without the validation check .
(function validateForm() {
'use strict';
var forms = document.getElementsByClassName('needs-validation');
Array.from(forms)
.forEach(function(form) {
form.addEventListener('submit', function(event) {
if (!form.checkValidity()) {
event.stopPropagation();
event.preventDefault();
}
form.classList.add('was-validated');
}, false)
})
})();
<form id="form" class="needs-validation" onsubmit="return validateForm()">
<!-- <label id="mandatoryField" class="hiddenfield" hidden>* is mandatory</label> -->
<div class="form-group row nameform">
<label for="validationName" class="col-form-label nameadduser">Name:</label>
<div class="col-6">
<input name="validationName" type="text" class="form-control" id="validationName" placeholder="Name" title="Name can be any. e.g. john" required>
<div class="invalid-feedback">
Enter a Name!
</div>
</div>
</div>
<div class="form-group row">
<label for="validationEmail" class="col-form-label emailadduser">Email:</label>
<div class="col-6">
<input name="validationEmail" type="email" class="form-control emails" id="validationEmail" placeholder="example1#gmail.com" pattern="^([a-zA-Z0-9_\-\.]+)#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$"
required>
<div style="margin-left: 3px;" class="invalid-feedback">
Enter a correct Email format!
</div>
</div>
</div>
<div class="form-group row">
<label for="validationUserName" class="col-form-label usernameadduser">Username:</label>
<div class="col-6 ">
<input name="validationUserName" type="text" class="form-control " id="validationUserName" placeholder="Username" pattern="^(?=.{4,}$)(?:[a-zA-Z\d]+(?:[a-zA-Z\d])*)+$" title="Username should be at least 4 letter" required>
<div class="invalid-feedback">
Username must meet the following requirements:
<b>At least four letter</b>
</div>
</div>
</div>
<div class="form-group row">
<label for="validationpassword" class="col-form-label oldpasswordadduser">Old<br>
Password:</label>
<div class="col-6 d-flex">
<input name="validationpassword" type="password" class="form-control pass" id="oldpasswords" placeholder="Password" required>
<i class="bi bi-eye-slash" id="toggleoldPassword"></i>
<!-- <div style="margin-left: 15px;" class="invalid-tooltip password-empty" >
Enter a password!
</div> -->
</div>
</div>
<div class="form-group row">
<label for="validationpassword" class="col-form-label passwordadduser">Password:</label>
<div class="col-6 d-flex">
<input name="validationpassword" onChange="onChange()" type="password" class="form-control pass" id="passwords" placeholder="Password" pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!##$%^&*_=+-]).{7,}$" title="Password should be like this. e.g. A123de!123"
required>
<i class="bi bi-eye-slash" id="togglePassword"></i>
<!-- <div style="margin-left: 15px;" class="invalid-tooltip password-empty" >
Enter a password!
</div> -->
<div id="passwordvalidator" class="invalid-tooltip password-notmeet">
Password must meet the following requirements:
<br><br>
<label class="color-text"> At least one capital letter</label>
<br>
<label class="color-text"> At least one special character</label>
<br>
<label class="color-text"> At least one number</label>
<br>
<label class="color-text"> Be at least 7 letter</label>
</div>
</div>
</div>
<div class="form-group row">
<label for="validationconfirmpassword" class="col-form-label passwordadduser">Re-enter<br>
Password:</label>
<div class="col-6 d-flex">
<input name="validationconfirmpassword" onChange="onChange()" type="password" class="form-control confirmpass" id="confirm_password" placeholder="Confirm Password" required>
<i class="bi bi-eye-slash" id="toggleconfirmPassword"></i>
<div style="margin-left: 20px;" class="invalid-tooltip">
Password do not match or value is null!
</div>
</div>
</div>
<div id="passwordconfirm"></div>
<div class="form-group row">
<label for="validationRole" class="col-form-label role">Role:</label>
<div class="col-3 ">
<select class="select-user-role custom-select-sm col-11" id="select-user-role" required>
<option class="selectrole" selected disabled value="">Select ....</option>
</select>
<div style="margin-left: 10px;" class="invalid-feedback">
Enter a valid user role!
</div>
</div>
</div>
<div class="form-group row placeholderimage">
<img src="" id="output" width="400" height="400" style="border-radius: 50%;" />
<input id="file-upload-input" type="file" accept="image/*" onchange="encodeImageFileAsURL(event);">
</div>
<button id="submitbtn" type="submit" class="btn-primary submitbutton" disabled>Done</button>
</form>
I have a button onclick where i got my database out when click which is this code it is with sweetalert as well not sure do we need to put the prevent button for validation here ?
$('#submitbtn').click(function() {
//get input value field
var name = $('#validationName').val();
var email = $('#validationEmail').val();
var username = $('#validationUserName').val();
var oldpassword = $('#oldpasswords').val();
var password = $('#passwords').val();
var picture = document.getElementById("output").src;
var role = $('#select-user-role').val();
//making ajax call after this retrieve
$.ajax({
url: "https://ecoexchange.dscloud.me:8090/api/postWithRawBody",
method: "POST",
contentType: "text/plain;charset=UTF-8",
headers: {
// Generally used for queries that we're planning to use
query: `UserUpdate(,'${formatParamString(name)}','${formatParamString(username)}','${formatParamString(email)}','','${formatParamString(password)}','','${formatParamString(role)}')`,
// apikey like oXkPNt3p6cuDobzBVjpsPUyawSYDFqFHVWPkijXZZstjVPLLWo
"Content-Type": "text/plain",
apikey: sessionStorage.getItem("apikey")
},
dataType: "text",
// May be quite long
// Usually an array
// Only for specific conditions
data: `UserUpdate(${getQueryInfo()["id"]},'${formatParamString(name)}','${formatParamString(username)}','${formatParamString(email)}','${formatParamString(oldpassword)}','${formatParamString(password)}','${formatParamString(picture)}','${formatParamString(role)}')`,
success: function(data, textStatus, xhr) {
// showing response from API
// showing response box that is added
//console.log(data)
$('#response').html("<div class='alert alert-success'>" + "<b>Success!</b> The information have been updated <b>successfully</b>" + "</div>")
Swal.fire({
icon: 'success',
title: 'Update Successfully!',
html: 'The information have been updated successfully!<br>By pressing <b>okay</b> this page will go to <b>view users</b> page',
showCancelButton: true,
cancelButtonText: "Cancel",
allowOutsideClick: false,
allowEscapeKey: false,
confirmButtonText: 'Okay',
cancelButtonColor: '#9b3be7', // purple
confirmButtonColor: '#79b446', // light green
heightAuto: false,
})
// footer: '<label class="fixissue">How to fix this issue?</label><br>Try to change the username input and press add button again'
.then(function(inputvalue) {
if (inputvalue.isConfirmed) {
window.location.assign('viewUsers.html?id=' + getQueryInfo()['id'])
} else if (inputvalue.isCancel) {
Swal.fire('')
}
})
},
error: function(xhr, textStatus, err) {
if (xhr["status"] == 409) {
$('#response').html("<div class='alert alert-danger'>" + "<b>Error!</b> There is an <b>duplicate</b> on username!" + "</div>")
//then
// setTimeout(function(){ window.location.reload(); },5000); //reload a page after 5 seconds
Swal.fire({
icon: 'error',
title: '<div class="color-text">Update not success!</div>',
html: 'There is an <label class="color-text"><b>duplicate</b></label> on username!<br><label class="fixissue">Solution ✔</label><br>Try to change the <b>username</b> and press <b>add</b> again',
heightAuto: false,
allowOutsideClick: false,
allowEscapeKey: false
// footer: '<label class="fixissue">How to fix this issue?</label><br>Try to change the username input and press add button again'
})
}
if (xhr["status"] == 400) {
$('#response').html("<div class='alert alert-danger'>" + "<b>Error!</b> The <b>old password </b> is incorrect!" + "</div>")
Swal.fire({
icon: 'error',
title: '<div class="color-text">Update not success!</div>',
html: 'The <label class="color-text"><b>old password</b></label> is incorrect!<br><label class="fixissue">Solution ✔</label><br>Try to change the <b>old password</b> and press <b>add</b> again',
heightAuto: false,
allowOutsideClick: false,
allowEscapeKey: false
// footer: '<label class="fixissue">How to fix this issue?</label><br>Try to change the username input and press add button again'
})
}
// if (xhr["status"] == "(failed)") {
// $('#response').html("<div class='alert alert-danger'>"+"<b>Error!</b> There is an <b>duplicate</b> on username! where you cant add in image"+"</div>")
// }
}
});
})

How to store an incomplete multi-step form?

I currently have a form that is multi-step; it doesn't do anything fancy per step, it simply does display: none on the previous step to hide the previous fields and move the user forward.
It submits via AJAX and has required fields.
Is there any way to capture the data from each step of the form, and then, if the user drops off or never submits the form, send the captured data - I'm not worried about any issues in regards to data protection, as it doesn't apply in this situation.
The form basically looks like this:
<form>
<div class="step-1">
<label>First Field
<input type="text" id="field1" name="field1" maxlength="50">
</label>
<label>Second Field
<input type="text" id="field2" name="field2" maxlength="50">
</label>
next step
</div>
<div class="step-2">
<label>Third Field
<input type="text" id="field3" name="field3" maxlength="50">
</label>
<label>Fourth Field
<input type="text" id="field4" name="field4" maxlength="50">
</label>
<input type="submit" id="send" name="submit" />
<span id="submitdata"></span>
</div>
</form>
The bit I'm struggling with is knowing when the user drops... Does it need to invoke some kind of session per the form?
You could automatically submit the form when the user leaves the page, using the beforeUnload event:
var notSubmitted = true;
$('form').on('submit', function() { notSubmitted = false; });
$(window).on("beforeunload", function() {
return notSubmitted ? $('form').submit() : null;
})
$("form").submit(function (e) {
e.preventDefault();
// ... ajax submission goes here ...
return false;
});
If you need to record that it is a 'by default' submission, then you could use a hidden form element instead of the variable notSubmitted. The hidden element would give you that data in the form.
Try this code:
$(document).ready(function () {
//alert("hi");
setTimeout(function () {
$("#msg").hide(1000);
}, 3000);
$("form#product_form").submit(function (e) {
//alert('hi');
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: '<?php echo site_url('C_home/pro_add'); ?>',
type: "POST",
data: formData,
dataType: "json",
contentType: false,
processData: false,
success: function (result) {
//alert(result);
$("#product_form").trigger('reset');
window.location.href = "<?php echo site_url('C_home/data_tbl'); ?>";
}
});
return false;
});
$("#product_form").validate({
rules: {
name: "required",
category_id: "required",
image: "required",
description: "required",
qty: "required",
price: "required"
},
messages: {
name: "Product name is required",
category_id: "Please Select Category name",
image: "Plases Select Product Image",
description: "Product Description is required",
qty: "Product Quantity is required",
price: "Product Price is required",
}
})
});
<script src="<?php echo base_url(); ?>assets/js/jquery.bootstrap.wizard.js" type="text/javascript"></script>
<script src="<?php echo base_url(); ?>assets/js/jquery.validate.min.js"></script>
<script src="<?php echo base_url(); ?>assets/js/wizard.js"></script>
<div class="wizard-container">
<div class="card wizard-card ct-wizard-orange" id="wizard">
<form id="product_form" method="POST" enctype="multipart/form-data">
<div class="wizard-header">
<h3>
Jquery Accordion
</h3>
</div>
<ul>
<li>Product Panel 1</li>
<li>Product Panel 2</li>
<li>Product Panel 3</li>
</ul>
<div class="tab-content">
<div class="tab-pane" id="about">
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<div class="form-group">
<label>Product Name</label>
<input type="text" class="form-control" name="name" id="name" placeholder="Enter Product Name" required="" />
</div>
<div class="form-group">
<label>Select Category</small></label>
<select class="form-control" id="category_id" name="category_id" required="">
<option></option>
<!-- <option>--Select Category Name--</option> -->
<?php
foreach ($category as $row) {
?>
<option value="<?php echo $row['category_id']; ?>"><?php echo $row['category_name']; ?></option>
<?php } ?>
</select>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="account">
<div class="row">
<div class="col-sm-4 col-sm-offset-1">
<div class="picture-container">
<div class="picture">
<img src="<?php echo base_url(); ?>assets/img/default-avatar.png" style="height: 100px;" class="picture-src" id="wizardPicturePreview" title=""/>
<input type="file" class="form-control" name="image" id="wizard-picture" required="">
</div>
<h6>Choose Picture</h6>
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Product Description</label>
<textarea class="form-control" name="description" id="description" placeholder="Enter Product Description" rows="5" required></textarea>
</div>
</div>
</div>
</div>
<div class="tab-pane" id="address">
<div class="row">
<div class="col-sm-10 col-sm-offset-1">
<div class="form-group">
<label>Product Qty</label>
<input type="text" class="form-control" name="qty" id="qty" placeholder="Enter Product Qty" required />
</div>
<div class="form-group">
<label>Product Price</label>
<input type="text" class="form-control" name="price" id="price" placeholder="Enter Product Price" required />
</div>
</div>
</div>
</div>
</div>
<div class="wizard-footer">
<div class="pull-right">
<button type='button' class='btn btn-next btn-fill btn-warning btn-wd btn-sm' name='next' id="next" />Next</button>
<button type='submit' class='btn btn-finish btn-fill btn-warning btn-wd btn-sm' name='submit' value='Submit' />Submit</button>
</div>
<div class="pull-left">
<input type='button' class='btn btn-previous btn-fill btn-default btn-wd btn-sm' name='previous' id="prev" value='Previous' />
</div>
<div class="clearfix"></div>
</div>
</form>
</div>
</div>

How to return object instead of actual value on ajax call?

I am trying to do CRUD using ajax in my php application i have been successful with insert but stuck on update since i will have to send id number to next page to update data.
here is my script
$(document).ready(function(){
// When click the button.
$("[id^=get]").click(function() {
// Assigning Variables to Form Fields
var cid = $(this).val();
if(cid) {
$.ajax({
type: "post",
url: "getsingle.php",
asynch: false,
data: {
"cid": cid
},
success: function(data) {
$("#catname").val(data);
$("#tochange").html("<button id='update' type='button' class='btn btn-success'>Update</button>");
$("#categories").html("");
$("#form_category").append("<div class='form-group m-form__group row'><div class='col-lg-6'><input type='text' id='cid' class='form-control m-input' placeholder='Enter category name' value='"+$(cid)+"' name='cname'><span id='ecname' style='color: red;'> </span></div>");
}
});
} else {
$("#ecname").html("fill category name");
}
});
});
here is button i click which runs this function
<td><button value="'.$category['cid'].'" class="btn btn-primary get" id="get'.$category['cid'].'">edit </button></td>
form which will be for update data.
<div class="m-portlet">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<span class="m-portlet__head-icon m--hide">
<i class="la la-gear"></i>
</span>
<h3 class="m-portlet__head-text">
Add Categories
</h3>
</div>
</div>
</div>
<!--begin::Form-->
<form class="m-form m-form--fit m-form--label-align-right m-form--group-seperator" id="form_category" method="post" action="">
<div class="m-portlet__body">
<div class="form-group m-form__group row">
<label class="col-lg-2 col-form-label">
Category Name:
</label>
<div class="col-lg-6">
<input type="text" id="catname" class="form-control m-input" placeholder="Enter category name" name="cname">
<span id="ecname" style="color: red;"> </span>
</div>
</div>
<div class="m-portlet__foot m-portlet__no-border m-portlet__foot--fit">
<div class="m-form__actions m-form__actions--solid">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-6">
<span id="tochange">
<button id="save" type="button" class="btn btn-success">Save</button>
</span>
<button type="reset" class="btn btn-secondary">
Cancel
</button>
</div>
</div>
</div>
</div>
<!--end::Portlet-->
</div>
</form>
<!--end::Form-->
</div>
on click edit button everything work perfect I get category name on input perfectly also my button changes from save to update, but only input cidgetting value as object not as 1,2,3 etc etc. actual id.
$("[id^=get]").click(function() {
// Assigning Variables to Form Fields
var cid = $(this).val();
if(cid){
$.ajax({
type: "post",
url: "getsingle.php",
asynch: false,
data: {
"cid": cid
},
success: function(data){
$("#catname").val(data);
$("#tochange").html("<button id='update' type='button' class='btn btn-success'>Update</button>");
$("#categories").html("");
$("#form_category").append("<div class='form-group m-form__group row'><div class='col-lg-6'><input type='text' id='cid' class='form-control m-input' placeholder='Enter category name' name='cname'></div>");
$("#cid").val(cid);
}
});
}
else{
$("#ecname").html("fill category name");
}
I have solved it instead giving value within append i gave it separately after it displays working perfectly.

Show form in a modal window with Rails

I want to show a form in a modal window but I have my buttons on my javascript, so I would want to make them the "submit button" of the form.
This is my code:
I open the modal with this javascript function, with 2 buttons:
modal.js
window.newModal = function(path, title){
ShopifyApp.Modal.open({
src: path,
title: title,
height: 400,
width: 'large',
buttons: {
primary: {
label: "OK",
message: 'modal_ok',
callback: function(message){
ShopifyApp.Modal.close("ok");
}
},
secondary: {
label: "Cancel",
callback: function(message){
ShopifyApp.Modal.close("cancel");
}
}
},
}, function(result){
if (result == "ok")
ShopifyApp.flashNotice("'Ok' button pressed")
else if (result == "cancel")
ShopifyApp.flashNotice("'Cancel' button pressed")
});
}
And this is my form:
form_page.html.erb
<section>
<section class="full-width" align="center">
<article>
<div class="card" style="margin-bottom:0px;">
<form method="POST" action="form_page">
<input name="authenticity_token" value="<%= form_authenticity_token %>" type="hidden">
<div class="row">
<label>Dirección:</label>
<input type="text" name="address"/>
</div>
<div class="row">
<label>Apt, suite, etc. (opcional):</label>
<input type="text" name="addressopt"/>
</div>
<div class="row">
<label>Código Postal:</label>
<input type="text" name="postal" pattern="[0-9]{5}"/>
</div>
<div class="row">
<label>Phone (opcional):</label>
<input type="text" pattern="[0-9]{9}" name="phone"/>
</div>
<div class="row">
<label>City:</label>
<select name="city">
<option>Madrid</option>
<option>Barcelona</option>
<option>Málaga</option>
</select>
</div>
</form>
</div>
</article>
How can I submit that form through that function buttons?
I haven't used ShopifyApp ever, but in general if you want to submit a form in javascript you can just call submit() on the element. You'd want to give an id to the form to find it easily.
https://www.w3schools.com/jsref/met_form_submit.asp

Refresh captcha image jquery codeigniter

I have problem with my refresh captcha button, it just work once when I click the button after I reload the page. I dont know if i wrong or if I missed something else.
I try to refresh the captcha with jquery because more efficiently.
This is piece of my code :
controller
public function refresh_login(){
// Captcha configuration
$config = array(
'img_path' => 'captcha_images/',
'img_url' => base_url().'captcha_images/',
'img_width' => '100',
'img_height' => '30',
'word_length' => '4',
'font_size' => '16'
);
$captcha = create_captcha($config);
// Unset previous captcha and store new captcha word
$this->session->unset_userdata('captchaCode');
$this->session->set_userdata('captchaCode',$captcha['word']);
// Display captcha image
echo $captcha['image'];
}
jquery
$( document ).ready( function () {
var base_url = '<?php echo base_url(); ?>';
$('.reload-captcha').click(function(event){
event.preventDefault();
$.ajax({
url:base_url+'index.php/auth/refresh_login',
success:function(data){
$('.captcha-img').replaceWith(data);
}
});
});
view
<form action="<?php echo base_url(); ?>index.php/auth/login/" id="login-form" method="post">
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="Username" id="username" name="username" required>
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="Password" id="password" name="password" required>
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="form-group">
<p id="captImg" class="captcha-img"><?php echo $captchaImg; ?></p>
<input type="text" class="form-control" name="captcha" placeholder="Captcha" style="margin-bottom: 5px"/>
</i>
</div>
<div class="row">
<!-- /.col -->
<div class="col-xs-8">
<label><u>Forgot your password?</u></label>
</div>
<div class="col-xs-4 pull-right">
<button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button>
</div>
<!-- /.col -->
</div>
</form>
what kind of problem is occurring ???
try :
$('.captcha-img').attr("src", data);
in place of :
$('.captcha-img').replaceWith(data);
and add
dataType: "text",
cache:false,
as follow :
$.ajax({
url:base_url+'index.php/auth/refresh_login',
dataType: "text",
cache:false,
success:function(data){
$('.captcha-img').attr("src", data);
}
});

Categories