I have made what is essentially a lightbox whereby if a change requires the user to confirm their password, this lightbox pops up and the user enters there password etc.
I am triggering the function like this:
if(verifyPassword())
{
//apply change
}
The verify function is:
function verifyPassword() {
$('#confirmpasswordoverlay').fadeIn(300);
$('#submit').click(function() {
$.post('', { password: $('input[name=password]').val() },
function(check) {
if(check.error)
{
if(check.password)
{
//show password error
return false;
}
else
{
//show error
return false;
}
}
else
{
return true;
}
}, 'json');
});
}
Basically I am needing the function to wait until #submit is clicked to return either true or false.
Thanks in advance
Since jQuery 1.5.0, you can do apply some magic with Deferred objects:
$.when( verifyPassword() ).done(function() {
// do something
});
You would need to re-write verifyPassword() a little:
function verifyPassword() {
var Notify = $.Deferred();
$('#confirmpasswordoverlay').fadeIn(300);
$('#submit').click(function() {
$.post('', { password: $('input[name=password]').val() },
function(check) {
if(check.error) {
if(check.password) {
//show password error
Notify.resolve();
}
else {
//show error
Notify.reject();
}
}
else {
return true;
}
}, 'json');
});
return Notify.promise();
}
This might not be the most elegant way of achieving your goal here, I'm just saying you could do it in a way like this :-)
Don't stall, instead provide a callback:
function verifyPassword(f) {
/**
* Do all your logic here, then callback to the passed function
*/
f(result);
}
verifyPassword(function (correct) {
if (correct) {
/* Continue */
}
else { /* Other */ }
});
I think you want to convert your $.post() call into the more generic $.ajax() jQuery call, and pass in async: false. Something like:
$.ajax('', { async:false, data: {password:...}, success: function() {
// ... success callback ...
}});
Related
I had integrated the Razorpay payment gateway in my magento site. It's working absolutely fine in web and mobile browser. But when I try to make the payment using in-app browsers (from Instagram, Facebook) I am facing the blank page issue. So I found the solution that I need to pass the callback URL along with other input parameter to payment gateway. Here I got stuck, what should be the callback URL here? Can anyone help me to resolve this!
Here is my code:
/app/code/Razorpay/Magento/view/frontend/web/js/view/payment/method-renderer/razorpay-method.js
define(
[
'Magento_Checkout/js/view/payment/default',
'Magento_Checkout/js/model/quote',
'jquery',
'ko',
'Magento_Checkout/js/model/payment/additional-validators',
'Magento_Checkout/js/action/set-payment-information',
'mage/url',
'Magento_Customer/js/model/customer',
'Magento_Checkout/js/action/place-order',
'Magento_Checkout/js/model/full-screen-loader',
'Magento_Ui/js/model/messageList'
],
function (Component, quote, $, ko, additionalValidators, setPaymentInformationAction, url, customer, placeOrderAction, fullScreenLoader, messageList) {
'use strict';
return Component.extend({
defaults: {
template: 'Razorpay_Magento/payment/razorpay-form',
razorpayDataFrameLoaded: false,
rzp_response: {}
},
getMerchantName: function() {
return window.checkoutConfig.payment.razorpay.merchant_name;
},
getKeyId: function() {
return window.checkoutConfig.payment.razorpay.key_id;
},
context: function() {
return this;
},
isShowLegend: function() {
return true;
},
getCode: function() {
return 'razorpay';
},
isActive: function() {
return true;
},
isAvailable: function() {
return this.razorpayDataFrameLoaded;
},
handleError: function (error) {
if (_.isObject(error)) {
this.messageContainer.addErrorMessage(error);
} else {
this.messageContainer.addErrorMessage({
message: error
});
}
},
initObservable: function() {
var self = this._super(); //Resolves UI Error on Checkout
if(!self.razorpayDataFrameLoaded) {
$.getScript("https://checkout.razorpay.com/v1/checkout.js", function() {
self.razorpayDataFrameLoaded = true;
});
}
return self;
},
/**
* #override
*/
/** Process Payment */
preparePayment: function (context, event) {
if(!additionalValidators.validate()) { //Resolve checkout aggreement accept error
return false;
}
var self = this,
billing_address,
rzp_order_id;
fullScreenLoader.startLoader();
this.messageContainer.clear();
this.amount = quote.totals()['base_grand_total'] * 100;
billing_address = quote.billingAddress();
this.user = {
name: billing_address.firstname + ' ' + billing_address.lastname,
contact: billing_address.telephone,
};
if (!customer.isLoggedIn()) {
this.user.email = quote.guestEmail;
}
else
{
this.user.email = customer.customerData.email;
}
this.isPaymentProcessing = $.Deferred();
$.when(this.isPaymentProcessing).done(
function () {
self.placeOrder();
}
).fail(
function (result) {
self.handleError(result);
}
);
self.getRzpOrderId();
return;
},
getRzpOrderId: function () {
var self = this;
$.ajax({
type: 'POST',
url: url.build('razorpay/payment/order'),
/**
* Success callback
* #param {Object} response
*/
success: function (response) {
fullScreenLoader.stopLoader();
if (response.success) {
self.renderIframe(response);
} else {
self.isPaymentProcessing.reject(response.message);
}
},
/**
* Error callback
* #param {*} response
*/
error: function (response) {
fullScreenLoader.stopLoader();
self.isPaymentProcessing.reject(response.message);
}
});
},
renderIframe: function(data) {
var self = this;
this.merchant_order_id = data.order_id;
var options = {
key: self.getKeyId(),
name: self.getMerchantName(),
amount: data.amount,
handler: function (data) {
self.rzp_response = data;
self.placeOrder(data);
},
order_id: data.rzp_order,
modal: {
ondismiss: function() {
self.isPaymentProcessing.reject("Payment Closed");
}
},
notes: {
merchant_order_id: '',
merchant_quote_id: data.order_id
},
prefill: {
name: this.user.name,
contact: this.user.contact,
email: this.user.email
},
callback_url: url.build('rest/default/V1/carts/mine/payment-information', {}),
_: {
integration: 'magento',
integration_version: data.module_version,
integration_parent_version: data.maze_version,
}
};
if (data.quote_currency !== 'INR')
{
options.display_currency = data.quote_currency;
options.display_amount = data.quote_amount;
}
this.rzp = new Razorpay(options);
this.rzp.open();
},
getData: function() {
return {
"method": this.item.method,
"po_number": null,
"additional_data": {
rzp_payment_id: this.rzp_response.razorpay_payment_id,
order_id: this.merchant_order_id,
rzp_signature: this.rzp_response.razorpay_signature
}
};
}
});
}
);
In the above code renderIframe function will pass the parameter to payment gateway, here I need to pass the callback URL. I tried to set it as rest/default/V1/carts/mine/payment-information but got 401 Unauthorised error. Please help me resolve this issue.
I have done the same thing with amazon payment.
As i remember you should act on this part of codes :
function () {
self.placeOrder();
}
And how i changed
function () {
$.when(self.placeOrder()).done(
function () {
///redirect;
}
}
But when i tried on the browser, i've still got some wrong cases then i decided to make a workaround by putting an event with jquery :
$( document ).ajaxStop(function() {
//redirect
});
This works right because after all ajaxs are finished we get the order is placed. That is the time to redirect.
Hope this helps.
I have a login method in my controller where I check if there is such user in database or not. I call this method when press Submit button. I show login from view at the same time.
In my case, it doesn't show message if there is such user. I think because in my controller I load view.
How could I show this message if there is such user using Ajax and if I return view as I do in my case?
I'm using Kohana. Thanks!
My code is:
$(document).ready(function(){
$('#submit').on('click', function() {
if(username.length === 0 || password.length === 0) {
//...check if validation fails
}
else {
$.ajax({
url: "/admin/signin" ,
type: "POST",
data: {
"username":username,
"password":password
},
success: function(data) {
if(data !== 'error') {
window.location = "/admin/index";
}
else
{
alert('no such user');
}
}
});
}
});
});
public function action_signin()
{
if ($_POST) {
$is_admin = Model_Admin::signin($_POST);
print 'success';
} else {
print 'error';
}
}
$this->template->content = View::factory('admin/login_form');
}
If you want not load 'default' template try using $this->auto_render = FALSE;
also kohana controller has method is_ajax $this->request->is_ajax()
You controller code will be like this.
public function action_signin()
{
if($this->request->is_ajax()){
$this->auto_render = FALSE;
}
if ($_POST) {
$is_admin = Model_Admin::signin($_POST);
if($is_admin){
print 'success';
} else {
print 'error';
}
}else{
$this->template->content = View::factory('admin/login_form');
}
}
I am trying to get foreach data I am using jquery to submit the page without a refresh being required for some reason jQuery is not retrieving the foreach data, It needs to loop through each admin input field to see each data seperatly.
If it's not possible I won't use JQuery for this but thought I ask
PHP:
if(isset($_POST['admin_add']) AND is_array($_POST['admin_add'])) {
foreach($_POST['admin_add'] as $admin_add) {
if(strlen($admin_add) > 0) {
// $sql=mysql_query("insert into hobbies(hobby)values('$hobby')");
}
}
}
die('<h3>'.$admin_add.'<h3/>');
jQuery:
$(document).ready(function () {
var clan_url_string = window.location.search.substring(1);
// Make a function that returns the data, then call it whenever you
// need the current values
function getData() {
return {
clan_title_edit: $('#clan_title_edit').val(),
clan_des: $('#clan_des').val(),
admin_add: $('#admin_add').val(),
//remember_me: ($('#remember_me').is(':checked')) ? 1 : 0
}
}
$(window).load(function(){
$('#background_cycler').fadeIn(1500);//fade the background back in once all the images are loaded
setInterval('cycleImages()', 4000); // run every 4s
});
function loading(e) {
$('#loading_status').show();
}
function hide_loading(e) {
$('#loading_status').hide();
}
function success_message(e) {
$('#success_login').html("We're Just Signing You In");
}
function clearfields() {
$('#login-username').val(''); //Clear the user login id field
$('#login_password').val(''); //Clear the user login password field
}
function check(e) {
e.preventDefault();
$.ajax({
url: 'ajax/save_settings.php?'+clan_url_string,
type: 'post',
error: function () {
//If your response from the server is a statuscode error. do this!!!'
hide_loading(e);
$('#status_message').html('<b>Something Has Gone Wrong</b><br> Please Try Again Later');
},
beforeSend: function () {
loading(e);
},
data: {
clan_title_edit: $('#clan_title_edit').val(),
clan_des: $('#clan_des').val(),
admin_add: $('#admin_add').val(),
remember_me: ($('#remember_me').is(':checked'))
}, // get current values
success: function (data) {
//if your response is a plain text. (e.g incorrect username or password)
hide_loading(e);
$('#status_message').hide();
$('#status_message').fadeIn(1000).html(data);
}
});
}
// Don't repeat so much; use the same function for both handlers
$('#login_content').keyup(function (e) {
if (e.keyCode == 13) {
var username = $('#login-username').val();
check(e);
}
});
$('#submit_clan_settings').click(function (e) {
if (e.keyCode != 13) {
check(e);
}
});
There's the php and jquery
Thanks
Yes its SQL injection prone, havent fix this yet and I should be using mysqli or $db->);
I want to return either TRUE or FALSE when the variable 'f' i FALSE. But the return never reaches the browser and the form does its default action.
How can i get my ELSE to return a value?
I have tried to hard code a return value instead of writing 'return myFunction();' this works but it doesn't help me as i need the return from 'myFunction()'.
Don't think to much about what the code is supposed to do, it doesn't make sense, its just for demonstration.
$('#theForm').submit(function()
{
var f = $('#theInput').val(); // input value
if(f == TRUE)
{
alert('Lorem ipsum');
return false;
}
else // If f is FALSE
{
$.post('/php/check.php',{check: f, function(data){myFunction(data);});
function myFunction(data)
{
if(data == 'false')
{
// Do something
return false;
}
else
{
// Do something
return true;
}
}
return myFunction();
}
});
I have tried this, but it is still not returning a value to the form from 'return myFunction()'
$('#theForm').submit(function()
{
var f = $('#theInput').val(); // input value
if(f == true)
{
alert('Lorem ipsum');
return false; // Stop default form action
}
else // If f is FALSE
{
var request = $.ajax({
async: false,
url: "/php/checkArea.php",
type: "POST",
data: {data: f},
dataType: "text"
});
request.done(function(data) {
myFunction(data);
});
function myFunction(data)
{
if(data == 'false')
{
// Do something
return false; // Stop default form action
}
else
{
// Do something
return true; // YES PLEASE, do the default form action
}
}
return myFunction();
}
});
I finally figured out a solution, with help from you, regarding the async part.
$('#theForm').submit(function()
{
var f = $('#theInput').val(); // input value
if(f == true)
{
alert('Lorem ipsum');
return false; // Stop default form action
}
else // If f is FALSE
{
var request = $.ajax({
async: false,
url: "/php/checkArea.php",
type: "POST",
data: {data: f},
dataType: "text"
});
request.done(function(data) {
globalData = data; // Global variable
});
function myFunction(globalData)
{
if(globalData == 'false')
{
// Do something
return false; // Stop default form action
}
else
{
// Do something
return true; // YES PLEASE, do the default form action
}
}
return myFunction(globalData); // Call the function with the global variable
}
});
This works perfectly :-)
This part should do what you want:
if(f == TRUE)
{
alert('Lorem ipsum');
return false;
}
This, however, should not:
$.post('/php/check.php',{check: f, function(data){myFunction(data);});
function myFunction(data)
{
if(data == 'false')
{
// Do something
return false;
}
else
{
// Do something
return true;
}
}
return myFunction();
The $.post will always return immediately. myFunction will be called when the Ajax call is finished, but by then you have already returned from the .submit block!
You may check out the jQuery.ajax, which have a setting to make it synchronous (set async to false). This may lock the browser from doing anything else while waiting for the Ajax call, but it's the only way to make a synchronous call.
Create a DIV that will hold your false or true value from the $.ajax
<div id="result"></div>
Now structure your javascript
$('#theForm').submit( function() {
var f = $('#theInput').val(); // input value
if(f == TRUE) {
alert('Lorem ipsum');
return false;
} else { // If f is FALSE
var rVal = $('div#result');
$.ajax({
type : 'POST',
data : f,
url : '/php/check.php',
context: rVal,
async : false,
success : function (msg) {
(msg == 'false') ? $(this).html('FALSE') : $(this).html(msg);
}
});
function myFunction(data) {
if(data == 'FALSE'){
// Do something
return false;
} else {
// Do something
return true;
}
}
return myFunction( rVal.html() );
}
Case-sensitivity may be an issue. Javascript uses true and false, not TRUE and FALSE.
In your else clause, you have a callback for your POST which handles the data returned. However, the callback myFunction will be run after the code has reached return myFunction() which — as it doesn't have an argument — will cause the anonymous function to return true.
You need to make your asynchronous call synchronous, but even then, where is myFunction returning its result to?
You might try forcing myFunction to return its result to the right context like the following (I prefer to declare the function before it's used), but you may still run into synchronicity issues. It appears from the docs that $.post cannot be forced to be synchronous.
else // If f is FALSE
{
function myFunction(data)
{
if(data == 'false')
{
// Do something
return false;
}
else
{
// Do something
return true;
}
}
return ($.post('/php/check.php',{check: f}, function(data){myFunction(data);}));
}
Well guys, with the following code:
$(document).ready(function() {
$(".list-book-description").css("display", "none");
$("#user-panel-login").css("display", "none");
$('#login-form').submit(function(e) {
e.preventDefault();
var formUsername=$("#login-form #username").val();
var formPassword=$("#login-form #password").val();
if((formUsername.length<6))
{
$("#ajax-output").html("<div class='error'>Attenzione username troppo breve!</div>");
}
else if((formPassword.length<6))
{
$("#ajax-output").html("<div class='error'>Attenzione password troppo breve!</div>");
}
else
{
$.post(
'index.php?module=login',
{
"username": formUsername,
"password": formPassword,
},
function(data){
$("#ajax-output").html(data);
}
);
}
});
});
i tried to pass to ?index.php&module=login&function=1 username and password got by #login-form fields #username & #password to login() php function that uses setLogin(); function if data is into database to set a login session.
function Login()
{
if(!checkLogin())
{
$function=#stringEscape($_GET['function']);
if($function==1)
{
$username=stringEscape($_POST['username']);
$password=sha1(stringCrypt($_POST['password'], 'sha1').stringCrypt(DB_CRYPT, 'sha1'));
if(setLogin($username, $password))
{
echo "<div class='ok'>Login effettuato con successo, tra pochi secondi verrai riportato alla homepage!</div>";
}
}
}
else notfound();
}
function setLogin($username, $password, $time="")
{
if(!checkLogin())
{
if((isset($username)) && (isset($password)))
{
$query=mysql_query("SELECT * FROM ".DB_PREF."users WHERE user_username='".$username."' AND user_password='".$password."'");
if(mysql_num_rows($query))
{
$fetch=mysql_fetch_assoc($query);
$_SESSION['logged_user_id']=$fetch['user_id'];
$_SESSION['logged_user_username']=$fetch['user_username'];
return true;
}
else
{
echo "<div class='error'>Dati non validi, ripeti la procedura di login o <a href='?index.php&module=registration'>registrati</a>!</div>";
}
}
}
else notfound();
}
Now i've a problem when i get the result of $.post() in my #ajax-input div submitting the login form, it doesn't return just the result of login function, but the index page+login function result.
If i try to set "json" parameter into $.post function and echo json_encode() in php function it doesn't work at all. So, what could be the problem?
you make a request for a full page here, I think.you could make a parameter, post or get, you decide, and if that is for example true, then you return the full page, and he it's false you only return a JSON string or something like that. I believe it is even possible to determine if the request is from ajax or not! That could be your second option. Just add a simple if-statement, I think.