International Telephone Input JQuery Plugin - Call set instance after ajax html response - javascript

I'm using this plugin to validate a tel html input https://github.com/jackocnr/intl-tel-input
I send the form through an ajax response and receive the html structure updated. When I set this html to the page, it loses the plugin instance and it's a normal tel input again, without the plugin instance attached to it. How do I call the previous instance to the new input received that it's technically the same?
// Call and set plugin instance
var inputRec = document.querySelector('#phone_number_rec');
var itiRecruiter = window.intlTelInput(inputRec, {
hiddenInput: "full",
initialCountry: "auto",
geoIpLookup: function(callback) {
$.get('https://ipinfo.io', function() {}, "jsonp").always(function(resp) {
var countryCode = (resp && resp.country) ? resp.country : "us";
callback(countryCode);
});
},
utilsScript : base_url + '/public/assets/modules/intl-tel-input-master/build/js/utils.js',
});
// Send form through ajax
// Submit recruiter experience
$('body').on('submit', '.submit-individual-recruiter', function(e){
e.preventDefault(e);
var form = $(this);
var post_url = $(this).attr('action'); //get form action url
var form_data = $(this).serialize(); //Encode form elements for submission
if ($(this)[0].checkValidity() === false) {
event.stopPropagation();
form.addClass('was-validated');
} else {
$(this).addClass('was-validated');
var responseState = false;
var jqxhr = $.ajax({
url : post_url,
type: 'post',
data : form_data,
}).done(function(response){
response = JSON.parse(response);
if(response.result == 'success'){
responseState = true;
iziToast.success({
message: response.message,
position: "topRight"
});
} else if(response.result == 'error'){
iziToast.error({
message: response.message,
position: "topRight"
});
}
});
jqxhr.always(function() {
if(responseState == true){
var $row = $('#recruiter-experience');
var url = base_url + '/get_info/experience';
$.post( url, function( response ) {
response = JSON.parse(response);
$row.html(response.recruiterView.data);
});
}
});
}
});

well you replaced the dom, so the element that u initialized the tel-validator is gone.
one thing u could do is wrap your initializer into a function so u can just call it again
function initializeTel() {
var inputRec = document.querySelector('#phone_number_rec');
var itiRecruiter = window.intlTelInput(inputRec, {
hiddenInput: "full",
initialCountry: "auto",
geoIpLookup: function(callback) {
$.get('https://ipinfo.io', function() {}, "jsonp").always(function(resp) {
var countryCode = (resp && resp.country) ? resp.country : "us";
callback(countryCode);
});
},
utilsScript : base_url + '/public/assets/modules/intl-tel-input-master/build/js/utils.js',
});
}
// call it initially
initializeTel();
// and then after u received and parsed the response
initializeTel();

Related

how to store data using jquery ajax?

I am using this jquery code to store data using ajax but if I use
let loc = $('[name="ot_location"]').val(position.coords.latitude+','+position.coords.longitude);
in console it says ReferenceError: loc is not defined I am new to javascript and learning and I need help
html
<span>Visit Clear</span><br><input type="checkbox" data-id="{{ $customer->id }}" name="visit_clear" class="js-switch2 js-switch" {{ $customer->visit_clear == 1 ? 'checked' : '' }}>
Java script
$(document).ready(function(){
$(document).on('change', '.js-switch2', function () {
let visit_clear = $(this).prop('checked') === true ? 1 : 0;
if ($(this).prop('checked') == 1) {
$(this).closest('tr').addClass('visitclear');
//ot get location
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
alert("Try any other browser");
}
}
function showPosition(position) {
let loc = $('[name="ot_location"]').val(position.coords.latitude+','+position.coords.longitude);
}
$(document).ready(getLocation);
} else {
$(this).closest('tr').removeClass('visitclear');
}
let userId = $(this).data('id');
$.ajax({
type: "GET",
dataType: "json",
url: '{{ route('users.update.visit_clear') }}',
data: {'visit_clear': visit_clear, 'user_id': userId , 'ot_location': loc},
success: function (data) {
console.log(data.message);
}
});
});
});
Controller
public function visitclear(Request $request)
{
$customer = Customer::findOrFail($request->user_id);
$customer->visit_clear = $request->visit_clear;
$customer->ot_location = $request->ot_location;
$customer->visit_date = date('Y-m-d H:i');
$customer->save();
return response()->json(['message' => 'User status updated successfully.']);
}
i want on click check box store geo cords in var loc and store it using ajax how i can do that?
use var in place of let in your code for loc and see if the reference error goes away.
So, your let loc = $('[name="ot_location"]').val(position.coords.latitude+','+position.coords.longitude);
should be
var loc = $('[name="ot_location"]').val(position.coords.latitude+','+position.coords.longitude);

