alert error when details was added into database - javascript

I am getting the error "User is unable to be created" despite the user being successfully created. I have commented the part where the eeror was being shown. The details were all being able to be stored into the database. When I change it to alert(arr[0].result), the output was 0. I tried to use inspect to check for any error but there was none.
(function () {
var admin_userid;
var admin_password;
var admin_passwordagain;
var admin_firstname;
var admin_lastname;
var admin_position;
$(document).ready(function () {
$("#NewAdminForm").validate({
rules: {
txtNewLogin: "required",
txtNewPassword: "required",
txtNewPasswordAgain: {
equalTo: "#txtNewPassword"
},
txtFirstName: "required",
txtLastName: "required",
txtNewPosition: "required"
},
messages: {
txtNewLogin: "new user name is required",
txtNewPassword: "new password is required",
txtNewPasswordAgain: "new password again is required and must be the same as new password",
txtFirstName: "First Name is required",
txtLastName: "Last Name is required",
txtNewPosition: "Position is required"
},
focusInvalid: false,
submitHandler: function () {
return false;
},
errorPlacement: function (error, element) {
error.appendTo(element.parent().parent().after());
},
});
$("#btnCreateAccount").bind("click", function () {
savenewuser();
});
});
function savenewuser() {
if ($("#NewAdminForm").valid()) {
admin_userid = $("#txtNewLogin").val();
admin_password = $("#txtNewPassword").val();
admin_passwordagain = $("#txtNewPasswordAgain").val();
admin_firstname = $("#txtFirstName").val();
admin_lastname = $("#txtLastName").val();
admin_position = $("#txtNewPosition").val();
if ($("#NewAdminForm").valid()) {
var url = serverURL() + "/newadmin.php";
var JSONObject = {
"admin_userid": admin_userid,
"admin_password": admin_password,
"admin_firstname": admin_firstname,
"admin_lastname": admin_lastname,
"admin_position": admin_position
};
$.ajax({
url: url,
type: 'GET',
data: JSONObject,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getAdminResult(arr);
},
error: function () {
alert("error");
}
});
}
}
}
function _getAdminResult(arr) {
if (arr[0].result == 1) {
localStorage.setItem("admin_userid", admin_userid);
localStorage.setItem("admin_password", admin_password);
alert("new user created");
window.location = "homepage_admin.php";
}
else {
alert("User is unable to be created"); //error displayed
}
}
})();

Related

Alert function not working after ajax call in laravel

<script>
$(function () {
$("#portal_register_post").validate({
rules: {
user_email: {
required:true,
email: true,
maxlength: 50
},
CreatePwd: {
required:true,
maxlength: 50,
minlength: 8,
pwcheck:true
},
confirmpassword: {
required:true,
equalTo: "#CreatePwd"
}
},
messages: {
user_email: {
required: "Please Enter E-mail",
},
CreatePwd: {
required: "Please Enter Password",
},
confirmpassword: {
required: "Please Enter Confirm Password",
}
},
submitHandler: function(form) {
var $form_id = '#register_post';
var form = document.forms.namedItem("register_post");
var formdata = new FormData(form);
var $inputs = $($form_id+' :input:not(input[name=_token] :input)');
$inputs.prop("disabled", true);
request = $.ajax({
async: true,
type: "POST",
dataType: "json",
contentType: false,
url: "{{ URL::to('/portal/register') }}",
data: formdata,
processData: false,
success: function (result) {
alert(result);
},
timeout: 1000000
});
request.always(function () {
$inputs.prop("disabled", false);
});
}
});
});
</script>
route:
Route::get('/portal/register', 'PortalController#register');
Route::post('/portal/register', ['as' => 'portal.register.post', 'uses' => 'PortalController#postRegister']);
In the above code I am simply want to get response in my alert function after ajax success but what happen when I click on form submit button then it show status code: 302 and not able to get response in alert function. I don't know where I am doing wrong? Please help me to solve this.
Thank you

How to load alert plugin when form is submited

