I know a similar question has be asked but none helped in my case.
I am developing a Cordova app. I ran series of test on the app and everything (Navigation, Web Service call) works fine using my system browsers(IE and Mozilla)
Now using Eclipse, From the Emulator, I tried to log-in to the app (Authentication should invoke the webservice) but nothing happens.
On checking the LogCat I saw an Exception:
Uncaught SyntaxError: Unexpected token )", Source: File:///android_asset/www/login.html
Here is the .js script part:
$(document).on('click', '#S_IN', function() {
if (($('#username').val() == "") || ($('#password').val() == "")) {
alert("All fields are required.");
} else {
$.ajax({
type: "POST",
data: JSON.stringify({
"username": $('#username').val(),
"password": $('#password').val()
}),
url: "http://127.0.0.1/appName/Service.asmx/Authenticate",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
if (JSON.parse(data.d).toLowerCase() == 'success') {
$.mobile.changePage('main.html');
} else {
alert("Login failed. Invalid Username or Password combination.");
}
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
}
});
}
});
//..............................Login End........................//
Pls what am I doing wrong? I'm stuck.
Imaxo, your code style isnt so good, you need to do the follow things:
Procces data after DOM/window is loaded
declare variables
do not attach events to document(except keyboard events which should
fired without form)
prepare data before put it to request
and here is the small example:
firstFile.js
var app = app || {};
app.auth = (function(){
return {
initialize: function(){
//declare variable
//this.variable = global for this object
//var some; = local for this method
},
validate: function(){
//validate data
},
send: function(){
//send AJAX request
}
//other methods
}
})();
secondFile.js
var app = app || {};
$(function(){
app.auth.initialize();
});
this is revealing modular pattern with basic module organization pattern, but better look at require.js
asnwering your question, somewhere in your code you write excess ")"
Related
I am working on Asp.Net core application and Application is running fine on my local but I am not able to validate Antiforgery token on the server.
Error: "Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted."
Below is the code.
#section scripts {
<script type="text/javascript">
$(document).ready(function() {
$("#btnstart").click(function(e) {
let productvals = $("#productlist").val();
let runnumber = $("#runnum").val();
let btnval = $("#btnstart").val();
e.preventDefault();
$.ajax({
url: "#Url.Action("
CheckRunnumber ","
Validation ")",
type: "POST",
dataType: "json",
data: {
runnumber: $('#runnum').val()
},
success: function(data) {
if (data.success == "True") {
console.log(data);
console.log(data.btnstartval);
//$("#Runform").submit();
if ($("#Runform").valid()) {
console.log(productvals, runnumber, data.btnstartval);
console.log(gettoken());
$.ajax({
url: "#Url.Action("
RunCase ", "
CallService ")",
type: "POST",
dataType: "json",
data: {
products: productvals,
runnumber: runnumber,
button: data.btnstartval,
__RequestVerificationToken: gettoken()
},
contentType: 'application/x-www-form-urlencoded; charset=utf-8'
});
} else {
alert("Error");
e.preventDefault();
}
}
}
});
function gettoken() {
var token = '#Html.AntiForgeryToken()';
token = $(token).val();
return token;
}
}
}
</script>
}
To compare this token I logged it on the console window and it is different then the one under Application tab inside the inspect window.
Below is the error log I am getting.
2020-10-08T13:00:05.5115395-05:00 0HM3BMFTTVJ22:00000001 [ERR] An exception was thrown while deserializing the token. (348bf365)
Microsoft.AspNetCore.Antiforgery.AntiforgeryValidationException: The antiforgery token could not be decrypted.
---> System.Security.Cryptography.CryptographicException: The key {dbeef040-4a73-45ff-8b62-064683015ea1} was not found in the key ring.
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[] protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus& status)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[] protectedData, Boolean ignoreRevocationErrors, Boolean& requiresMigration, Boolean& wasRevoked)
at Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[] protectedData)
at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)
--- End of inner exception stack trace ---
at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgeryTokenSerializer.Deserialize(String serializedToken)
at Microsoft.AspNetCore.Antiforgery.DefaultAntiforgery.GetCookieTokenDoesNotThrow(HttpContext httpContext)
2020-10-08T13:00:35.9439222-05:00 0HM3BMFTTVJ22:00000004 [INF] Process not found (d326d86c)
Do you host your application on shared server backend or else? It seems that your application doesn't have enough permission to read the key.
I suggest you could try to modify the IIS application pool identity to have enough permission to read the key. More details ,you could refer to below steps:
1.Open IIS management console:
2.Select your application pool
3.Modify the application pool identity to local system or other domain account which has enough permission to access your keys.
If this couldn't solve your issue, could you please share the startup.cs settings?
This javascript within an Office js add-in always fails when making a get request:
function update() {
Excel.run(function (ctx) {
return ctx.sync()
.then(function () {
var company = $('#company').val();
var environment = $('#environment').val();
var apiUrl = "https://localhost:44321/api/Country";
var params = "company=" + company + "&environment=" + environment;
$.getJSON(apiUrl, params)
.done(function (result) {
showNotification(result.length);
})
.fail(function (xhr, status, error) {
//showNotification(error.statusText);
showNotification(error.length);
});
});
}).catch(function (error) {
showNotification(error);
});
}
I can see the json being returned successfully within Fiddler and JSONLint says the json is valid. Here it is:
[{"country":"UK","countryLongName":"United Kingdom","currency":"GBP"}]
I'm running on localhost with https, and have the following AppDomains in my manifest (belt and braces):
<AppDomain>https://localhost:44321/api/Country</AppDomain>
<AppDomain>https://localhost:44321</AppDomain>
<AppDomain>https://localhost</AppDomain>
However, getJSON.fail() is always invoked, with the following parameters:
xhr.responseJSON: undefined
xhr.statusText: "error"
status: "error"
error: ""
Why does getJSON always fail?
Further edit
I've tried this js instead...
$.ajax({
url: apiUrl,
dataType: 'json',
async: false,
data: params,
success: function (data) {
showNotification(data);
},
error: function (msg) {
showNotification('error : ' + msg.d);
}
});
...and now the error function is being invoked with the following parameters:
msg.responseJSON: undefined
msg.status: 0
msg.statusText: "NetworkError"
It's all to do with CORS, I found the solution in rick-strahl's post:
https://weblog.west-wind.com/posts/2016/Sep/26/ASPNET-Core-and-CORS-Gotchas#ApplythePolicy
Specifically,
"UseCors() has to be called before UseMvc()
Make sure you declare the CORS functionality before MVC so the middleware fires before the MVC pipeline gets control and terminates the request."
I am currently developping a new website
When I am trying to create an account, I get an error like this :
Uncaught TypeError: Cannot read property 'hasError' of null.
And this is the code
function submitFunction()
{
$('#create_account_error').html('').hide();
//send the ajax request to the server
$.ajax({
type: 'POST',
url: baseUri,
async: true,
cache: false,
dataType : "json",
data: {
controller: 'authentication',
SubmitCreate: 1,
ajax: true,
email_create: $('#email_create').val(),
back: $('input[name=back]').val(),
token: token
},
success: function(jsonData)
{
if (jsonData.hasError())
{
var errors = '';
for(error in jsonData.errors)
//IE6 bug fix
if(error != 'indexOf')
errors += '<li>'+jsonData.errors[error]+'</li>';
$('#create_account_error').html('<ol>'+errors+'</ol>').show();
}
else
{
// adding a div to display a transition
$('#center_column').html('<div id="noSlide">'+$('#center_column').html()+'</div>');
$('#noSlide').fadeOut('slow', function(){
$('#noSlide').html(jsonData.page);
// update the state (when this file is called from AJAX you still need to update the state)
bindStateInputAndUpdate();
$(this).fadeIn('slow', function(){
document.location = '#account-creation';
});
});
}
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert("TECHNICAL ERROR: unable to load form.\n\nDetails:\nError thrown: " + XMLHttpRequest + "\n" + 'Text status: ' + textStatus);
}
});
}
It seems to be the jsonData, on the function, which is not working as well. Any idea or suggestions?
The success handler will be passed the data returned from the ajax request.
It will not have a function called hasError() because it is just a json object it will not have any functions.
The error handler should be fired if there is an http error i.e. if the ajax call returns an http 500.
I'm not familiar with prestashop, but looking over the prestashop documentation hasError is returned as a bool (not a function), so instead try (without the parenthesis).
if (jsonData.hasError)
You may also want to check if any data is returned first.
if (jsonData)
I am working on a piece of code where the user clicks on a button to make a call and the status of the call is displayed to him/her.
Everything is working fine and the calls are being made too, but the server which sends the json response is on another domain and I have no control over its response. I therefore used jsonp to get the response, but no matter what i did, i keep getting the error of Uncaught SyntaxError: Unexpected token.
I am attaching my code. please help as this is a live project and I am badly stuck in it. I need a response to be alerted with the message received by the server. the message received by the server in case of success is {"success": {"status": "success", "message": "Call successfully placed"}} and in case of error is {"error": {"message": "Invalid API Key"}}. I just need to display the message part.
my code:
function makecall() {
document.getElementById('<%=click2call_submitbtn.ClientID%>').disabled = true;
var agentNum = document.getElementById('<%=lblCallFrom.ClientID%>').innerHTML;
var custNum = "+91";
custNum = custNum + document.getElementById('<%=txtNotoCall.ClientID%>').value;
document.getElementById('<%=lblCallStatus.ClientID%>').innerHTML = "Calling...";
if (validatePhone(agentNum) && validatePhone(custNum)) {
$.ajax({
url: 'http://www.knowlarity.com/vr/api/click2call/?api_key=9e69eab0-1ec7-11e3-866c-16829204aaa4&agent_number=agent_number_variable&phone_number=Caller_number_variable&sr_number=%2B918881692001&response_format=json'.replace('Caller_number_variable', custNum.replace('+', '%2B')).replace('agent_number_variable', agentNum.replace('+', '%2B')),
type: 'GET',
cache: false,
dataType: 'jsonp',
success: function (res) {
alert(JSON.stringify(res));
},
error: function (res) {
alert(JSON.stringify(res));
}
});
} else {
document.getElementById('<%=lblCallStatus.ClientID%>').innerHTML = "Num. should be a valid 10 digit mobile no.";
document.getElementById('<%=click2call_submitbtn.ClientID%>').disabled = false;
}
}
Try using this as an absolute minimum where you can pass in valid hard wired values for the numbers:
var url = 'http://ip.jsontest.com/ ';
$.ajax({
url: url,
cache: false,
dataType: 'jsonp',
success: function (res) {
if (res != undefined) console.log(res);
},
error: function (res) {
if (res != undefined) console.log(res);
}
});
I am trying to POST some data to my ASP.Net MVC Web API controller and trying to get it back in the response. I have the following script for the post:
$('#recordUser').click(function () {
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: $("#recordUserForm").serialize(),
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
//...
}
}
});
});
The problem with this script is that whenever I try to post the data, the jQuery comes back in "error" instead of "success".
I have made sure that there is no problem with my controller. I can get into my api method in debug mode whenever the request is made and can see that it is getting the data from the POST request and is returning it back. This controller is quite simple:
public class RecordUserController : ApiController
{
public RecordUserEmailDTO Post(RecordUserEmailDTO userEmail)
{
return userEmail;
}
}
I am not sure how I can get jQuery to print out any useful error messages. Currently when I try to debug the jQuery code using Chrome console it shows an empty xhr.responseText, nothing in "err" object and "status" set to "error" which as you see is not quite helpful.
One more thing that I have tried is to run the following code directly from the console:
$.ajax({
type: 'POST',
url: 'api/RecordUser',
data: {"Email":"email#address.com"},
dataType: 'json',
success: function (useremail) {
console.log(useremail);
},
error: function (xhr, status, err) {
console.log(xhr);
console.log(err);
console.log(status);
alert(err.Message);
},
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
}
}
});
i.e. using the same script without actually clicking on the button and submitting the form. Surprisingly, this comes back with the right response and I can see my data printed out in console. For me this atleast means that my Web API controller is working fine but leaves me with no clue as to why it is not working on clicking the button or submitting the form and goes into "error" instead of "success".
I have failed to find any errors in my approach and would be glad if someone could help me in getting a response back when the form is posted.
As suggested by Alnitak, I was using complete callback along with success and error ones. Removing complete from my code fixed the issue.
Thanks to Alnitak.