JQuery SmartWizard Form Submission - javascript

So I have a Spring Boot API project using Jquery SmartWizard. The first Step of 4 contains a simple form. For the sake of testing, am using with one field (ID: first-name).
On clicking of the Next button of the Wizard, the jquery method should execute, form details posted to the database and then go to the Next Step of the Wizard(i.e. 2).
$( document ).ready(function() {
$('#wizard').smartWizard({
onLeaveStep: function() {
ajaxPost();
}
});
$('.buttonNext').addClass('btn btn-success');
$('.buttonPrevious').addClass('btn btn-primary');
$('.buttonFinish').addClass('btn btn-default');
function ajaxPost(){
var formData = {
name : $("#first-name").val()
//lastname : $("#lastname").val()
};
// DO POST
$.ajax({
type : "POST",
contentType : "application/json",
url : "http://localhost:8080/api/uc/create",
data : JSON.stringify(formData),
dataType : 'json',
success : function(result) {
console.log(result)
},
error : function(e) {
alert("Error!");
console.log("ERROR: ", e)
}
});
//$('#wizard').smartWizard('goForward');
// Reset FormData after Posting
//resetData();
}
function resetData(){
$("#first-name").val("");
//$("#lastname").val("");
}
});
The ajaxPost() works but the Wizard doesnt move to the next step. If I uncomment this line //$('#wizard').smartWizard('goForward'); The ajaxPost() function replicates alot of data in the database then.
How do I get the Wizard to move to Step 2 after doing the form submit via the ajax functionality by clicking on the next button.

The ajax post is asynchronous, so the javascript needs to wait for the response.
Most likely you want to continue with the wizzard, only if the ajax request was successful.
So move 'goForward' into the success handler :
...
success : function(result) {
$('#wizard').smartWizard('goForward');
},
...
You wrote, many entries are added to the database. This can have two reasons :
The server does not work correctly, so add breakpoints there to see when its called and how many entries per call are created
The client calls the server many times, so you need to debug the frontend

Related

Do a form submit calling a function instead create specific submit on its id

