Call This Function Outside of Form Submit - javascript

I have a submit button at the end of my form that is labeled like this:
<button id="sendbutton" style="margin-left:25px;" class="btn btn-large btn-primary" type="submit">Send Responses</button>
This button calls this script:
<script type="text/javascript">
$(function() {
$('form').unbind('submit').bind('submit', function(){
$.ajax({
type: 'post',
url: 'chapter.php',
data: $("form").serialize(),
success: function() {
alert('Your answers have been saved.');
}
});
return false;
});
});
</script>
How do I create a button outside of this form structure that will call the same function?

You may create whatever button you'd like, even if its outside of the form. And then, to get that button to do the same thing you could simply do
$('#yourNewButton').click(function(){
$('form').submit();
});
Or, why not wrap up your original logic into its own function
function submitMyForm(){
$.ajax({
type: 'post',
url: 'chapter.php',
data: $("form").serialize(),
success: function() {
alert('Your answers have been saved.');
}
});
return false;
}
And then
$('#yourNewButton').click(submitMyForm);
$('form').submit(submitMyForm);

You can write a click handler to the new button and in the handler trigger the form submit using script
<button id="test" style="margin-left:25px;" class="btn btn-large btn-primary" type="button">Send Responses</button>
then
jQuery(function($){
$('#test').click(function(){
$('form').submit()
})
})

Rather than make the submit handler an anonymous function you make it a named function
function submitHandler() {
$.ajax({
type: 'post',
url: 'chapter.php',
data: $("form").serialize(),
success: function () {
alert('Your answers have been saved.');
}
});
return false;
}
then change your code to
$('form').unbind('submit').bind('submit', submitHandler);
That way you can call that function whenever you like simple by writing submitHandler();

Related

Event needs multiple clicks in Jquery

I am trying to get the response from the PHP scripts but the button takes multiple clicks on firing the event. I read about that on Google but unable to understand that why it is going to happen.
Html Code
<form action="javascript:MyResults()">
<input type="submit" value="Search" id ="button1"/>
</form>
Javascript Code
function MyResults(){
$(document).ready(function(){
$("#button1").click(function(){
var searchData = $("#search").val();
alert(searchData);
$.ajax({
url: "http://localhost/test.php",
type:"POST",
async:true,
data:{
"search" : searchDat,
},
success: function(value){
alert( JSON.parse(value));
$.each(value, function(index, value1){
console.log(value1);
});
}
});
});
});
}
</script>
You are declaring $(document).ready(function() inside MyResult function . In first case it will execute the MyFunction & in second case it will execute the code inside the ready function.
Actually there is no need to the action here. Following change will work
HTML
<form id='target'>
<input type="submit" value="Search" id="button1" />
</form>
JS
$(document).ready(function() {
$("#target").submit(function() {
event.preventDefault()
var searchData = $("#search").val();
alert(searchData);
$.ajax({
url: "http://localhost/test.php",
type: "POST",
async: true,
data: {
"search": searchData,
},
success: function(value) {
alert(JSON.parse(value));
$.each(value, function(index, value1) {
console.log(value1);
});
}
});
});
})
The problem is that your current code doesn't set-up the click-handler for button until the form is submitted. That first click triggers the action attribute on the <form>, which sets up the handler. The second click then calls the button handler.
Instead of your current code, you probably want HTML like this:
<form>
<input type="submit" value="Search" id ="button1"/>
</form>
Use $(document).ready(...) without the wrapper function MyResults(), and be sure to cancel the click event to stop traditional form submission:
<script>
$(document).ready(function(){
$("#button1").click(function(event){
event.preventDefault();
event.stopPropagation();
var searchData = $("#search").val();
alert(searchData);
$.ajax({
url: "http://localhost/test.php",
type:"POST",
async:true,
data:{
"search" : searchDat,
},
success: function(value){
alert( JSON.parse(value));
$.each(value, function(index, value1){
console.log(value1);
});
}
});
});
});
</script>
Here fired one event at two times.
First fired when form submit.
action="javascript:MyResults()"
Second fired after form submit which you have defined in the function part.
$("#button1").click(function(){});

Javascript not running in order

i have problem with my javascript not running in order on submit event.
i have a form more or less like this:
<form id="myForm">
<div>
<button type="submit" name="submit">Submit</button>
</div>
<div>
<div id="loading" style="display:none;"><img src="images/loading.gif"/></div>
<div id="hasil" style="display:none;"></div>
</div>
</form>
and a javascript function with ajax :
$('#myForm').submit(function() {
$('#hasil').fadeOut('fast', function() {
alert('a');
$('#loading').fadeIn('fast');
});
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
if(data=='0'){
$('#hasil').html('Code Already Exist');
$('#loading').fadeOut('fast', function() {
alert('d');
$('#hasil').fadeIn();
});
}
}
});
return false;
});
it supposed to show #loading, hide #loading, then show #hasil. at first submit, it will run with no problem. but when i submit it at second time, the script not running at orderly from top to bottom, instead from point 'd', then 'a' (alert()).
i wonder why the script run like this? did i made a mistake somewhere?
Reference to jQuery API document: http://api.jquery.com/fadeout/
the callback is fired once the animation is complete.
So, if the ajax request was completed faster than the fade out animation, point 'd' will happen first and then point 'a'.
You can place the ajax request inside the fade out callback function to solve the problem.
$('#myForm').submit(function(e) {
$('#hasil').fadeOut('fast', function() {
alert('a');
$('#loading').fadeIn('fast');
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
success: function(data) {
if(data=='0'){
$('#hasil').html('Code Already Exist');
$('#loading').fadeOut('fast', function() {
alert('d');
$('#hasil').fadeIn();
});
}
}
});
});
return false;
});

