JQuery form submit with function not working - forms

I'm having an issue with the jquery function submit for a form :
$(document).ready(function () {
$('#message').keydown(function(e) {
if(e.which == 13 && !e.shiftKey) {
$('#edit_message_11').submit(function() {
alert("HELLO2");
});
return false;
}
});
});
<form id="edit_message_11" class="edit_message" method="post" action="/message/11" accept-charset="UTF-8">
<textarea id="message" class="form-control edit_message_form" name="message">
Hello
</textarea>
http://jsfiddle.net/978QC/
When I do the following for my form : $('#edit_message_11').submit(function() { ... }); it doesn't trigger the submit.
However, If I do $('#edit_message_11').submit(); it does trigger the submit.
The reason why I need to do $('#edit_message_11').submit(function() { ... }); is because I want to do an ajax submit.
Anyone has a clue?
Thanks!

I don't believe it will work the way you are trying to do it. When it's inside the submit function, the alert will never fire until it gets a response back from POST. Which means you need a response from your form processing script.
Your AJAX call doesn't need to be inside the submit function, it just needs to be inside the event.
$(document).ready(function () {
$('#selfie_message').keydown(function(e) {
if(e.which == 13 && !e.shiftKey) {
$('#edit_selfie_11').submit();
$.ajax({
type: "POST",
url: "/selfies/11",
data: $("#edit_selfie_11").serialize()
});
}
});
});
If you need something to happen on success, you would do it like this.
$(document).ready(function () {
$('#selfie_message').keydown(function(e) {
if(e.which == 13 && !e.shiftKey) {
$('#edit_selfie_11').submit();
$.ajax({
type: "POST",
url: "/selfies/11",
data: $("#edit_selfie_11").serialize(),
success: function(response){
//your response code here//
}
});
}
});
});

Related

Not able to get response in braintree checkout button

I am using braintree paypal checkout for the payment, payment is working fine, but not able to get response of that, here is my code for that
<script type="text/javascript">
var form = document.querySelector('#payment-form');
var client_token = "<?php echo \Braintree\ClientToken::generate(); ?>";
braintree.dropin.create({
authorization: client_token,
selector: '#bt-dropin',
paypal: {
flow: 'vault',
onSuccess: function (nonce, email) {
alert('sdsdsd123');
console.log(JSON.stringify(nonce));
},
},
}, function (createErr, instance) {
if (createErr) {
console.log('Error', createErr);
return;
}
form.addEventListener('submit', function (event) {
event.preventDefault();
instance.requestPaymentMethod(function (err, payload) {
if (err) {
console.log('Error', err);
return;
} else {
console.log("Payment confirmation");
console.log(payload);
}
// Add the nonce to the form and submit
document.querySelector('#nonce').value = payload.nonce;
form.submit();
});
});
},
);
var checkout = new Demo({
formID: 'payment-form'
});
But not able to get response in onsuccess function, can anyone please tell me how cani get this success response,
Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
It looks like you may be confusing the implementation of PayPal within the Braintree JSv2 Drop-In UI with the Braintree JSv3 Drop-In UI. The onSuccess option is not supported in JSv3. The full list of configuration options of the PayPal object in JSv3 is available here.
Based on the code you provided, I would suggest removing your onSuccess callback function. You should still be able to achieve your desired result by placing that code in your instance.requestPaymentMethod callback function like so:
<script type="text/javascript">
var form = document.querySelector('#payment-form');
var client_token = "<?php echo \Braintree\ClientToken::generate(); ?>";
braintree.dropin.create({
authorization: client_token,
selector: '#bt-dropin',
paypal: {
flow: 'vault'
}
}, function (createErr, instance) {
if (createErr) {
console.log('Error', createErr);
return;
}
form.addEventListener('submit', function (event) {
event.preventDefault();
instance.requestPaymentMethod(function (err, payload) {
if (err) {
console.log('Error', err);
return;
}
console.log("Payment confirmation");
console.log(payload);
alert('sdsdsd123');
console.log(payload.nonce);
// Add the nonce to the form and submit
document.querySelector('#nonce').value = payload.nonce;
form.submit();
});
});
});
</script>