I am using an alert plugin and I want it to load the alert-success when the form is submitted under the .done function in my script. Plugin page here.
The plugin works with a button like this:
<button id="alert-success" class="bordered" >Try out!</button>
then when the user clicks the button it calls the jquery $(document).ready and executes the plugin. All I want to accomplish is to be loaded without the button when the form is submitted.
My form script:
var form = $('#contact');
form.submit(function (event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
var $form = $(this);
var name= $('#fname').val();
var email= $('#email').val();
var Message = $('#msg').val();
var selectedOption = document.getElementById("country").value;
$.ajax({
type: 'POST',
url: '../sendemail.php',
data: {
Name: name,
Email: email,
message: Message,
Country : selectedOption,
},
beforeSend: function () {
form.append(form_status.html(sending. . .
<i class="material-icons w3-spin w3-text-indigo" style="font-size:30px">mail_outline</i>').fadeIn()); }
}).done(function (data) {
form_status.html('<i id="alert-success" class="bordered material-icons w3-text-green" style="font-size:30px">done</i> message sent!').hide(10000);
});
document.getElementById("fname").value = "";
document.getElementById("email").value = "";
document.getElementById("country").value = "";
document.getElementById("msg").value = "";
});//end contact form
Script that executes when the button is clicked:
$(document).ready(function() {
var variants = {
'alert-success': {
args: [
{
content: 'Success! Message sent!',
icon: $.sweetModal.ICON_SUCCESS
}
]
},
};
for (var key in variants) {
if (variants.hasOwnProperty(key)) {
var variant = variants[key];
$('#' + key).on('click', { variant: variant }, function(e) {
var variant = e.data.variant;
variant.fn = variant.fn || $.sweetModal;
variant.fn.apply(this, variant.args);
});
} }
});
try adding this inside done method
$.ajax({
type: 'POST',
url: '../sendemail.php',
data: {
Name: name,
Email: email,
message: Message,
Country : selectedOption,
},
success:function()
{
// after success show modal
$.sweetModal({
title: "Title here",
message: "",
content: "Alert Success",
classes: ["success"],
showCloseButton: !0,
blocking: !0,
timeout: null,
theme: $.sweetModal.THEME_LIGHT,
type: $.sweetModal.TYPE_MODAL,
});
}
});
Customize as per your need. Customization options are on the plugin page

how to validate a same form in different button click using jquery

edit-txt,updatePassword are two buttons in a single form superAdminDetailsForm . i want to valide this form in both button click. I wrote form validation on each button click .but it doesn't work. edit-txt button is type of text and update password is type of button
$().ready(function() {$('#edit-txt').on('click', function() {
$("#superAdminDetailsForm").validate({
rules: {
superadminEmail:{
required:true,
email:true
},
},
messages: {
superadminEmail:"Please enter your Email id"
},
submitHandler: function(){
var formData =$("#superAdminDetailsForm").serialize();
$.ajax({
url:'/accounts',
type:'post',
datatype: 'json',
data: formData,
success : function(response){
if(response == "true"){
window.location='/accounts';
} else {
alert("false")
}
},
error: function (request,status, error) {
}
});
return false;
}
});
});
$('#updatePassword').on('click', function() {$("#superAdminDetailsForm").validate({
rules: {
oldPassword:"required",
newPassword:"required",
confirmpassword:{
require :"true",
equalTo : "#oldPassword"
}
},
messages: {
oldPassword:"Please enter Old Password ",
newPassword: "Please enter New Password",
confirmpassword:"Retype password is incorrect"
},
submitHandler: function(){//to pass all data of a form serial
var formData =$("#superAdminDetailsForm").serialize();
$.ajax({
url:'/changePassword',
type:'post',
datatype: 'json',
data: formData,
success : function(response){
if(response == "true"){
window.location = '/accounts';
} else {
alert("password incorrect");
}
},
error: function (request,status, error) {
}
});
return false;
}
});
});
});

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;
},

jquery image validation not working for array

jQuery validation is working fine but it's not working for array. Please check the working code in here.
http://jsfiddle.net/rq5ra/1050/
If I added array in input then it's not working.
html code
<form id="createprofile">
<input type="file" name="profilepic[]">
<input type="file" name="profilepic[]">
<input type="submit" />
</form>
jQuery code
$.validator.addMethod('filesize', function (value, element, param) {
return this.optional(element) || (element.files[0].size <= param)
}, 'File size must be less than {0}');
jQuery(function ($) {
"use strict";
$('#createprofile').validate({
errorElement: "label"
, errorClass: "has-error"
, submitHandler: function (form) {
form.submit(); //return false;
}
, highlight: function (element) {
$(element).closest('.form-group').removeClass('success').addClass('has-error');
}
, rules: {
profilepic[]: {
extension: "jpg,jpeg"
, filesize: 300000, //500kb
}
},
messages: {
profilepic[]: {
extension: "Please upload only jpg, jpeg format"
,filesize: "Please upload maximum 500Kb"
}
}
});
});
Please help me to fix it.
Please add "profilepicp[]"
working code http://jsfiddle.net/rq5ra/1052/
$.validator.addMethod('filesize', function (value, element, param) {
return this.optional(element) || (element.files[0].size <= param)}, 'File size must be less than {0}');
jQuery(function ($) {
"use strict";
$('#createprofile').validate({
errorElement: "label"
, errorClass: "has-error"
, submitHandler: function (form) {
form.submit(); //return false;
}
, highlight: function (element) {
$(element).closest('.form-group').removeClass('success').addClass('has-error');
}
, rules: {
"profilepic[]": {
extension: "jpg,jpeg"
, filesize: 300000, //500kb
}
, profileurl: {
remote: {
url: "http://localhost:8888/codeigniternew/edit/username_exists"
, type: "post"
}
}
, email: {
required: true
, remote: {
url: "http://localhost:8888/codeigniternew/edit/email_exists"
, type: "post"
}
}
},
messages: {
"profilepic[]": {
extension: "Please upload only jpg, jpeg format"
,filesize: "Please upload maximum 500Kb"
}
}
});
});
html code
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<form id="FORM_SEND_IMAGE">
<input type="file" id="file" />
<input type="submit" value="submit" />
</form>
jquery code
function getExtension(filename) {
var parts = filename.split('.');
return parts[parts.length - 1];
}
function isImage(filename) {
var ext = getExtension(filename);
switch (ext.toLowerCase()) {
case 'jpg':
case 'png':
case 'gif':
//etc
return true;
}
return false;
}
$(document).on('submit', '#FORM_SEND_IMAGE', function(e) {
e.preventDefault();
e.stopPropagation();
function failValidation(msg) {
alert(msg); // just an alert for now but you can spice this up later
return false;
}
var file = $('#file');
if (!isImage(file.val())) {
return failValidation('Please select a valid image');
}
var form_data = new FormData($(this)[0]);
$.ajax({
url: base_url + 'gallery/add',
type: 'POST',
data: form_data,
dataType: 'json',
beforeSend: function() {
console.log('before');
},
error: function(error) {
console.log(error);
},
success: function(data) {
console.log(data);
},
complete: function() {
console.log('complete');
},
processData: false,
contentType: false
});
});
demo jsfiddle

Categories