changing the class of clicked button on ajax function success

i have a several html buttons (not within a form).
When clicked they call a JavaScript function that after conformation, runs an ajax call.
This part all works OK, but i would then like to change the class of whichever button was clicked on success of the ajax call.
i have tried various methods seen on stackOverflow, but none of them seem to work...
can i please ask what am i doing wrong?
here is the simplified HTML (buttons)
<button class="btn btn-primary" onclick="primaryImage(4107,19372,'/abbie1.jpg'); return false;">
set as profile image
</button>
<button class="btn btn-primary" onclick="primaryImage(4107,19373,'/abbie2.jpg'); return false;">
set as profile image
</button>
<button class="btn btn-success" onclick="primaryImage(4107,19374,'/abbie3.jpg'); return false;" disabled="disabled">
profile image
</button>
Please note: the last button is already the active/success button, and i would also like to remove the class on success too (as only one should be active), but that is maybe my next stage....
here is the javaScript, (i have left in some of the methods i have tried, but commented them out)
function primaryImage(eid,pid)
{
if (confirm("Are you sure you wish to use this as your profile image?"))
{
$.ajax({
type: "POST",
async: false,
cache: false,
dataType: "json",
url: "ajax_photo.php",
data: "action=primary&eid="+eid+"&pid="+pid,
//context: this,
success: function(data){
if(data.result=='success')
{
alert('The image is now set as the profile image');
//$('button').click(function(){
// $(this).addClass('btn-success');
//});
//$('button').on(data.result=='success', function(e) {
// $(this).toggleClass("btn btn-success"); //you can list several class names
// e.preventDefault();
//});
//$(this).removeClass('btn-primary').addClass('btn-success');
}
else
{
alert('An error occurred when trying to set the image: ' + data.result);
}
}
});
}
}
I would be very grateful for any advice of what i am doing wrong
(as you can see, i am not too good with JS (yet))
Thanks!
Ford
As noted in your commented out code, you are binding the click event after click event has already been fired.
I would suggest you to pass a reference of the button that was clicked in the primaryImage() function itself as such:
<!-- In your HTML -->
<button class="btn btn-success" onclick="primaryImage(this, 4107,19374,'/abbie3.jpg'); return false;" disabled="disabled">
profile image
</button>
function primaryImage(button, eid,pid){
/** ... */
Then using that referenced button, you can add or remove CSS classes to the element, as well as the siblings of the element (using jQuery's siblings() method).
//your ajax call
success: function(data){
if(data.result=='success') //make sure this really is success
{
alert('The image is now set as the profile image');
$(button).removeClass('btn-primary').addClass('btn-success');
$(button).siblings('button').removeClass('btn-success').addClass('btn-primary');
}
}
As you don't use the jQuery .click() event, I think you need to pass the button in your function args.
So your button will look like
<button class="btn btn-primary" onclick="primaryImage(this, 4107,19373,'/abbie2.jpg'); return false;">
set as profile image
</button>
Then your function will be like
function primaryImage(el, eid,pid)
{
if (confirm("Are you sure you wish to use this as your profile image?"))
{
$.ajax({
type: "POST",
async: false,
cache: false,
dataType: "json",
url: "http://anzvirtuel.org",
data: "action=primary&eid="+eid+"&pid="+pid,
//context: this,
success: function(data){
if(data.result=='success')
{
$(el).addClass('btn-success');
alert('The image is now set as the profile image');
// keep doing whatever you want...
}
else
{
alert('An error occurred when trying to set the image: ' + data.result);
}
}
});
}
}
As I have not fully understood your commented JS I'll let you put the code you want, just remember that your button will be accessible in jQuery with $(el).
Hope it may helps you
You should pass the clicked element to the primaryImage() function, and use it on success to do whatever you like.
<button class="btn btn-primary" onclick="primaryImage(this, 4107,19372,'/abbie1.jpg'); return false;">set as profile image</button>
And in your JS
function primaryImage(element, eid,pid)
{
[...]
success: function(data){
if(data.result=='success')
{
$(element).addClass('btn-success');
}
else
{
alert('An error occurred when trying to set the image: ' + data.result);
}
}
[...]
}
You could use data-* attributes instead of onclick (MDN Documentation) and then access those throught jQuery, so your code is more clean and HTML / JS are separated.
Try this code, I've created three data attributes (data-eid, data-pid and data-image) for your params and also replaced your JS to make the whole stuff work with those data attributes. Those attributes can be accessed with following jQuery code - var eid = $(this).attr('data-eid'); as an example
This line of code removes the btn-primary class from the clicked button, adds a btn-success class to it and disables it, so it can't be toggled again.
pushedBtn.removeClass("btn-primary").addClass("btn-success").prop("disabled", true);
HTML
<button class="btn btn-primary" data-eid="4107" data-pid="19372" data-image="/abbie1.jpg">
profile image
</button>
<button class="btn btn-primary" data-eid="4107" data-pid="19373" data-image="/abbie2.jpg">
profile image
</button>
<button class="btn btn-primary" data-eid="4107" data-pid="19374" data-image="/abbie3.jpg">
profile image
</button>
JS
$(".btn").click(function (e) {
if (confirm("Are you sure you wish to use this as your profile image?")) {
var eid = $(this).attr('data-eid'); //like 4107
var pid = $(this).attr('data-pid'); //like 19372
var image = $(this).attr('data-image'); //like /abbie1.jpg
var pushedBtn = $(this);
$.ajax({
type: "POST",
async: false,
cache: false,
dataType: "json",
url: "ajax_photo.php",
data: "action=primary&eid=" + eid + "&pid=" + pid,
//context: this,
success: function (data) {
if (data.result == 'success') {
alert('The image is now set as the profile image');
pushedBtn.removeClass("btn-primary").addClass("btn-success").prop("disabled", true);
} else {
alert('An error occurred when trying to set the image: ' + data.result);
}
}
});
}
});

One submit button for multiple forms. Master save strategy,

Picture below shows simplification of the html page layout I am working with. It has 3 forms, every form has it's own submit button and can be submitted individually. At the top of the page "Master Save" is located. This button should save all 3 forms.
Every form have submit() function overloaded and they look like this:
form1.submit(function () {
Form1SubmitOverloaded(this);
return false;
});
Form1SubmitOverloaded = function (form) {
$.post(form.action, $(form).serialize(), function (data) {
//DOM manipulation, etc/
}).fail(function () {
//error parsing etc.
});
return false;
};
After pressing "Master Save" I want to submit forms in order 1 > 2 > 3. But I want Form 2 to wait until form 1 has ended.
Form1 submitted >> Form2 submitted >> Form3 submitted.
$('#masterSave').click(function () {
$('#form1').submit();
$('#form2').submit(); // wait until form1 ended
$('#form3').submit(); // waint until form2 ended
return false;
});
Please provide method to order submits in 'click' function as presented.
Thanks.
.post() method doesn't look to have a synch property. But .ajax() has.
I suggest you use the .ajax() method instead of the .post() shortcut method. That way you could force ajax to be synchronious
$.ajax({
[...]
async : false
}
you can use something like this
Form1SubmitOverloaded();
$.ajax({
type: "POST",
url: test1.php,
data: $( "#form1" ).serialize(),
success: function(){
Form2SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
Form3SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
alert("All submit successfully");
}
});
}
});
}
});