Javascript function not called from jquery

I have a script with two methods one that's submits a form with Ajax
function saveCustomer(){
$('#createCustomer').submit(function(ev) {
ev.preventDefault();
$('#submit').attr('disabled',true);
var $inputs = $('#createCustomer :input');
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
$.ajax({
url: '/customer',
type : 'POST',
data : values,
success : function(data){
//check if controller validation send customer exist
if(data.confirmation){
$("#confirmation").show();
}
else{
$('#createCustomer :input').val('');
$("#customer").hide();
//assign values to success modal
$('#firstName').val(data.customer.firstName);
$('#lastName').val(data.customer.lastName);
$('#street').val(data.address.street);
$('#businessName').val(data.customer.businessName);
$('#submit').attr('disabled',false);
}
},
error : function(error){
$('#submit').attr('disabled',false);
}
});
});
}
And a function that adds another input to the form and calls the first function
$('#proceedWithSave').on('click', function(){
var input = $("<input>")
.attr("type", "hidden")
.attr("name", "proceed");
$('#createCustomer').append($(input));
saveCustomer();
});
Now the second function is called successfully because it adds the new input but the first function is not called because no ajax call is made.
Any ideas on what can be wrong here?
You want to submit the form, using Ajax, on click of $('#proceedWithSave')...
So just remove the $('#createCustomer').submit(function(ev) { line and its closing }); bracket.
function saveCustomer(){
//$('#createCustomer').submit(function(ev) {
//ev.preventDefault();
$('#submit').attr('disabled',true);
var $inputs = $('#createCustomer :input');
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
$.ajax({
url: '/customer',
type : 'POST',
data : values,
success : function(data){
//check if controller validation send customer exist
if(data.confirmation){
$("#confirmation").show();
}
else{
$('#createCustomer :input').val('');
$("#customer").hide();
//assign values to success modal
$('#firstName').val(data.customer.firstName);
$('#lastName').val(data.customer.lastName);
$('#street').val(data.address.street);
$('#businessName').val(data.customer.businessName);
$('#submit').attr('disabled',false);
}
},
error : function(error){
$('#submit').attr('disabled',false);
}
});
//});
}
$('#proceedWithSave').on('click', function(){
var input = $("<input>")
.attr("type", "hidden")
.attr("name", "proceed");
$('#createCustomer').append($(input));
saveCustomer();
});

AJAX: form.serialize() and csrf token together?

