ajax custom dialog box upon success - javascript

I've coded a custom dialog/modal box as follows:
<div id="somedialog" class="dialog">
<div class="dialog__overlay"></div>
<div class="dialog__content">
<h2><strong>Howdy</strong>, I'm a dialog box</h2><
div><button class="action" data-dialog-close>Close</button></div>
</div>
</div>
It is currently triggered by a button with the javascript code as follows:
<script src="js/classie.js"></script>
<script src="js/dialogFx.js"></script>
<script>
(function() {
var dlgtrigger = document.querySelector( '[data-dialog]' ),
somedialog = document.getElementById( dlgtrigger.getAttribute( 'data-dialog' ) ),
dlg = new DialogFx( somedialog );
dlgtrigger.addEventListener( 'click', dlg.toggle.bind(dlg) );
})();
</script>
…where our trigger button has the data-attribute data-dialog="somedialog".
However, now I want to call this custom dialog only when my AJAX returns successful and pass in the message from AJAX into the dialog's <h2> text. How do I actually do that?
ajax call:
<script>
$(document).on("click", "#submit", function(){
var $self = $(this);
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var request = $.ajax({
url: "login.php",
type: "POST",
data: { username: username, password: password},
beforeSend: function(){
$self.html("Loading please wait...");
}
});
//WHEN SUCCESS
request.success(function( data ) {
if( data == 'user' )
{
window.location.href = "filter.php";
} else if(data=='company'){
window.location.href = "filter.php";
}else {
alert("Wrong Username or Password!");
window.location.href = "indexwithlogin.php";
<insert the dialog box here>
}
});
});
</script>

From your first code block you're calling the dialog box using this line:
dlgtrigger.addEventListener( 'click', dlg.toggle.bind(dlg) );
...so it is simply the matter of calling it when a success/done response is obtained from the AJAX call. I have made some changes to your script:
Use the jqXHR deferred object .done() instead of .success(). The latter has been deprecated in favour of .done(), and the same for .error(), which is succeeded by .fail().
Convert native JS code into jQuery for the dialog box variable declaration, for consistency — although it's completely ok to use native JS, there is a lack of consistency here
Remove the window redirection by commenting it out, because it defeats the purpose of displaying the dialog box, no?
Here is the revised JS:
$(document).on("click", "#submit", function(){
var $self = $(this);
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var request = $.ajax({
url: "login.php",
type: "POST",
data: { username: username, password: password},
beforeSend: function(){
$self.html("Loading please wait...");
}
});
// When successful
// Use deferred object .done()
request.done(function(data) {
if(data=='user') {
window.location.href = "filter.php";
} else if(data=='company') {
window.location.href = "filter.php";
} else {
alert("Wrong Username or Password!");
// Call dialogue box
var dlgtrigger = $('[data-dialog]'),
somedialog = $(dlgtrigger).attr('data-dialog'),
dlg = new DialogFx( somedialog );
dlg.toggle.bind(dlg);
//window.location.href = "indexwithlogin.php";
}
});
});

use
dlg.toggle.bind(dlg)() inside success function
instead of
dlg.toggle.bind(dlg)

Related

Show modal form before ajax cal and get data from it

I have an ajax function something like this:
function foo(e, e1, curc)
{
var sender = (e && e.target) || (window.event && window.event.srcElement);
$.ajax({
type: 'POST',
url: 'script.php',
dataType: 'json',
data: "id="+e+"&mod="+e1+"&curc="+curc,
beforeSend: function() {
$('#mform').show();
},
complete: function() {
$('#fountainG').hide();
},
success: function(data) {
document.getElementById("itog").innerHTML = data.d+data.a;
},
error: function(xhr) {
document.getElementById("itog").innerHTML = '123';
}
});
}
I need to show some modal form to user, and get the data from it in ajax script. I tried to add show function to ajax beforeSend - but I do not understand how to wait for user form submit, and get data from modal form. Ajax function call in html: href="javascript:void(0)" onclick="javascript:foo(3800064420557,1,138)
You just need to re-arrange your logic. Instead of trying to show the modal "within" the ajax request, hold off on sending the ajax request until you have gotten the necessary data from the modal. Here is a rough outline, presuming that your modal element $('#mform') has a form in it with an id of myform which is the form you want to get data out of.
function foo(e, e1, curc)
{
var sender = (e && e.target) || (window.event && window.event.srcElement);
var modal = $('#mform');
var form = $('#myform', modal);
form.on( 'submit', function(){
$('mform').hide();
// make your ajax call here the same way, and inside the
// onsuccess for this ajax call you will then have access to both
// the results of your ajax call and the results of the form
// data from your modal.
$.ajax({ ... });
});
}
To get form data, you can try with below code
function foo(e, e1, curc)
{
var sender = (e && e.target) || (window.event && window.event.srcElement);
form_values = {}
$('mform').show();
$('#myForm').submit(function() {
var $inputs = $('#myForm :input');
$inputs.each(function() {
form_values[this.name] = $(this).val();
});
console.log("form data:", form_values)
// with form_values continue with your coding
$.ajax({
type: 'POST',
url: 'script.php',
dataType: 'json',
data: "id="+e+"&mod="+e1+"&curc="+curc,
success: function(data) {
$('mform').show();
document.getElementById("itog").innerHTML = data.d+data.a;
},
error: function(xhr) {
document.getElementById("itog").innerHTML = '123';
}
});
});
}
Hope it will help you :)