overwrite javascript standard submit function behavior

In a huge webapplication I need a workaround for submitting forms.
For overriding a built-in javscript method I tried this example, but I don't even get the alert popup.
My idea for the overwritten submit function is this:
function submit(event) {
var target = event ? event.target : this;
$.ajax({
url: target.action,
data: $('form').serialize(), // &nd someone knows how I can get the serialize() of the form I just clicked?
success: function (data) {
alert('done');
},
error: function (data) {
alert('error (check console log)');
console.log(data);
}
});
//this._submit();
return false;
}
The way the submit is used everywhere is not consistent. Possiblities in the original code:
<button onclick="form.submit">
onclick="calltoFunction();" // where inside the function the submit is called
<button type="submit" // the normal way
I guess my idea is possible, because I overwritten js-functions before. But how should I do it with the submit part.
Any suggestions, ideas, fixes are welcome!
Bind the event to your button like so:
$('#my_button').click(
function(event){
event.preventDefault(); //This will prevent the buttons default submit behavior
...//The rest is up to you!
}
);
function submit(form) {
$.ajax({
url: $(form).attr('action'),
data: $(form).serialize(),
success: function (data) {
alert('done');
},
error: function (data) {
alert('error (check console log)');
console.log(data);
}
});
return false;
}
<form id="my-form" action="/my-action-file.php" method="post" onsubmit="return submit('#my-form');">
<!-- my form content -->
</form>
I suspect you will find this useful:
$('#yourForm').beforeSubmit(function()
{
return doWhateverYouLikeAndReturnTrueToContinueFormSubmition($(this));
});
This will execute doWhateverYouLikeAndReturnTrueToContinueFormSubmition before any other form submission code
You can try this:
function submit(event) {
var target = event ? event.target : this;
$.ajax({
url: target.action,
type: "POST",
data: $('form').serialize(), // &nd someone knows how I can get the serialize() of the form I just clicked?
success: function (data) {
alert('done');
},
error: function (data) {
alert('error (check console log)');
console.log(data);
}
});
//this._submit();
return false;
}

Categories

Resources