Can someone say whats wrong with this lane data:... inside saveForm function?
I have list of tasks in my page. Every task has there own form where users can send comments. It means that I have several forms in one page. When I add new task AJAX update list of comments and then I try to send comment by one of the form and it raise error : “CSRF token missing or incorrect”. I have {% csrf_token %} in all my forms.
It seems like I need send CSRF in AJAX. Where I did mistake?
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
// TASK
$(function () {
var loadForm = function () {
var btn = $(this);
$.ajax({
url: btn.attr("data-url"),
type: 'get',
dataType: 'json',
beforeSend: function () {
$("#modal").modal("show");
},
success: function (data) {
$("#modal .modal-content").html(data.html_group_task_form);
}
});
};
var saveForm = function () {
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize().append('csrfmiddlewaretoken', getCookie(csrftoken)),
type: form.attr("method"),
dataType: 'json',
success: function (data) {
if (data.form_is_valid) {
$("#task-list").html(data.html_task);
$("#modal").modal("hide");
}
else {
$("#modal .modal-content").html(data.html_task_form);
}
}
});
return false;
};
// Create task
$("#task-add-button").click(loadForm);
$("#modal").on("submit", ".js-task-add-form", saveForm);
// Update task
$("#task-list").on("click", "#js-edit-task-button", loadForm);
$("#modal").on("submit", ".js-task-edit-form", saveForm);
});
//TASK COMMENT ADD
$(".task-comment-form").submit(function(event) {
event.preventDefault();
console.log(event.preventDefault());
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize().append('csrfmiddlewaretoken', getCookie(csrftoken)),
type: form.attr("method"),
dataType: 'json',
success: function (data) {
var current_group = form.closest('.custom-list-group');
if (data.form_is_valid) {
current_group.find(".task-comments").html(data.html_task_comment);
}
else {
current_group.find(".task-comment-form").html(data.html_task_comment_form);
}
},
});
form[0].reset();
return false;
});
CODE ABOUT COMMENT ADD:
views.py:
def task_comment_add(request, project_code, task_code):
data = dict()
project = get_object_or_404(Project, pk=project_code)
task = get_object_or_404(Task, pk=task_code)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.author = request.user
comment.save()
task.comments.add(comment)
data['form_is_valid'] = True
data['html_task_comment'] = render_to_string('project/task_comment_list.html' {'task': group_task})
else:
data['form_is_valid'] = False
else:
form = CommentForm()
context = {'project': project, 'task': task, 'form': form}
data['html_task_comment_form'] = render_to_string('project/task_comment_form.html', context, request=request)
return JsonResponse(data)
JS:
// TASK COMMENT ADD
$(".task-comment-form").submit(function(event) {
event.preventDefault();
console.log(event.preventDefault());
var form = $(this);
$.ajax({
url: form.attr("action"),
data: form.serialize(),
type: form.attr("method"),
dataType: 'json',
success: function (data) {
var current_group = form.closest('.custom-list-group');
if (data.form_is_valid) {
current_group.find(".task-comments").html(data.html_task_comment);
}
else {
current_group.find(".task-comment-form").html(data.html_task_comment_form);
}
}
});
form[0].reset();
return false;
});
.append is for DOM elements.
The result of .serialize is a string.
Why don't you just put the token in a hidden input in the form with a 'name' attr of 'csrfmiddlewaretoken'?
That will serialize it with the rest of your form data.
Here's what I did that worked for ajax forms with Django:
$('#ajax_form').submit(function(e){
e.preventDefault();
var form = this;
var action = $(form).attr('action'); // grab the action as url
var form_array = $(form).serializeArray(); // use serializeArray
form_array.push({ // *expand the array to include a csrf token*
name: 'csrfmiddlewaretoken',
value: getCookie('csrftoken') // getCookie function from django docs
});
var form_data = $.param(form_array); // set it up for submission
$.post(action,form_data,function(resp){
// do stuff after receiving resp
});
});
Basically, I used jquery's .serializeArray() instead of serialize.
.serializeArray() gives you an array of objects like this:
[{name:'name1',value:'value1'},{name:'name2',value:'value2'}]
calling $.param(serilaized_array_data) turns it into a string for submitting. So the key is to add the csrf token to the array. I did that in the code above on the line from_array.push({... with the *'s in the comments.
The problem was in my view. I use this and error disappeared:
context = {...}
context.update(csrf(request))

Jquery popup modal, how to call from a js function

After I submit form, below line opens a popup modal.
<input class="js__p_start" type="submit" value="submit" name="submit"/>
I want to open this popup from a JS function where I will check if form field is not empty then only call this popup modal, otherwise will give alert to fill the form field.
Any way I call call this popup using that class from another JS function.
In case you need source code, see the source code of http://www.hunt4flat.com
Here is my code:
<script>
$(document).ready(function(){
$("#hidden_form").submit(function(){
var mobile = $("#mobile").val();
var name = $("#name").val();
var dataString = 'mobile='+ mobile + '&name='+ name;
if(name=='')
{
alert("Please Enter your name");
}
else
{
$.ajax({
type: "POST",
url: "ritz.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
//I Want to call Popup here, so that popup will appear only after user properly entereed form fields
}
});
}
return false;
});
});
</script>
How to do it?
JS file is:
(function($) {
$.fn.simplePopup = function(event) {
var simplePopup = {
settings: {
hashtag: "#/",
url: "popup",
event: event || "click"
},
initialize: function(link) {
var popup = $(".js__popup");
var body = $(".js__p_body");
var close = $(".js__p_close");
var routePopup = simplePopup.settings.hashtag + simplePopup.settings.url;
var cssClasses = link[0].className;
if (cssClasses.indexOf(" ") >= 0) {
cssClasses = cssClasses.split(" ");
for (key in cssClasses) {
if (cssClasses[key].indexOf("js__p_") === 0) {
cssClasses = cssClasses[key]
}
};
}
var name = cssClasses.replace("js__p_", "");
// We redefine the variables if there is an additional popap
if (name !== "start") {
name = name.replace("_start", "_popup");
popup = $(".js__" + name);
routePopup = simplePopup.settings.hashtag + name;
};
link.on(simplePopup.settings.event, function() {
simplePopup.show(popup, body, routePopup);
return false;
});
$(window).on("load", function() {
simplePopup.hash(popup, body, routePopup);
});
body.on("click", function() {
simplePopup.hide(popup, body);
});
close.on("click", function() {
simplePopup.hide(popup, body);
return false;
});
$(window).keyup(function(e) {
if (e.keyCode === 27) {
simplePopup.hide(popup, body);
}
});
},
centering: function(popup) {
var marginLeft = -popup.width()/2;
return popup.css("margin-left", marginLeft);
},
show: function(popup, body, routePopup) {
simplePopup.centering(popup);
body.removeClass("js__fadeout");
popup.removeClass("js__slide_top");
location.hash = routePopup;
document.getElementById("menu_but").style.visibility = "hidden";
document.getElementById("toTop").style.visibility = "hidden";
document.getElementById("cbp-spmenu-s1").style.visibility = "hidden";
},
hide: function(popup, body) {
popup.addClass("js__slide_top");
body.addClass("js__fadeout");
location.hash = simplePopup.settings.hashtag;
document.getElementById("menu_but").style.visibility = "visible";
document.getElementById("toTop").style.visibility = "visible";
document.getElementById("cbp-spmenu-s1").style.visibility = "visible";
},
hash: function(popup, body, routePopup) {
if (location.hash === routePopup) {
simplePopup.show(popup, body, routePopup);
}
}
};
return this.each(function() {
var link = $(this);
simplePopup.initialize(link);
});
};
})(jQuery);
Using my library:
$.ajax({
type: "POST",
url: "ritz.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
//I Want to call Popup here, so that popup will appear only after user properly entereed form fields
var popup = new jPopup({
title: "<h2>Succes</h2>",
content: "<p>Form has been sent succesfully, results: "+result+"</p>",
buttons: [{
text: "Close"
}]
});
popup.open();
}
});
Library: https://github.com/seahorsepip/jPopup
You can do the same with a jquery ui dialog but jquery ui dialogs require too much js and aren't that great in my opinion :P