I did on a project many forms with its "" in the part of page (generated by php) that add specific function to it per form id and are working, for example:
$("#fregistrazione").submit(function(event){
...
}
I did the same with an html part loaded with ajax request but is not working.
I thinked to do in a different way with the same function called by many form submit, instead having one different defined for any form on any form submit, call a function with additional parameter that do the specific form things with less code duplication but I'm unable to have it working.
I did many try, for example:
<form id="f_man-marker_edit-marker" method="post" action="#" onsubmit="TM.editMarker(this)">
...
...
TM.editMarker = function(rform){
// Abort any pending request
if (request) { request.abort(); }
let form = $(rform);
// Let's select and cache all the fields
let inputs = form.find("input, select, button, textarea");
// Serialize the data in the form
let serializedData = form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
inputs.prop("disabled", true);
request = $.ajax({
url: "ajax.php?req=man-marker_edit-marker",
type: "post",
data: serializedData,
dataType: "html"
});
request.done(function (response){
$("#ajaxoutput2").empty().append(response);
$("#ResultModal2").modal("show");
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"Ajax man-marker_edit-marker request failed. The following error occurred: "+
textStatus, errorThrown
);
});
request.always(function () {
inputs.prop("disabled", false);
});
};
but on submit reload the page with parameters as "get" in url and didn't execute the edit marker function.
Can someone please tell me what I did wrong and how to do a correct call of a function from the form submit instead do a .submit on any form id containing dozens of duplicate lines for each form and not working if generated by a code that is received through ajax request?
Thanks for any reply and sorry for my bad english.
EDIT:
I did what suggested by ChrisG and I tried to add a parameter in TM.editMarker but I not found how to maintain correctly event as first parameter and add 2 other parameters.
For example adding 1 parameter:
TM.editMarker = function (e, ajax_request) {
...
I tried (even if IDE gave me event as deprecated):
$('#f_man-marker_edit-marker').on('submit', TM.editMarker(event, 'man-marker_edit-marker'));
And also without but in both case don't work.
EDIT2:
solved with:
$('#f_man-marker_edit-marker').on('submit', function(e){
TM.editMarker(e, $(this), 'man-marker_edit-marker');
});
...
TM.editMarker = function (e, form, ajax_request) {
...
but I'm open to better solutions.
Simple Answer:
You manipulated the DOM, so your selector is not there yet on event-binding.
Use a parent selector thats already there like document
$(document).on("submit", "#fregistrazione", function(event){
event.preventDefault(); // stop the form submitting if needed
...
});
this way it will work

Jquery Ajax Callback not working in proper order

I have a piece of code I want to run after all the ajax is completed.
The function I wish to run is:
function autoContinueCart(){
$('.nextSection a:visible').click();
}
This click event runs validating script and moves to next section. Heres the main ajax.
$('#SubmitLoginOpc').click(function () {
$.ajax({
type:'POST',
url:authenticationUrl,
async:false,
cache:false,
dataType:"json",
data:'SubmitLogin=true&ajax=true&email=' + encodeURIComponent($('#login_email').val()) + '&passwd=' + encodeURIComponent($('#login_passwd').val()) + '&token=' + static_token,
success:function (jsonData) {
if (jsonData.hasError) {
//error stuff
}
else {
// update token
static_token = jsonData.token;
$('#dlv_label, #new_label').removeClass('new-l').addClass('logged-l'); // change label on delivery address section
updateNewAccountToAddressBlock();
// RESET ERROR(S) MESSAGE(S)
$('#opc_account_errors').html('').hide();
$('#opc_account_errors_invoice').html('').hide();
//It doesnt work here
//autoContinueCart();
}
},
//doesnt work here
// complete:autoContinueCart
});
return false;
});
I have put this function call in the success part, which I thought would work since it is synchronous. I also put it as complete and in .done function after the ajax call and it still runs before all the inside code is complete. The function updateNewAccountToAddressBlock(); basically makes another jquery ajax request with this type async:true, and returns json that is then used in about 10 functions or sub functions in the success call. One of these uses this data to fill out all the fields of a form. My function I am trying to call at the end is supposed to validate the info that is being populated. But no matter what I try, the validation is failing because the autoContineCart is being run before the fields are being populated. I also tried to use a callback like updateNewAccountToAddressBlock(updateAddressSelection); and then checked callback function inside of that and it also didnt work. Anyone have an idea what I could be doing wrong?
Since your call is already asynchronous, is it possible to move the processing code out of the ajax callback function? This would ensure that all of the ajax portion is complete before moving on to the processing piece.
Example:
$('#SubmitLoginOpc').click(function () {
$.ajax({
type:'POST',
url:authenticationUrl,
async:false,
cache:false,
dataType:"json",
data:'SubmitLogin=true&ajax=true&email=' + encodeURIComponent($('#login_email').val()) + '&passwd=' + encodeURIComponent($('#login_passwd').val()) + '&token=' + static_token
},
success: function(jsonData) {
$('#SubmitLoginOpc').data("some_key",jsonData);
}
//doesnt work here
// complete:autoContinueCart
});
jsonData = $('#SubmitLoginOpc').data("some_key");
if (jsonData.hasError) {
//error stuff
}
else {
// update token
static_token = jsonData.token;
$('#dlv_label, #new_label').removeClass('new-l').addClass('logged-l'); // change label on delivery address section
updateNewAccountToAddressBlock();
// RESET ERROR(S) MESSAGE(S)
$('#opc_account_errors').html('').hide();
$('#opc_account_errors_invoice').html('').hide();
//It doesnt work here
//autoContinueCart();
return false;
}
});
As the poster above said, Perhaps you could move some of the other ajax functions to run from the same js file, or move some of the Php functions to be run at the same time as the first call.
Ideally you shouldn't have to do another ajax request, because the php/whatever already has the info it needs from the client side. You should be able to send that data to other php/whatever scripts.
If you do need to do another ajax call, perhaps having the user wait a mandatory second, before you run the ajax call.
for instance:
$ajax.done(
// code
if (success)
{
setTimeout('foo', 5000);
$('#spinner').show();
}
function foo()
{
$('#spinner').hide();
//second ajax request
}

Using ajaxForm plugin on view that is itself an AJAX response

I am building a messaging system for my site. The mailbox is flat, i.e. accessing the inbox, or sending a new message does not move to another page, it just toggles divs. When a user clicks a message, an AJAX call replaces the inbox div with the chosen thread. Inside the thread view, there is a form to reply to the message.
A few problems:
From inside this thread_view, which sends an AJAX response to a div nested inside the entire mailbox div, I don't have access to document objects outside of it. So, I can't manipulate divs outside of this view, such as the one that receives the AJAX beforeSend and Success messages. I think this may be accomplished with some kind of .load(), though I'm not sure exactly how.
My AJAX doesn't fire. I am using the Ajax.Form() plugin. I think this problem might be related to the first, but I can't say for certain. I'm not sure how to begin troubleshooting the Ajax request because I get no errors in the console.
I wonder if the problem has to do with the fact that I am trying to send an ajaxRequest from a view that is itself a response from a previous ajaxRequest, i.e. the entire view for the thread is a result of the following, in the same js file as the next request:
// compose a message function
$('#send_message').on("click", function(e) {
var send_message_options = {
type: 'post',
url: "/users/new_message",
beforeSend: function() {
//Display a loading message while waiting for the ajax call to complete
$('#message').html("Sending message...");
},
// Hide form and display results
success: function(response) {
$('#message').html(response);
}
};
$('#message_form').ajaxForm(send_message_options);
});
My new AJAX request, which does nothing:
$('#reply_in_thread').on("submit", function(e) {
e.preventDefault();
console.log("trying for reply");
var reply_options = {
type: 'post',
url: "/users/reply",
beforeSend: function() {
//Display a loading message while waiting for the ajax call to complete
$('#reply_message').html("Sending message...");
},
// Hide form and display results
success: function(response) {
$('#reply_message').html(response);
}
};
$('#reply_in_thread').ajaxForm(reply_options);
});
I couldn't say why the ajaxForm() plugin failed, but a jquery $.post was successful. The code that worked below:
$('#reply_in_thread').on("submit", function(e) {
e.preventDefault();
var data = $(this).serialize();
$.post('/users/reply',data,function(response){
$('#reply_message').html(response);
})
});

alert dialogue during a process with javascript

using ASP .Net MVC 4.0 , vs10 , MSSQL 2008
I have a stored procedure, which is executed in one of my page. it generally takes 30 to 50 second to execute. I want to show a alert dialogue where an gif image will be loaded during this process time. I am executing stored procedure with sqlcommand. The process started on clicking Process button. after finishing the process, the page returns another view.
I have poor knowledge of javascript, so please show me a simple way.
EDIT:
Is it possible to show an image on buttonclick an do other codebehind process?
Like:
<script type="text/javascript">
function showImage() {
document.getElementById('Processing').style.visibility = visible;
}
</script>
<div id="progessbar">
<img alt="Processing" src="../../Images/Processing2.gif" id="Processing" style="visibility:hidden"/>
</div>
It will be difficult to accomplish what you're trying to do in a traditional MVC fashion since the request takes a long time. This is better accomplished using AJAX which processes your request asynchronously. I recommend also using jQueryUI dialog or any modal to show a progress indicator, or even any custom JS.
I like jQuery BlockUI personally to create the modal for me but that's just a preference.
/** Using a wrapper to show/hide the progress indicator.
Swap the blockUI with any library or custom JavaScript for displaying the progress indicator.
*/
var showProgress = function() {
$.blockUI({ message: '<img src="progressImage.gif" />' });
};
var hideProgress = function() {
$.unblockUI();
;}
/** Trigger to submit the form */
$('#submit').click(function() {
/** Show an indicator before making an AJAX request*/
showProgress();
$.ajax({
url: '/someEndpoint',
data: $.toJSON({/* some JSON param */}),
type: 'POST',
dataType: 'json',
timeout: 50000 /** Override timeout in ms accordingly */
}).done(function(data){
/** Remove the indicator once the request has succeeded and process returned data if any. */
hideProgress();
});
return false;
});
Use ajax for your process. It ll make the parallel processing for "showing gif" and completing your desired code.
You can use JQuery-AJAX with page methods this way: [1]: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
The success callback contains a parameter with the returning data.
or you can try simply this
var actionURL = "(Your disired action e.g /index.jsp)"
$.ajax({
cache:false,
url: actionURL,
beforeSend: function( xhr ) {
xhr.overrideMimeType( 'text/plain; charset=UTF-8' );
$("#progessbar").show();
//Here you can write any code to execute before the action like gif loading etc
},
success: function( data ) {
alert("Success Conditions");
//"data" is what u gets from your target. You can see by alert(data); here
//Here you can write any code which you want to execute on finding the required action successfully
},
complete: function(){
alert("Complete Conditions");
$("#progessbar").hide();
//Here you can write any code which you want to execute on completion of the required action you given in actionURL
},
error: function(){
alert("Error Conditions");
}
});
NOTE: alerts are just for explanation, you can write your own code also
For this code you have to include jquery plugins. which can be downloaded from their official site [l]: http://jquery.com/

AJAX Load Content

Im completely lost on how to work AJAX. Looked up some tutorials and all seemed pretty confusing. I ran into the problem: [ Script only runs once ].
I would use it to reload pages like so: [ http://www.roblox.com/Poison-Horns-item?id=62152671 ] so I could get the latest item prices, without refreshing the page. if anyone could help/tell/point me in the right direction, it'd help TONS.
Im somewhat a beginner scripter, so be a little patient ;)
Thanks for any help,
Alex
AJAX requests are the same as page requests (GET and POST), except that they are handled asynchronously and without leaving the current page. The response data is the source of the page you wanted to fetch. That source is useless until you parse/use it.
A simple jQuery example:
//for example, we are on example.com
$.ajax({
type : 'get', //the METHOD of the request, like the method of the form
url : 'index.php' //the url to fetch
data : { //additional data which is synonymous to:
query1 : 'foo', // - url queries
query2 : 'bar', // - form inputs
query3 : 'baz',
},
success : function(resposeText){ //response text is the raw source of the fetched resource
$(element).html(responseText); //use response as HTML for element
}
});
//this is similar to requesting:
http://example.com/index.php?query1=foo&query2=bar&query3=baz
agree with joseph. You can use ajax by javascript manner or by jQuery, I personally suggest jQuery because it is simple to implement.
$.ajax({
type: 'GET',
url: "URL you want to call" ,
data: 'Data you want to pass to above URL',
cache: true, //to enable cache in browser
timeout: 3000, // sets timeout to 3 seconds
beforeSend: function() {
//when ur ajax call generate then u can set here loading spinner
},
error: function(){
// will fire when timeout is reached
},
success: function(response){
//in response you can get your response data from above called url.
}
});

Categories

Resources