page redirect is not working in jquery

<script>
$(document).ready(function() {
$("#btnSubmit").live('click',function(){
var sum = '0';
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var required = $(this).attr("data-required");
var label = $(this).attr("data-label");
if(required == '1'){
if(c_data == ""){
sum += '1';
}
}
});
if(sum == "0"){
$("[id^=FormData_][id$=_c_data]").each(function(){
var c_data = $(this).val();
var admin = $(this).attr("data-admin");
var form = $(this).attr("data-form");
var component = $(this).attr("date-component");
var unic = $(this).attr("data-unic");
var user = $(this).attr("data-user");
var url = "<?php echo Yii::app()->createUrl('formdata/admin&id='.$form_id);?>";
if(c_data == ""){
var site_url = "<?php echo Yii::app()->createUrl('/formdata/deleteDetail' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
} else {
var site_url = "<?php echo Yii::app()->createUrl('/formdata/updateDetailValue' ); ?>";
jQuery.ajax({
type: "POST",
url: site_url,
data: {new_value:c_data,admin:admin,form:form,component:component,unic:unic,user:user},
cache: false,
async: false,
success: function(response){
}
});
}
});
window.location = "http://www.example.com";
}else {
if(sum != ""){
bootbox.dialog({
message: 'Please Fill All Required Field !',
title: 'Alert',
buttons: {
main: {
label: 'OK',
className: 'blue'
}
}
});
return false;
}
}
});
});
</script>
in this script window.location = "http://www.example.com"; is not working.
But I check alert message it is working fine. why its not working in if condition.
I need to redirect page when each function was completed.
please any one help me:-((((((((((((((((((((((((((((
Try this.,
window.location.href = 'http://www.google.com';
This may work for you.
Window.location.href and Window.open () methods in JavaScript
jQuery is not necessary, and window.location.replace(url) will best simulate an HTTP redirect.
still you want to do this with jQuery use this $(location).attr('href', 'url')
If I got your question correct, you want to redirect the user when all your ajax requests, within your each function, are completed. For this, you can create an array that will hold the success status of each ajax request, and depending on this array you may do your redirection task.
Add below few snippets to your existing code:
In your #btnSubmit click function (Though, I recommend you use .on() delegation method)
var ajax_succ_arr = []; // success status container
var this_ajax_succ = false; // flag
In you success function of both ajax calls (within your each function).
if(c_data == ""){
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
} else {
...
jQuery.ajax({
...
success: function(response){
if(response == "1"){
this_ajax_succ = true; // set true if required response is received
}
}
});
ajax_succ_arr.push(this_ajax_succ); // push it to the success array
}
And finally your redirection. Put this just after each function ends.
if(ajax_succ_arr.indexOf(false)<0){ // if all statuses are ok
window.location="http://www.example.com";
}
Hope this helps.

Closing a dialog box if ajax sucess

I'm using dialog box for add new users to db , I want to close dialog box if validation pass and user successfully saved. please advice
$('.add_user_link a').each(function () {
var $link = $(this);
var $dialog = $('<div id="dialog"></div>')
.load($link.attr('href') + ' #content')
.dialog({
autoOpen: false,
title: $link.attr('title'),
});
$link.click(function () {
$dialog.dialog('open');
$('#add_user').submit(function () {
url = '/user/useradd/';
$.ajax({
type: "POST",
cache: false,
url: $('#add_user').attr('action'),
data: $('#add_user').serializeArray(),
success: function (data) {
var json_obj = $.parseJSON(data);
var result = json_obj['result'];
var lname = json_obj['lname'];
var email = json_obj['email'];
var fname = json_obj['fname'];
if (!result) {
$("#dialog").dialog('close');
}
else {
//
document.getElementById('email-error').innerHTML = email;
var fname_count = $("label[id*='errorfname']").length;
$('input[name=fname]').after('<label id="errorfname"></label>');
document.getElementById('errorfname').innerHTML = fname;
var lname_count = $("label[id*='errorlname']").length;
if (lname_count == 0) {
$('input[name=lname]').after('<label id="errorlname"></label>');
document.getElementById('errorlname').innerHTML = lname;
}
}
}
});
return false;
});
return false;
});
});
I'm getting this error
jquery-1.11.1.min.js:2 Uncaught Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'
Replace:
$("#dialog").dialog('close');
With
$dialog.dialog('close')
You've already set a variable for your dialog in the click function which should be in scope so you don't need to reselect it.
UPDATE:
Element IDs should be unique so you should make the dialog ID unique when adding it for a link if there are multiple links. Otherwise, you will select multiple dialog elements when you do this $('#dialog') when there are mulitiple links.
When you do this:
$dialog = $('<div id="dialog"></div>')
the ID value "dialog" should be something unique, like "dialog1", "dialog2", etc.

Jquery send post form ajax not work

am try to send form ajax like this code
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#non").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { title: $('#mak').val(),meaning: $('#za').val()} );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
});
});
</script>
it not alert success,and i check action after click button is ok
If jquery.min.js added. Then please ignore it. Else add it. To get action of <form> Use var action_url = form.attr('action');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$('#non').on('submit', function(e) {
e.preventDefault();
var form = $(this);
var formData = form.serialize();
var action_url = form.attr('action');
$.ajax({
url: action_url,
type: "POST",
data: formData,
success: function (data) {
alert(data);
},
error: function () {
alert("Oops..!! Problem Ocurred. Please Try Again..!!");
}
});
});
</script>
User's Requirement
<script>
$('#non').on('submit', function(e) {
e.preventDefault();
var form = $(this);
var val1 = $('#text1').val();
var val2 = $('#text2').val();
var action_url = form.attr('action');
$.ajax({
url: action_url,
type: "POST",
data: { text1: val1, text2: val2 },
success: function (data) {
alert(data);
},
error: function () {
alert("Oops..!! Problem Ocurred. Please Try Again..!!");
}
});
});
Or, check Send FormData and String Data Together Through JQuery AJAX?
Additional
<script>
$('#non').on('submit', function(e) {
e.preventDefault();
var form = $(this);
var formData = form.serialize();
var title_f = $('#mak').val();
var meaning_f = $('#za').val();
formData.append(title,title_f);
formData.append(meaning,meaning_f);
var action_url = form.attr('action');
$.ajax({
url: action_url,
type: "POST",
data: formData,
success: function (data) {
alert(data);
},
error: function () {
alert("Oops..!! Problem Ocurred. Please Try Again..!!");
}
});
});
Why not attach your Handler directly to the Submit-Button & do something like this:
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#submitBtn").on("click", function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
// HERE IS THE PROBLEM... THE $(this) VARIABLE POINTS TO THE BUTTON, NOT FORM.
var $form = $( this ).parentsUntil("form").parent("form"),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { title: $('#mak').val(),meaning: $('#za').val()} );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
});
});

JS/AJAX Auto submit form: Disabling enter key to prevent page refresh

I am using a function that will submit with ajax and without the help of a button click. But I am currently undergoing two issues which with trial and error haven't found plausible solutions:
First is there any way I can disable the enter button click(this causes the whole page to refresh)?
JSFIDDLE basic example in how the JS function works
Second, It feels like I am going the roundabout way to display what has been posted. How can I change this part of the function $('#special').html('<p>' + $('#resultval', result).html() + '</p>'); to have it POST just inside a div called #special without the need of span or <p> #resultval?
Everytime i echo through php I have to do set it like this to display a result: <div id="special"><span id="resultval">This is the result.</span></div>
<script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(){
$.ajax({ type: "POST",
url: "posting.php",
data: dataString,
success: function(result){
$('#special').html('<p>' + $('#resultval', result).html() + '</p>');
}
});
return false;
}
$('#ytinput').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#ytinput").val();
dataString = 'name='+ name;
});
});
</script>
$(document).ready(function() {
var timer = null;
var dataString;
function submitForm(event){// the function call on click or on submit onclick=submitForm(event);
event.preventDefault(); //to prevent enter key
$.ajax({ type: "POST",
url: "posting.php",
data: dataString,
success: function(result){
$('#special').text(result); //you can use text() or html() only
}
});
return false;
}
$('#ytinput').on('keyup', function() {
clearTimeout(timer);
timer = setTimeout(submitForm, 050);
var name = $("#ytinput").val();
dataString = 'name='+ name;
});
});

Categories

Resources