How do I exit the click function?

So with this example I have form with a hidden field and a button called ban user. When the ban user button is clicked, it submits the value in the hidden field and sends the ajax request to a java servlet. If it is successful, the user is banned and the button is changed to "unban user". The problem is when I click the button once and ban a user and I try to click it again to unban, I'm still inside the click event for the ban user and I get the alert "Are you sure you want to ban the user with the id of ...?". How do I exit the click event to make sure when the button is clicked a second time, it starts at the beginning of the function and not inside the click function? I have tried using 'return;' as you can see below but that doesn't work.
$(document).delegate('form', 'click', function() {
var $form = $(this);
var id = $form.attr('id');
var formIdTrim = id.substring(0,7);
if(formIdTrim === "banUser") {
$(id).submit(function(e){
e.preventDefault();
});
var trimmed = id.substring(7);
var dataString = $form.serialize();
var userID = null;
userID = $("input#ban"+ trimmed).val();
$("#banButton"+ trimmed).click(function(e){
e.preventDefault();
//get the form data and then serialize that
dataString = "userID=" + userID;
// do the extra stuff here
if (confirm('Are you sure you want to ban the user with the id of ' + trimmed +'?')) {
$.ajax({
type: "POST",
url: "UserBan",
data: dataString,
dataType: "json",
success: function(data) {
if (data.success) {
//$("#banUser"+trimmed).html("");
$('#banUser'+trimmed).attr('id','unbanUser'+trimmed);
$('#ban'+trimmed).attr('id','unban'+trimmed);
$('#banButton'+trimmed).attr('value',' UnBan User ');
$('#banButton'+trimmed).attr('name','unbanButton'+trimmed);
$('#banButton'+trimmed).attr('id','unbanButton'+trimmed);
$form = null;
id = null;
formIdTrim = null;
return;
}else {
alert("Error");
}
}
});
} else {
}
});
}
else if(formIdTrim === "unbanUs") {
//Stops the submit request
$(id).submit(function(e){
e.preventDefault();
});
var trimmed = id.substring(9);
var dataString = $form.serialize();
var userID = null;
userID = $("input#unban"+ trimmed).val();
$("#unbanButton"+ trimmed).click(function(e){
e.preventDefault();
//get the form data and then serialize that
dataString = "userID=" + userID;
// do the extra stuff here
if (confirm('Are you sure you want to UNBAN the user with the id of ' + trimmed +'?')) {
$.ajax({
type: "POST",
url: "UserUnban",
data: dataString,
dataType: "json",
success: function(data) {
if (data.success) {
//$("#banUser"+trimmed).html("");
$('#unbanUser'+trimmed).attr('id','banUser'+trimmed);
$('#unban'+trimmed).attr('id','ban'+trimmed);
$('#unbanButton'+trimmed).attr('value',' Ban User ');
$('#unbanButton'+trimmed).attr('name','banButton'+trimmed);
$('#unbanButton'+trimmed).attr('id','banButton'+trimmed);
$form = null;
id = null;
formIdTrim = null;
return;
}else {
alert("Error");
}
}
});
} else {
}
});
}
});
Try with:
$("#banButton"+ trimmed).off('click').on('click', (function(e){......
I had similar problem and this was solution

Categories