ajaxSubmit: Duplicate Entry on the database - javascript

I have a form and a input type file inside.
<form id='imageform' method='post' enctype='multipart/form-data' action='php/exec/add-message-image-exec.php' style='clear:both'>
<div id='imageloadstatus' style='display:none'><img src='assets/loader.gif' alt='Uploading....'/></div>
<div id='imageloadbutton'>
<div class='file-field input-field'>
<div class='btn'>
<span>Upload</span>
<input type='file' name='file' id='photoimg'/>
</div>
<div class='file-path-wrapper'>
<input class='file-path validate' type='text'>
</div>
</div>
</div>
</form>
It performs whenever i attach an image in the input file, and an ajax will handle it to submit it automatically and save it to the database.
$(document).ready(function () {
$('#photoimg').on('change', function () {
var A = $('#imageloadstatus');
var B = $('#imageloadbutton');
$('#imageform').ajaxSubmit({target: '#preview',
beforeSubmit: function () {
A.show();
B.hide();
},
success: function () {
A.hide();
B.show();
},
error: function () {
A.hide();
B.show();
}}).submit();
});
});
My problem is that it submits the image twice and save it to my database/table twice. But when i remove the .submit(); inside my script, it only perform once but there's a small modal-like window and another screen appeared whenever i attach an image/submit.

Remove 'action' and put it in an ajax POST request instead.
$(document).ready(function () {
$('#photoimg').on('change', function () {
var A = $('#imageloadstatus');
var B = $('#imageloadbutton');
$.ajax({
url: 'php/exec/add-message-image-exec.php',
type: 'POST',
data: $('#imageform').serialize(),
beforeSubmit: function () {
A.show();
B.hide();
},
success: function (data) {
//do something with data
//ex: console.log()
console.log(data);
A.hide();
B.show();
},
error: function () {
A.hide();
B.show();
}
});
});
});

Related

jQuery - Hook function to html attribute

Is it possible to hook a function to an html attribute?
For example:
HTML:
<form method="post" action="ajax.php" id="login-form" data-function="doSomething">
//...
</form>
JS:
function doSomething() {
alert('hello!');
}
$(document).on('submit', 'form', function(event){
event.preventDefault();
var form = $(this);
$.ajax({
url: form.attr('action'),
type: "POST",
data: form.serialize(),
success: function(result){
form.attr('data-function'); //<-- call the function defined in data-function here
}
});
});
Thanks in advance!
you can do this if you store the function in an object
const obj = {
doSomething() {
alert('hello!');
}
}
then you can call doSomething with
obj['doSomething']()

Ajax executing different form on submit

