I have a one signal javascript code and an ajax form, that give me a Player Id of the user in one signal,
so I want to use this code in my ajax login form and add the Player id to login form data, but i can't use a defined variable in one signal function, out of that and receive not defined message
OneSignal.push(function() {
OneSignal.getUserId(function(userId) {
var userid = userId;
});
});
var options = {
url: "{{CONFIG ajax_url}}/auth/login?hash_id=" + getHashID(),
beforeSubmit: function () {
$('#output-errors').empty();
$("#btn-submit").text("{{LANG Please wait..}}");
},
success: function (data) {
$("#btn-submit").text("{{LANG Login}}");
if (data.status == 200) {
if ($('#page').attr('data-page') != 'home' && $('#page').attr('data-page') != 'forgot' && $('#page').attr('data-page') != 'reset') {
$('#main-header').html(data.header);
$('#login_box').modal('hide');
if (Amplitude.getActiveSongMetadata().price >= 0) {
location.href = window.location.href;
} else {
ajaxRedirect();
}
} else {
location.href = window.location.href;
}
} else if (data.status == 400) {
var errros = data.errors.join("<br>");
$('#output-errors').html(errros);
}
},
// here i add the one signal id
data: {
OSid: userid
}
};
$('#login-form').ajaxForm(options);
There are a couple ways you can solve this, here's one approach:
OneSignal.push(function() {
OneSignal.getUserId(doAjax);
});
function doAjax(userId) {
var options = {
url: "{{CONFIG ajax_url}}/auth/login?hash_id=" + getHashID(),
beforeSubmit: function () {
$('#output-errors').empty()
...
}
$('#login-form').ajaxForm(options);
}
The function OneSignal.getUserId() takes a function as an argument, so my solution declares a function doAjax that will take the userId as an argument, and then we pass that function to the getUserId function.
Simplest way I suggest is:
Var userid;
OneSignal.push(function() {
OneSignal.getUserId(function(userId) {
userid = userId;
});
});
Related
I am trying to run 2 function where one is called inside the other.
I have a function and inside it I call a second function. I want to use the data from the second function in the first one.
function addLine() {
if (ContagemAntesIntegracao == '' || !ContagemAntesIntegracao) {
ContagemAntesIntegracao = 0;
}
var AfetaStock = '0';
verify_serialnumbers().complete(function (data){....
and the function that is runing inside:
function verify_serialnumbers() {
....if (ArrayErros.length > 0) {
set_errors(ArrayErros);
ArrayErros = undefined;
return;
}
...
var Link = $('#LINK').val() + '/?action=_ajax_inventory';
$.ajax({
type: 'POST',
url: Link,
dataType: 'json',
placeholder: 'Lote',
data: {
CheckSerialNumbers: '1',
CodArmazem: CodArmazem,
CodProduto: CodProduto,
CodLocalizacao: CodLocalizacao,
ArrayNumerosSerie: ArrayNumerosSerie,
}
}).done(function (response) {
if (response != 'ok')
{
set_errors(dados);
}else{
return ArrayNumerosSerie;
}
});
}
}
How can I continue inside the first one with an array that does not come from the AJAX call?
I have certain fields getting filled in my controller.
public string AjaxLogin()
{
//some code to check admin or not
Session["UserName"] = "Smith";
if(type="Admin")
{
Session["UserRole"] = 1;
}
Session["EmployeeID"] = 101;
}
I have an ajax call to this controller like below and if it is success, I need to access these session variables inside success to check the user role.
$.ajax(
{
url: GLOBAL.GetAppPath() + 'Home/AjaxLogin',
data: data,
type: 'POST',
error: function (xhr, status, error) {
console.log(error);
},
success: function (result, status, xhr) {
if (result == 'OK')
{
var UserVal = '#Session["UserRole"]';
alert(UserVal);
if(UserVal ==1)
{
var baseUrl ="#Url.Action("Admin","AdminPage")";
window.location.href = baseUrl;
}
else
{
var baseUrl ="#Url.Action("Admin","RegularPage")";
window.location.href = baseUrl;
}
}
else {
$('#msgError').html('Error: ' + result);
$('#msgError').css('display', 'block');
}
},
});
But I cannot access this variable in this call. I want to check the user role variable and give url actions accordingly.
If you want to redirect to a controller in your project you can use the Url helper for you
Sample:
return JavaScript( "window.location = '" + Url.Action("Edit","Dispatch") + "'" );
P.S: I couldn't comment since it asks for 50 reputation that's why I'm commenting it over here.
I am wanting to implement a recaptcha process that captures all ajax requests before they go through - the desired process would be as follows:
User completes an action which is going to cause an ajax request of some sort.
If the user has already completed the recaptcha process, the ajax request proceeds without further delay
If the user has not completed the recaptcha process, put the ajax request "on hold" temporarily until the recaptcha process is completed, then continue the ajax request.
I have got things to a state where I intercept the call, however I don't know how to put it on hold temporarily. Here's the relevant code:
<script>
var captchaValidated = null;
var currentRequests = [];
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (options.url != "/ValidateCaptcha") {
if (captchaValidated == null || captchaValidated == false) {
if (captchaValidated == null){
openRecaptcha();
} else {
verifyCaptcha(); //see async question in method
}
if (!captchaValidated) {
jqXHR.abort();
} else {
//let the original request proceed now - but how?!
}
}
}
});
function verifyCaptcha() {
var grecaptcha = $("g-recaptcha-response");
var encodedResponse;
if (grecaptcha != null) {
encodedResponse = grecaptcha.val();
$.ajax({
async: false, //set to false so that the calling method completes rather than async - what do you think?
headers: headers,
cache: false,
url: "/ValidateCaptcha",
type: 'POST',
contentType: 'application/json',
success: function (data) {
//parse the data - did we get back true?
captchaValidated = data;
},
error: function (raw, textStatus, errorThrown) { captchaValidated = null; alert("Validate ReCaptcha Error: " + JSON.stringify(raw)); },
data: JSON.stringify({ "encodedResponse": encodedResponse })
});
}
}
function invalidateCaptcha(){
captchaValidated = null;
}
function openRecaptcha() {
grecaptcha.render('recaptcha', {
'sitekey': "thekey",
'callback': verifyCaptcha,
'expired-callback': invalidateCaptcha,
'type': 'audio image'
});
$("#recaptchaModal").modal('show');
}
</script>
Any suggestions of how to proceed would be appreciated, thanks in advance!
Thank you #Loading and #guest271314 for your help in pointing me in the right direction that helped me get things figured out. I've pasted how I accomplished it below - perhaps it will be of help to someone else. Of course if anyone would like to weigh in on my implementation please do.
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCaptcha&render=explicit&hl=en" async defer></script>
<script>
var captchaValidated = null;
var currentRequests = [];
var captchaPrompted = false;
var captchaReady = false;
var resetCaptcha = false;
function onloadCaptcha() {
captchaReady = true;
captcha = grecaptcha.render('recaptcha', {
'sitekey': '<yoursitekey>',
'callback': verifyCaptcha,
'expired-callback': invalidateCaptcha,
'type': 'audio image'
});
}
var deferredCaptcha = null;
var promiseCaptcha = null;
var captcha = null;
function openRecaptcha() {
if (!captchaReady) {
setTimeout(openRecaptcha, 50);
}
if (captchaPrompted) {
return;
}
captchaPrompted = true;
var captchaTimer = setInterval(function () {
if (captchaValidated != null) {
if (captchaValidated) {
deferredCaptcha.resolve();
} else {
deferredCaptcha.reject();
captchaValidated = null;
}
}
}, 100);
if (resetCaptcha) {
captcha.reset();
}
deferredCaptcha = $.Deferred();
promiseCaptcha = deferredCaptcha.promise();
promiseCaptcha.done(function () {
//captcha was successful
clearInterval(captchaTimer);
//process the queue if there's items to go through
if (currentRequests.length > 0) {
for (var i = 0; i < currentRequests.length; i++) {
//re-request the item
$.ajax(currentRequests[i]);
}
}
});
promiseCaptcha.fail(function () {
//captcha failed
clearInterval(captchaTimer);
currentRequests = []; //clear the queue
});
$("#recaptchaModal").modal('show');
}
function verifyCaptcha() {
resetCaptcha = true;
var response = $("#g-recaptcha-response").val();
var encodedResponse;
// confirm its validity at the server end
$.ajax({
headers: headers,
cache: false,
url: "/ValidateCaptcha",
type: 'POST',
contentType: 'application/json',
success: function (data) {
captchaValidated = data;
if (!data) {
captchaPrompted = false;
}
},
error: function (raw, textStatus, errorThrown) { captchaValidated = false; captchaPrompted = false; alert("WTF Validate ReCaptcha Error?!: " + JSON.stringify(raw)); },
data: JSON.stringify({ "encodedResponse": response })
});
}
function invalidateCaptcha(){
deferredCaptcha.reject();
captchaValidated = null;
resetCaptcha = true;
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (settings.url == '/ValidateCaptcha' || captchaValidated) {
// we're validating the captcha server side now or it's already been validated - let it through
} else {
if (typeof settings.nested === 'undefined'){
settings.nested = true; //this flag is to determine whether it's already in the queue
currentRequests.push(settings); //add the request to the queue to be resubmitted
//prompt them with the captcha
openRecaptcha();
}
return false; // cancel this request
}
}
});
</script>
At $.ajaxPrefilter() use .then() chained to openCaptcha to call verifyCaptcha
if (captchaValidated == null){
openRecaptcha().then(verifyCaptcha);
}
at verifyCaptcha use .is() with parameter "*" to check if an element exists in document
if (grecaptcha.is("*")) {
at openRecaptcha(), if grecaptcha.render does not return asynchronous result return jQuery promise object using .promise(); else chain to grecaptcha.render and $("#recaptchaModal").modal('show'); using $.when()
return $("#recaptchaModal").modal('show').promise()
or
return $.when(grecaptcha.render(/* parameters */)
, $("#recaptchaModal").modal('show').promise())
Something like this? (pseudo-code)
verified = false;
$('#myButton').click(function(){
if (!verified) verify_by_captcha();
if (verified){
$.ajax(function(){
type: 'post',
url: 'path/to/ajax.php',
data: your_data
})
.done(function(recd){
//ajax completed, do what you need to do next
alert(recd);
});
}
});//end myButton.click
How to show can alert message in the ajax return request if the return request does not contain any data !!!
i have tried in the ajax success but nothing is working!
This is my script ---
<script>
$(document).ready(function () {
$("#searchform").on('submit', function (e) {
var data = {};
data['contentSearch'] = $('#contentSearch').val();
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (returnedData) {
$("#displayResult").html($(returnedData).find("#displayResult").html());
// how can i do something where so if the return value is null alert
}
}
});
return false;
});
});
</script>
console.log(returnedData) output
Do anyone knows how i can make an alert when the return value is null !!!
how about?
success: function (returnedData) {
if(!returnedData) alert('message');
}
Try this one....
< script >
$(document).ready(function() {
$("#searchform").on('submit', function(e) {
var data = {};
data['contentSearch'] = $('#contentSearch').val();
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function(returnedData) {
if(returnedData != "") { $("#displayResult").html($(returnedData).find("#displayResult").html());
} else {
alert("Data is Null");
}
}
}
});
return false;
});
}); < /script>
success: function (returnedData) {
if(!!returnedData && returnedData != null) {
$("#displayResult").html($(returnedData).find("#displayResult").html());
} else {
alert('No data');
}
}
Or this:
success: function (returnedData) {
if(returnedData && returnedData.length) {
$("#displayResult").html($(returnedData).find("#displayResult").html());
} else {
alert('No data');
}
}
success: function (returnedData) {
$("#displayResult").html($(returnedData).find("#displayResult").html());
// check whether your returned data is null
if(returnedData == null)
{
alert("Your message");
}
}
Replace it here --
success: function (returnedData) {
if($.trim(returnedData.length))
$("#displayResult").html($(returnedData).find("#displayResult").html());
else
alert('Nothing got');
}
}
May be you would like to do this:
success: function (returnedData) {
var data = $(returnedData).find("#displayResult").html() || ""; // this won't alert but
$("#displayResult").html(data); // sets a value if that's null
}
I also wanted to do the same thingy. You can try the following code fragment. It checks your callback data`s length. Depends on it, you can trigger your success message etc. If the length of return data is zero which means NO DATA, you can trigger the message relevant to that scenario.
success: function (returnedData) {
var sizeOfData = returnedData.length; // check the size of return data, be it zero means NO DATA
if (sizeOfData != 0) {
alert('Data exists !! Success !!');
}
else {
alert('No Data !! Error !!');
}
You can try as below :
if (returnedData == 'null' || returnedData == null){
alert('I am null');
}
I need to start polling a URL upon the page loading, to get a JMS response from a credit card server. I put the following together.
It works, but only if I hit the Refresh button on the browser. I want the data from the URL to load automatically when the page is first displayed, without requiring the user to Refresh.
I am missing a fundamental concept here, and would appreciate any advice on how to make it work. I have about 2 days of JavaScript experience so far.
<html>
<body>
<div id="p_results"></div>
<script type="text/javascript">
$(document).ready(function() {
function doJMSPolling() {
$.ajax({
url: "./poll",
type: "GET",
dataType: "text",
success: function(json) {
var json = $.parseJSON(json);
if (json.status === 'continue-polling' && json.msg === 'ok') {
setTimeout(function() {
doPolling();
}, 2000);
}
else if (json.status === 'stop-polling' && json.msg === 'success') {
for (key in json) {
if (key === "providerResponse") {
res = json[key];
for (reskey in res) {
$("#p_results").append(reskey + ":" + res[reskey] + "<br>");
}
}
}
} else if (json.status === 'stop-polling') {
$("#p_results").text(json.status);
}
}
});
}
});
</script>
</body>
</html>
You don't have to place the actual function definition inside your document.ready callback. The function can sit anywhere inside the <script> tags. Once you have done that, all you need to do is call the function from within the document.ready callback -
<script type="text/javascript">
$(function(){
doJMSPolling();
});
function doJMSPolling(){
...
}
</script>
Note :
$(function(){}) is shorthand for $(document).ready(function(){})
Seems to me that you're declaring your function, but not calling it. In order for the function's code to execute you'll need to add this after the function declaration within document.ready:
doJMSPolling();
Don't put your function within the document.ready, simply call it in there. Try this:
$(document).ready(function() {
doJMSPolling();
});
function doJMSPolling() {
$.ajax({
url: "./poll",
type: "GET",
dataType: "text",
success: function(json) {
var json = $.parseJSON(json);
if (json.status === 'continue-polling' && json.msg === 'ok') {
setTimeout(function() {
doPolling();
}, 2000);
}
else if (json.status === 'stop-polling' && json.msg === 'success') {
for (key in json) {
if (key === "providerResponse") {
res = json[key];
for (reskey in res) {
$("#p_results").append(reskey + ":" + res[reskey] + "<br>");
}
}
}
}
else if (json.status === 'stop-polling') {
$("#p_results").text(json.status);
}
}
});
}