Semantic UI modal and ajax loaded content

I have modified original modal.js script to support ajax content as well, and added a new Behavior called "ajax" here is my piece of code:
ajax: function(callback) {
callback = $.isFunction(callback)
? callback
: function(){}
;
var $content = $(this).find('.content');
$.get("contentData.php", function(data) {
$content.html(data);
});
And I call it like:
$('body').on('click', '.domOdal', function() {
$('.ui.modal')
.modal({
observeChanges: true
}).modal('ajax')
});
The above code works perfect and loads content correclty, but I would like to extended a bit more, so I can include additional info such as custom url, dataType, etc pretty much all the ajax options, and I would like to do that from initialization part like:
$('body').on('click', '.domOdal', function() {
$('.ui.modal')
.modal({
observeChanges: true
}).modal('ajax', {"id":5}, dataType:"json", "url": http://myurl.php" etc...)
});
A bit late but this it what's working for me:
$('body').on('click', '.domOdal', function (e) {
e.preventDefault();
$('.ui.modal')
.modal({
blurring: true,
observeChanges: true,
transition: 'scale',
onVisible: function (callback) {
callback = $.isFunction(callback) ? callback : function () { };
var $content = $(this).find('.content');
$.get("contentData.php", function (data) {
$content.html(data);
});
}
}).modal('show')
});
And in your html where the modl is called:
<div class="ui modal">
<i class="close icon"></i>
<div class="content">
</div>
</div>
How about doing it like this:
$('body').on('click', '.domOdal', function() {
$.ajax({
url: "specs.html",
type: 'POST',
dataType: 'xml',
dataType: 'html'
}).done(function(response) {
console.log(response)
$(response).modal();
});
});

How to make the form submit with normal button?

Here is the code I used.
With a click function, I made the POST action to the controller..
$('#btn1').click(function (e) {
$.post($('#frmLogin').attr('action'), $('#frmLogin').serialize(), function (data) {
});
});
#using (Html.BeginForm("Login", "Login", new { Model }, FormMethod.Post, new { id = "frmLogin" }))
{
<input type="button" id="btn1"/>
});
Call this function on clicking your normal button
function form_submit()
{
document.getElementById('formID').submit();
}
or use this jquery
$( "#btn1" ).click(function() {
$( "#frmLogin" ).submit();
});

Page need to be refresh before Facebook Login works

I am facing this issue in my application where facebook login is used.
ISSUE
Users need to press F5/refresh the page before facebook login prompt comes up. otherwise it doesn't come up and nothing happens on button click.
Here is the button tag for Facebook Login, which calls "Login()" method {angularJS is used}.
<a href="#" class="btn btn-default btn-lg" ng-click="login()"
ng-disabled="loginStatus.status == 'connected'"> <i class="fa fa-facebook fa-fw"></i> <span
class="network-name">Login Using Facebook</span></a>
AngularJS Code which gets called:
app.controller('DemoCtrl', ['$scope', 'ezfb', '$window', 'PFactory', '$location', function ($scope, ezfb, $window, PFactory, $location) {
updateLoginStatus(updateApiMe);
$scope.login = function () {
ezfb.login(function (res) {
/**
* no manual $scope.$apply, I got that handled
*/
if (res.authResponse) {
updateLoginStatus(updateApiMe);
}
}, {scope: 'email,user_likes,user_status,user_about_me,user_birthday,user_hometown,user_location,user_relationships,user_relationship_details,user_work_history'});
$location.path('/view9');
};
$scope.logout = function () {
ezfb.logout(function () {
updateLoginStatus(updateApiMe);
});
};
$scope.share = function () {
ezfb.ui(
{
method: 'feed',
name: 'angular-easyfb API demo',
picture: 'http://plnkr.co/img/plunker.png',
link: 'http://plnkr.co/edit/qclqht?p=preview',
description: 'angular-easyfb is an AngularJS module wrapping Facebook SDK.' +
' Facebook integration in AngularJS made easy!' +
' Please try it and feel free to give feedbacks.'
},
null
);
};
var autoToJSON = ['loginStatus', 'apiMe'];
angular.forEach(autoToJSON, function (varName) {
$scope.$watch(varName, function (val) {
$scope[varName + 'JSON'] = JSON.stringify(val, null, 2);
}, true);
});
function updateLoginStatus(more) {
ezfb.getLoginStatus(function (res) {
$scope.loginStatus = res;
$scope.promotion = 'promotion';
(more || angular.noop)();
});
}
function updateApiMe() {
ezfb.api('/me', function (res) {
$scope.apiMe = res;
});
}
}]);
Please help resolving it!
Thanks in Advance
Add true parameter after getLoginStatus callback function to force refreshing cache.
https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
ezfb.getLoginStatus(function (res) {
$scope.loginStatus = res;
$scope.promotion = 'promotion';
(more || angular.noop)();
}, true);

How to upload multiple files on separate Forms by Ajax upload?

I've worked on this but couldn't fully figure out.
Basically, what I need is to upload 2 or more files separately (only on demand one by one, not all files at once) using Ajax upload. Currently, I have 2 file inputs but somehow, the JavaScript code always uploads the first file input (the one inside "formContentProperty").
Here is my HTML code:
<div>
<form enctype="multipart/form-data" id="formContentProperty">
<input id="fileContentProperty" type="file" name="fileContentProperty" />
<a id="uploadbuttonContentProperty" href="javascript:void(0)">
<span>Upload 1</span>
</a>
</form>
<progress></progress>
</div>
<div>
<form enctype="multipart/form-data" id="formContentPreviewImage">
<input id="fileContentPreviewImage" type="file" name="fileContentPreviewImage"/>
<a id="uploadbuttonContentPreviewImage" href="javascript:void(0)">
<span>Upload 2</span>
</a>
</form>
<progress></progress>
</div>
Here is my JavaScript code:
$('#uploadbuttonContentProperty').click(function () {
return UpdoadFile('formContentProperty', 'divUploadContentPropertyResultMessage');
});
$('#uploadbuttonContentPreviewImage').click(function () {
return UpdoadFile('formContentPreviewImage', 'divUploadContentPreviewImageResultMessage');
});
function UpdoadFile(formElementId, divMessageElementId) {
var formData = new FormData($('form')[0]);
$.ajax({
url : '<%= base.AjaxUploadHandlerPath %>', //Server script to process data
type : 'POST',
xhr : function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){ // Check if upload property exists
myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//beforeSend: beforeSendHandler,
success : function(response) {
var obj = $.parseJSON(response);
$('#' + divMessageElementId).html(obj.ResultMessage);
},
//error : errorHandler,
data : formData,
//Options to tell jQuery not to process data or worry about content-type.
cache : false,
contentType : false,
processData : false
});
};
function progressHandlingFunction(e){
if(e.lengthComputable)
$('progressContentProperty').attr({ value: e.loaded, max: e.total });
}
I'd really appreciate any help.
To upload files using ajax file upload
<script>
function uploadFiles()
{
var files = $('#previewFile')[0].files;
var totalFiles = files.length
for(var i=0; i < totalFiles; i++)
{
var formData = new FormData();
formData.append("previewFile",files[i]);
doAjaxFileUpload("/storeTempFile.do", formData,function(data)
{
data = eval(data);
if (data.result=="success")
{
alert("File uploaded successfully");
}
else
{
alert("Error occured : "+data);
}
},
function(data)
{
alert("Error occured : "+data);
});
}
}
function doAjaxFileUpload(actionURL,params,callbackSuccessFunction,callbackFailureFunction)
{
$.ajax(
{
url: actionURL,
type: "POST",
data: params,
processData: false,
contentType: false,
error: callbackFailureFunction,
success : callbackSuccessFunction
});
}
</script>