I've created two forms and assigned different submit button IDs. But ajax is executing single form every time even if I execute different button for different ajax call. Following is the code:
Form1.
<button class='btn genz-light-red'type='submit'
style="margin-top:20px;width:50%; background:#FF1744; height:33px;color:white;" id="customButton">Enroll</button>
</div>
</form>
<script src="https://checkout.stripe.com/checkout.js"></script>
<script type="text/javascript">
var handler = StripeCheckout.configure({
key: 'pk_test_YgHVTCLIMQLW4NV6ntnJPAXs',
image: '/assets/img/icons/GenZ_Logo.png',
locale: 'auto',
token: function (token) {
$("#stripeToken").val(token.id);
$("#stripeEmail").val(token.email);
$("#monthlyForm").submit();
$.ajax({
url: '/monthlycharged',
data: $('form').serialize(),
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
}
});
$('#customButton').on('click', function (e) {
handler.open({
name:'Monthly',
description:'Monthly Package',
amount:1450
});
e.preventDefault();
});
$(window).on('popstate', function () {
handler.close();
});
</script>
Form2:
<form action='/cancelannual' method='post'><a href="/cancelannual">
<input class='btn genz-light-red'style=";width:50%; background:#FF1744; height:33px;color:white;"type="submit" value="Cancel" /></a></form>
<!-- Custom Button -->
<form id="yearlyForm" action="/yearlycharged" method="post" >
<div class="form-group">
<input type="hidden" id="stripeToken" name="stripeToken" />
<input type="hidden" id="stripeEmail" name="stripeEmail" />
<button class='btn genz-light-red'type='submit'
style="margin-top:20px;width:50%; background:#FF1744; height:33px;color:white;" id="customButton1">Enroll</button>
</div>
</form>
<script src="https://checkout.stripe.com/checkout.js"></script>
<script type="text/javascript">
var handler = StripeCheckout.configure({
key: 'pk_test_YgHVTCLIMQLW4NV6ntnJPAXs',
image: '/assets/img/icons/GenZ_Logo.png',
locale: 'auto',
token: function (token) {
$("#stripeToken").val(token.id);
$("#stripeEmail").val(token.email);
$("#yearlyForm").submit();
$.ajax({
url: '/yearlycharged',
data: $('form').serialize(),
type: 'POST',
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});
}
});
$('#customButton1').on('click', function (e) {
handler.open({
name:'Yearly',
description:'Yearly Package',
amount:9500
});
e.preventDefault();
});
// Close Checkout on page navigation
$(window).on('popstate', function () {
handler.close();
});
</script>
If I click on "customButton" it processes yearly subscription if I click on "customButton1" still it processes yearly subscription instead of monthly. Surprisingly when form popups it has the monthly values in it. But after processing database shows Yearly package processed. In my python/flask code without ajax I can process both packages seperately so the problem is not in my views it lies somewhere in Ajax. Please advise
You have two var handler declarations in the global scope - the second hides the first. Name them differently or wrap both code fragments in separate $(document).ready(function() {...});

Change text of Input button after clicking on it

I have the following input HTML tag
<input type="submit" id="submitForm" value="Submit" class="btn btn-primary start" autocomplete="off" onclick="submitForm();" />
When I click on the submit button, it goes to the related JavaScript file and executes the function submitForm();
I would like to change the text of the submit form to "Please wait..." until the function is completed.
Is there a way this can be done?
This is how the submitForm() function looks like:
function submitForm() {
$("#submitForm").val("Please wait...");
if (formValidation() === true) {
submitFormInfo().done(function () {
$("#submitForm").val("Submit");
});
}
}
function submitFormInfo() {
return $.ajax({
cache: false,
url: "URLHERE"
error: function (xhr) {
},
success: function (result) {
},
async: false,
processData: false
});
}
Are you having asynchronus operation in submitform() ?
if yes then you can use following line
$("#submitForm").val("Please Wait");
You can use jquery please see:-
https://jsfiddle.net/swawrm1g/3/
I have removed:-
onclick="submitForm();"
and added:-
$('#submitForm').click(function(){
$(this).val('Please Wait...');
submitForm()
});
function submitForm() {
alert('Form submitted');
};
Simple javascript is enough to do this..
<script>
function submitForm(){
document.getElementById('submitForm').value="Please wait..";
}
</script>
<input type="submit" id="submitForm" onclick="submitForm()" value="Submit">
Use the beforeSend option on your ajax call, so in your submitForm() function, you can do something like this:
function submitForm() {
var submitForm = $("#submitForm");
if (formValidation() === true) {
$.ajax({
cache: false,
url: "URLHERE",
async: false,
type: 'post',
data: { somedata: 'here' },
beforeSend: function (){
submitForm.val("Please wait...").attr("disabled", "disabled");
},
success: function (data){
// do something
},
error: function (){
// do something
},
complete: function () {
// regardless of the response status (success/error)
// the codes below will be executed.
submitForm.val("Submit").removeAttr("disabled");
}
});
}
}

How to Get Button to Trigger Ajax Request in Bootstrap

I have a modal form with Bootstrap that is associated with a specific item that is customized by the user before being added to the cart. I'm trying to trigger an Ajax request when the "Add to Cart" button is clicked. But the button doesn't seem to be triggering anything. I'm using a modified version of Bootstrap's sample code: http://getbootstrap.com/javascript/#modals-related-target
Any suggestions on how to get the button to trigger an ajax request properly?
UPDATE: I've added the PHP code below in case that might be the issue.
HTML:
<div class="modal-body">
<form name="formBasic" id="formBasic">
<input type="hidden" name="function" value="basic-form">
<div class="form-group">
<label for="message-text" class="control-label">Enter customized information</label>
<textarea class="form-control" id="customized-information"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="basic-submit">Add to Cart</button>
</div>
Javascript:
$(document).ready(function () {
var formBasic = function () {
var formData = $("#formBasic").serialize();
$(form).ajaxSubmit({
type: 'post',
data: formData,
dataType: 'json',
url: 'http://localhost/forms.php'
error: function () {
console.log(output);
alert("There was an error processing this page.");
return false;
},
complete: function (output) {
$('#formBasicResults').html(output.responseText);
}
});
return false;
};
$("#basic-submit").on("click", function (e) {
e.preventDefault();
formBasic();
});
});
PHP:
//formBasic Processing
function formBasic(){
$output = 'Output from Form Basic:
';
foreach ($_POST as $key => $value) {
$output .= $key . ': ' . $value . '
';
}
echo $output;
}
//FormAdvanced Processing
//. . .
if(in_array($_POST['function'], array('formBasic','formAdvanced'))){
$_POST['function']();
}else{
echo 'There was an error processing the form';
}
Your code should be:
$(document).ready(function () {
var formBasic = function () {
var formData = $("#formBasic").serialize();
$.ajax({
type: 'post',
data: formData,
dataType: 'json',
url: 'http://localhost/forms.php',
error: function () {
alert("There was an error processing this page.");
return false;
},
complete: function (output) {
$('#formBasicResults').html(output.responseText);
}
});
return false;
};
$("#basic-submit").on("click", function (e) {
e.preventDefault();
formBasic();
});
});
Issues:
1- Missing comma on line:
url: 'http://localhost/forms.php'
2- form not defined:
$(form).ajaxSubmit({
Working fiddle: http://jsfiddle.net/p9v2eg4u/2/
$('#basic-submit').click(function() {
var formData = $("#formBasic").serialize();
console.log(formData);
added a console.log(); of the value of form data
$('#formBasic').ajaxSubmit({
type: 'POST',
data: formData,
dataType: 'JSON',
url: 'http://localhost/forms.php',
added missing comma after URL
error: function () {
alert("There was an error processing this page.");
return false;
},
complete: function (output) {
console.log(output);
another console.log of output object
$('#formBasicResults').html(output.responseText);
},
success: function(output) {}
consider using success instead of complete, complete will execute if success or error.
});
return false;
});

Submit ajax request one by one with each()

i tried to submit multiple form using ajax, but how to send one by one, i mean send the first ajax after done/success then send second ajax, below is my script:
<form>
<input type="text" name="name" value="john doe" size="60">
<input type="text" name="age" value="23" size="2">
</form>
<form>
<input type="text" name="name" value="Alex" size="60">
<input type="text" name="age" value="24" size="2">
</form>
<button>Submit</button>
<script>
function post_form_data(data) {
$.ajax({
type: 'POST',
url: 'https://members.lelong.com.my/Auc/Member/Feed/feed.asp',
data: data,
success: function () {
console.log('Success');
},
error: function () {
console.log('error');
}
});
}
$('button').on('click', function () {
$('form').each(function () {
post_form_data($(this).serialize());
});
});
</script>
You can try this :
function post_form_data(data,cache,i) {
$.ajax({
type: 'POST',
url: 'https://members.lelong.com.my/Auc/Member/Feed/feed.asp',
data: data,
success: function () {
console.log('Success');
i++;
post_form_data(cache.eq(i).serialize(),_cached,i);
},
error: function () {
console.log('error');
}
});
}
$('button').on('click', function () {
var _cached=$('form');
post_form_data(_cached.eq(0).serialize(),_cached,0);
});
You can add
async : false
to make it sequential.
$.ajax({
type: 'POST',
url: 'https://members.lelong.com.my/Auc/Member/Feed/feed.asp',
data: data,
async :false ,
success: function () {
console.log('Success');
},
error: function () {
console.log('error');
}
});
Note:- async : false can logically turn down behavior of ajaxified request. We discourage the use of it until its needed desperately.
You could put requests data in array, returning promise interface from function and use done/then or always:
function post_form_data(data) {
return $.ajax({
type: 'POST',
url: '/echo/html',
data: data,
success: function () {
console.log('Success');
},
error: function () {
console.log('error');
}
});
}
$('button').on('click', function () {
var requests = $('form').map(function () {
return $(this).serialize();
}).get();
var i = 0;
if (requests.length) {
makeRequest(requests, i);
}
});
function makeRequest(requests, i) {
var iPromise = post_form_data(requests[i]);
if (i < requests.length - 1) {
iPromise.done(makeRequest(requests, ++i))
}
}

Categories