$.post throwing "Illegal invocation " - javascript

Edit: None of the answers suggested so far have worked at all.
I'm running this call with django. The first time it runs, the server returns "n_usr" (which changes the form the user files in). The second time, it just throws an Illegal invocation error.
function log_in () {
username = $('#usr_enter').val();
password = $('#pass_enter').val();
if(!n_usr){
$.post('/ajax/login',{password: password, username: username}, function(data) {
if(data == "n_usr"){
$('#new_user_entry').show('slow');
n_usr = true;
}
else {
}
})
}else {
password2 = $('#pass_re_enter');
penname = $('#pen_enter');
$.post('/ajax/login', {password: password, password2: password2, username: username, pen_name: penname, TN: "TN"}, function(data) {
if(data == "e_act"){
} else {
}
});
}
}

In your else, you have:
password2 = $('#pass_re_enter');
penname = $('#pen_enter');
Then you have:
{password: password, password2: password2, username: username, pen_name: penname, TN: "TN"}
You are getting Illegal invocation because jQuery is trying to serialize the jQuery object for $.post, and it can't. It's probably trying to call a string method, and is passing it a jQuery object as context, thus causing the error.
You need to add .val().
password2 = $('#pass_re_enter').val();
penname = $('#pen_enter').val();

Well you are not calling them the same -- the first time:
$.post(url_base+'/ajax/login' ...
and the 2nd
$.post('/ajax/login', {....
Change the 2nd one to include url_base.

Related

How to automatically populate fields from ajax request in spring boot?

I made an ajax request to the server for checking whether a particular username exists in the database. Here is the code for that..
$("input[placeholder='Username']").focusout(function() {
var username = $("input[placeholder='Username']").val();
if(username.length <3 || username.length>20) {
$("#username_taken").html("Username must be between 3-20 characters!");
usernameFlag = true;
}
else if(username != null) {
$.ajax({
type: "POST",
url: "/data/validate_username",
data: username,
success: function(isValid) {
if(!isValid) {
$("#username_taken").html("The username has already been taken!");
usernameFlag = true;
}
},
error: function() {
$("#username_taken").html("Could not verify username from server!");
}
});
}
});
In the server side I have written a RestController to handle this request and provide the data on whether the user exists or not.
// necessary imports done...
#RequestMapping("/data")
#RestController
public class UserAccountRest {
#Autowired
private UserAccountService userAccountService;
#PostMapping("/validate_username")
public boolean validateUsername(String username) {
return !userAccountService.accountExists(new UserAccount(username));
}
}
Normally spring auto populates the parameters like username, if it was a form submit. But here status 500 Internal Server Error occurs, and in the console it says that the id must not be null. This means that the username is not populated.
I could probably use HttpRequest object in the parameter and get the username from it. But is there any way to configure so that the username is directly populated?
The data sent needs to have key/value pairs.
When you get the value of an <input> you only have 1/2 of the pair. Your variable username only contains the value part
Change
data: username,
To
data: {username : username}
Have you tried doing
public boolean validateUsername(#RequestBody String username) {
return !userAccountService.accountExists(new UserAccount(username));
}
You are probably posting a JSON value which should be a key value pair.

function not working: not getting info from form fields

Trying to figure out why this code doesn't work. When I console.log the userinfo, it comes back as ["", ""]. So, it's not collecting the username or password.
According to the documentation,
GET /users
returns a list of users.
{"users": ["alex", "bill", "charlie"]}
200 - Successful
GET /users/:name
Display a user.
200 - Successful
404 - User not found
What's going on?
/**
* Click event handler for submit button, return username and password
*/
function getInfo(){
var user = document.getElementById("username").value;
var username = user;
var pass = document.getElementById("password").value;
var password = pass;
return [username, password];
}
document.getElementById("submit").addEventListener("click", getInfo, false);
var userinfo = getInfo();
var username = userinfo[0];
var password = userinfo[1];
console.log(userinfo);
/**
* Get request for user's information, return user data, save as user.
* Check for matching password - if true open userprofile.html
* If false, show notice from index.html, reset user to empty
*/
function showGetResult( username )
{
var result = {};
var scriptUrl = "http://localhost:4567/main.rb";
$.ajax({
url: scriptUrl,
type: 'get/users[username]',
dataType: 'json',
async: false,
success: function(data) {
result.append(data);
}
});
return result;
}
var user = showGetResult(username);
console.log(user);
function passwordCheck(user, password)
{
if (user[2] === password){
window.open = "http://localhost:4567/userprofile/userprofile.html";
}
else {
document.getElementById("notice").style.display = "block";
user = {};
}
}
passwordCheck(user, password);
console.log("still working");
When you’re dealing with the DOM it’s important to execute your code only after the page is fully loaded. If you don’t, there’s a good chance the DOM won’t be created by the time your code executes. That's why you keep getting empty results or sometimes error. To overcome this, you need to ensure your script executes only when the page load is completed.
window.onload = init;
var username = "", password = "";
function init() {
document.getElementById("submit").addEventListener("click", getInfo, false);
}
function getInfo(){
username = document.getElementById("username").value;
password = document.getElementById("password").value;
}
I noticed you invoke the function getInfo() manually in your code. I don't know why you are doing that. By using the above code, your function will be invoked only when the submit button is clicked.

Meteor: Async Callback issues

Currently I have the user click submit and then a click event occurs where a token is created and a method is called. What I am trying to do is after the charge get a callback which says if it is successfully or not. If successful it will run router.go to the confirmation page. If it is not successful then it will let the user know the card has been declined. All the above I can code out except despite non stop tinkering, I can't seem to figure out how to pass the message back to the event.
Here is my server side method:
Meteor.methods({
'chargeCard': function(token,amount,email) {
var Stripe = StripeAPI('where the key info guys');
// get a sync version of our API async func
var stripeCustomersCreateSync=Meteor.wrapAsync(Stripe.customers.create,Stripe.customers);
// call the sync version of our API func with the parameters from the method call
var result=stripeCustomersCreateSync({
description: 'Woot! A new customer!',
card: token,
email: email
}, function(error,result) {
if(error) {
return error;
}
return 'Success';
});
return result;
}
});
and my Client side method:
Stripe.card.createToken({
number: $('#cc-number').val(),
cvc: $('#card-cvc').val(),
exp_month: expM,
exp_year: expY,
name: $('#fn').val(),
address_zip: $('#postCode').val()
}, stripeResponseHandler);
}
function stripeResponseHandler(status, response) {
var $form = $('form');
if (response.error) {
// Show the errors on the form
$form.find('.validation').text(response.error.message);
return false;
} else {
var token = response.id;
var amount = 15000;
var Payid = $('#pid').text();
var userEmail = Leaguemembers.findOne({_id: Payid}).Email;
Meteor.call('chargeCard', token, amount,userEmail, function (error, result) {
console.log(error,result); alert(result); alert(error);
}
);
}
};
Any help would be greatly appreciated.
EDIT:
I went back into the backend and I can see the errors being generated through console.log but still am unable to pass it back to where the call was made to display those errors to the user or pass them to the confirmation page. All I seem to get is undefined.
The meteor.call should look like this
Meteor.call('chargeCard',token,amount,username,function(err,result){
if(!err){
Router.go("theRoute") //if there is not error go to the route
}else{
console.log(err.reason) // show the error
}
})

AJAX "success" executing before response is returned

I'm hoping this is just a simple fix due to me being a little dumb somewhere along the line. I'm executing my ASP.NET MVC login using AJAX. There is a "success" handler which returns a "true" value to the calling function which, in turn, load the home page.
The issue is that the "success" handler is executing BEFORE any value is returned - which means that nothing happens because the value is not "SUCCESS". I can confirm this by looking at the request in Firebug, the value returned is SUCCESS but nothing happens. If I apply a breakpoint to the end of the function and then continue execution it works just fine.
I have no idea what the issue is, I'd be very grateful for help or an explanation to what I'm doing wrong.
Thanks!
My JS Function:
function LogIn(UserName, Password) {
var Cont = true;
var ErrorString = "";
if (UserName == null || UserName == "") {
Cont = false;
ErrorString += "Username is Required.";
}
if (Password == null || Password == "") {
Cont = false;
ErrorString += "Password is Required.";
}
var result = false;
if (Cont) {
var LogInUrl = "/AJAX/LogIn?UserName=" + UserName + "&Password=" + Password;
$.ajax({
url: LogInUrl,
type:"GET",
success: function( data ){
if (data == "SUCCESS") {
result = true;
}
}
})
}
return result;
}
UPDATE: The function that calls the LogIn function:
$('#FormLogin').submit(function (e) {
e.preventDefault();
var UserName = $("#TxtLoginUsername").val();
var Password = $("#TxtLoginPassword").val();
var IsLoggedIn = LogIn(UserName, Password);
if (IsLoggedIn) {
window.location.assign("/");
} else {
$('#LoginErrorContainer').show();
$('#LoginErrorContainer .error-text').html("There was a problem logging you in. Please try again.");
}
})
As I said, the function does it's job and logs me in, but the "success" handler seems to execute before the value is returned.
Change your ajax call to something like this:
$.ajax({
url: LogInUrl,
type:"GET",
success: function( data ){
if (data == "SUCCESS") {
window.location.assign("/");
} else {
$('#LoginErrorContainer').show();
$('#LoginErrorContainer .error-text').html("There was a problem logging you in. Please try again.");
}
}
});
There is no point in returning result from LogIn, it'll always be false. You need to put the code handling the returned value in the callback.
Another alternative, if you don't like the idea of your LogIn function being so closely coupled to DOM manipulation is to return the promise from your ajax call. So at the end of LogIn, you'd do something like this:
return $.ajax({
url: LogInUrl,
type:"GET"
}
});
And then when you call it, you'd do something like this:
LogIn(UserName, Password).then(function(data) {
if (data == "SUCCESS") {
window.location.assign("/");
} else {
$('#LoginErrorContainer').show();
$('#LoginErrorContainer .error-text').html("There was a problem logging you in. Please try again.");
}
});

Uncaught TypeError: undefined is not a function for request() in Titanium

I have a problem with 1 of my functions.
in app.js ia have th following:
//Including all functions
Ti.include('functions.js');
//Including the login screen
Ti.include('login.js');
//Including the register screen
Ti.include('register.js');
So all the functions are above the other files that could call a function.
In login.js I have the following code:
//'login' is the type
var request = request('login', loginUsernameInput.value, md5(loginPasswordInput.value));
Ti.API.info('request: ' + request);
if(request == true) {
alert('You are loggedin');
} else {
alert('Something went wrong');
}
The request function looks like this:
function request(type, username, password) {
//Database connection
var db = Ti.Network.createHTTPClient();
db.open('POST', 'http://myip/mobile_app/');
Ti.API.info('type: ' + type);
Ti.API.info('username: ' + username);
Ti.API.info('password: ' + password);
//If variables has been send
db.onload = function() {
var answer = this.responseText;
Ti.API.info('type answer: ' + typeof this.responseText);
if(answer == 'true') {
Ti.API.info('TEST');
return true;
} else {
return false;
}
};
//Variables to send
db.send({
type: type,
username: username,
password: md5(password)
});
//If there is an error
db.onerror = function(e) {
Ti.API.info('error: ' + JSON.stringify(e));
};
}
I know that this.responseText returns true and that the function md5() works aswell.
I know this because I also tested login.js when the code is like:
Ti.API.info('request: ' + request('login', loginUsernameInput.value, md5(loginPasswordInput.value)));
if(request('login', loginUsernameInput.value, md5(loginPasswordInput.value)) == true) {
alert('You are loggedin');
} else {
alert('Something went wrong');
}
The above also returns that function request() is undefined
So as soon as try to login I get the following error:
So my question is how can resolve the error?
I think the issue is that you redefine variable request to the return value of function request. You request function does not return anything. Therefore it returns undefined.
Now that you set request to undefined. You cannot use request() anymore, because you overwrote it.
Attempting to call an undefined value as a function, results in undefined is not a function
See demonstration: http://repl.it/UXE/1
Indeed, #Gabs00 is right when he says that you're redefining your request variable.
But the real question is how could you have avoid this problem ?
And the answer is in the way you're coding. By using Ti.include, you're not using the best practices recommended by Titanium.
Instead, you should do something like this :
In a file models/User.js :
exports.request = function(type, username, password) {
// Your code here
};
Then, instead of writing (in your app.js file) :
Ti.include('functions.js');
var request = request('login', loginUsernameInput.value, md5(loginPasswordInput.value));
You'll have :
var User = require('models/User');
User.request('login', loginUsernameInput.value, md5(loginPasswordInput.value));
But even with this code, it's sot satisfying enough...
What you should probably try is to declare as many functions as your requests. Even if your code is common for your 2 requests for now, I can assure you that it won't be that way very long.
Thus, there is the final code I recommend :
In your models/User.js file :
function request(type, username, password) {
// Your code
};
exports.login = function(username, password) {
request('login', username, password);
};
exports.register = function(username, password) {
request('register', username, password);
};
The cool thing with this code is that your request method is totally protected: the only code which can access this function is the one written in your models/User.js file. For the others, it's like this function doesn't even exist.
In you app.js file :
var User = require('models/User');
User.login(loginUsernameInput.value, md5(loginPasswordInput.value));
I think it's more readable this way, don't you?
If you want more information about this pattern, you should probably read these articles:
CommonJS modules
Titanium best practices
As you'll see, you should reuse this pattern for your windows too (your Ti.include('login.js'); and Ti.include('register.js');)
This question got answered here: http://developer.appcelerator.com/question/175412/function-not-returning-anything#280011
Edit:
In User.js:
function request(type, username, password, callback) {
db.onload = function() {
Ti.API.info('type antwoord: ' + typeof this.responseText);
callback( this.responseText );
};
}
exports.login = function(username, password, callback) {
request('login', username, password, callback);
};
and in login.js:
// last parameter is the callback function
User.login(loginUsernameInput.value, md5(loginPasswordInput.value), function(response){
Ti.API.info('login response: ' + response)
});
now i get true or false as response.

Categories