ajax:send form, can't receive parameters? - ajax

I try to send a form use ajax. I can send the information successfully. And I can receive the information. However, I can't get parameters form the request. I don't know the reason.
I try IE, FIREFOX, Chrome, none of them can send the form.
This is my code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="Expires" content="0">
<meta http-equiv="kiben" content="no-cache">
<title>Login Page</title>
<%String account =(String) session.getAttribute("fail"); %>
</script>
<script language="javascript" type="text/JavaScript" src="jquery-1.3.2.min.js">
</script>
<script language="javascript" type="text/JavaScript">
window.onload = function fillChecklist(){
var error ="${sessionScope.fail}";;
if(null != error&& error!=""){
alert(error);
}
}
function doFind() {
if(document.getElementById("username").value.length>0&&document.getElementById("password").value.length>0){
$.ajax({
cache : false,
type : "POST",
url : "login",
data : $("#ajaxFrm").serialize(),
async : false,
error : function(request) {
alert(“error");
},
success : function(data) {
//$("#ajaxDiv").html(data);
alert(data);
}
});
}
}
</script>
</head>
<body>
<form id="ajaxFrm" >
UserName<input type="text" id="username" ><br />
Password &nbsp<input type="password" id="password">
</form>
<input type="checkbox" name="remember" id="remember">Remeber Username</input><br />
<input value="Submit" type="button" onClick="doFind()"/>
<input value="Delete" type="button" onClick="DelCookie()"/>
<div id="ajaxDiv"></div>
</body>
</html>

Please change your input type="button" to input type="submit" first, and then submit with ajax.e.g
<html>
<head>
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript">
$("form#ajaxFrm").submit(function() {
var mydata = $("form#ajaxFrm").serialize();
console.log(mydata); //check data before send to server
$.ajax({
type: "POST",
url: "myUrlToPostData.php",
data: mydata,
success: function(response, textStatus, xhr) {
alert("success");
},
error: function(xhr, textStatus, errorThrown) {
alert("error");
}
});
return false;
});
</script>
</head>
<body>
<form id="ajaxFrm" method="post">
UserName<input type="text" id="username" name="username"/><br />
Password <input type="password" id="password" name="password"/>
<input value="submit" type="submit" name="submit"/>
</form>
</body>
</html>

Related

semantic-ui form validation with google recaptcha (captcha)

Any simple way to implement semantic-ui form validation with google recaptcha if the recaptcha field is checked or empty?
To expand on Arpit's answer:
Here's a non-Angular solution that worked for me
Custom validation rule above your fields validation:
$.fn.form.settings.rules.recaptchaValidate = function() {
return (recaptchaVerified);
};
Add this to your validation:
recaptcha: {
identifier: 'recaptcha',
rules: [
{
type: 'recaptchaValidate',
prompt: 'Please complete reCaptcha validation.'
}
]
}
and your HTML:
<div class="required field">
<div class="g-recaptcha" data-sitekey="{your key here}" data-callback="correctCaptcha"></div>
<input type="hidden" name="recaptcha" id="recaptch-validation">
</div>
[ ... then this just before closing body tag ... ]
<script type="text/javascript">
var recaptchaVerified = false;
var correctCaptcha = function(response) {
recaptchaVerified = true;
};
var expiredCaptcha = function() {
recaptchaVerified = false;
};
</script>
use below validation for Google reCaptcha validation.
Script:
$(document).ready(function () {
$('.ui.form').form({
recaptcha: {
identifier: 'g-recaptcha-response',
rules: [
{
type: 'empty',
prompt: 'Please complete reCaptcha validation.'
}
]
}
},
{
onSuccess: function (event, fields) {
console.log('Success:', fields);
return false;
//event.preventDefault();
},
onFailure: function (error) {
console.log('Failure',error);
return false;
}
});
});
HTML:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Self Registration Module</title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<script src="../../Content/Scripts/jquery.min.js"></script> <!-- version 3.0.0 ->
<script src="../../Content/semantic/semantic.min.js"></script>
<link href="../../Content/semantic/semantic.min.css" type="text/css" rel="stylesheet" class="ui" />
<script src="https://www.google.com/recaptcha/api.js?onload=vcRecaptchaApiLoaded&render=explicit" async defer></script>
</head>
<body ng-app="registrationApp">
<div class="ui container" lang="en"
<div class="ui attached message">
<div class="header">
Registation Form
</div>
<p>Fill out the form below to register user in rev</p>
</div>
<form class="ui form attached segment">
<div class="field">
<div vc-recaptcha
key="'6Lf4ax0UAAAAADWkffMAXBsFzx2dgkMMnqvw4tIE'"
ng-model="RecaptchaResponse">
</div>
</div>
</div>
</form>
</div>
</body>
</html>

Uncaught Error: Parse Error: Unexpected token

new to parse and react and I'm I'm getting this error
Uncaught Error: Parse Error: Line 50: Unexpected token
observe: function() {
How can I fix it ?
Here is my whole code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width">
<link href='http://fonts.googleapis.com/css?family=Roboto:400' rel='stylesheet' type='text/css'>
<script src="http://fb.me/react-0.13.3.min.js"></script>
<script src="https://www.parsecdn.com/js/parse-latest.js"></script>
<!-- Now include parse-react.js -->
<script src="https://www.parsecdn.com/js/parse-react.js"></script>
</head>
<body>
<script src="./jquery.min.js"></script>
<script src="./jquery.velocity.min.js"></script>
<script src="./velocity.ui.min.js"></script>
<script src="./react.js"></script>
<script src="./JSXTransformer.js"></script>
<script type="text/jsx">
/** #jsx React.DOM */
var App = React.createClass({
render: function() {
var name=null;
var password=null;
var email=null;
return (
<div>
<label>Name</label>
<input type="text" ref="name" /><br/>
<label>Password</label>
<input type="password" ref="password" /><br/>
<label>Email</label>
<input type="email" ref="email" /><br/>
<button onClick={this.saveAndContinue}>
Save and Continue
</button>
</div>
)
},
saveAndContinue: function(e) {
e.preventDefault()
//debugger;
// Get values via this.refs
data = {
name: this.refs.name.getDOMNode().value,
password: this.refs.password.getDOMNode().value,
email: this.refs.email.getDOMNode().value,
}
//this.props.saveValues(data)
},
//this.props.nextStep()
saveValues: function()
{
return function()
{
mixins: [ParseReact.Mixin],
observe: function() {
return {
};
}
}
}
}
);
React.renderComponent(<App />, document.body);
</script>
</body>
</html>
Since I'm new to this so Any Help will be appreciated. Thanks
saveValues is a function that returns a function. Within the returned function body you seem to attempt to use object literal syntax.
function() {
a: "something",
b: "something else"
}
is not valid syntax. You probably mean to return some object.

MEAN stack ajax POST Error: TypeError: Cannot read property 'userName' of undefined

So, here's some background: I am working on a MEAN stack app for my school where we can read and post our Galaga and Dig Dig highscores to a mongo database.
I am getting an error:
POST http://url.com/api/scores 500 (Internal Server Error)
TypeError: Cannot read property 'userName' of undefined at /app/server.js:37:22
server.js:37 is:
app.post("/api/scores", function(req, res){
Score.create({
name:res.body.userName,
game:res.body.game,
points:res.body.userPoints
});
});
The index.html that the res.body.* is coming from is:
<!DOCTYPE html>
<html ng-app="nameOfApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
<script src="core.js"></script>
</head>
<body ng-controller="mainController">
<div class="container">
<div class="jumbotron text-center">
<div class="container">
<h1>HelpDesk Gaming Leaderboard</h1>
</div>
</div>
<div class="container">
<table>
<tr>
<td><b>Name</b></td>
<td><b>Score</b></td>
</tr>
<tr ng-repeat="score in scores">
<td>{{score.name}}</td>
<td>{{score.points}}</td>
</tr>
</table>
</div>
<br/>
<h2>Score?</h2>
<form>
<input name="userName" type="String" class="form-control" id="userName" ng-model="formData.userName" placeholder="Your Name">
<input name="game" type="String" class="form-control" id="game" ng-model="formData.game" placeholder="The game?">
<input name="userPoint" type="Number" class="form-control" id="userPoint" ng-model="formData.userPoint" placeholder="Points?">
<button type="submit" class="btn btn-default" ng-click="createScore()">Submit</button>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js">
</script>
</body>
</html>
and the core.js, which is the angular piece is:
var nameOfApp= angular.module('nameOfApp', []);
nameOfApp.controller("mainController", ["$scope", "$http", function($scope, $http) {
$scope.formData = {};
// when landing on the page, get all scores and show them
$http.get('/api/scores')
.success(function(data) {
$scope.scores = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
$scope.createScore = function() {
$http.post('/api/scores', $scope.formData)
.success(function(data) {
$scope.formData = {};
$scope.scores = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
}]);
Thanks for your input, and if there are any stylistic things that I have wrong, I would love to hear them. I am trying to get better at MEAN stack development.
It's not res.body.* you want to use in your Score.create method, you want to be using req.body.*. 'req' is what has all the data from your http request.
Should be:
app.post("/api/scores", function(req, res){
Score.create({
name:req.body.userName,
game:req.body.game,
points:req.body.userPoints
});
});

jQuery Mobile and Cordova not sending AJAX HTTP request multi-page model

I have searched this forum for answers and have tried different suggestions that worked for others but did not work for me - including adding the site address to the whitelist in config.xml.
I am working on developing a web app using HTML5, CSS and JavaScript with Cordova 3.5.0-0.2.6 and jQuery Mobile 1.4.3 for the UI. I am using a multi-page JQM page model with the need to make ajax request to submit forms to a server.
Testing the code on localhost works fine but when I build on Android platform in Cordova, the request is not even sent at all as I get the alert message I wrote for when the request is not sent ("Could not connect!").
The code is supposed to use the JSON object returned from the server to display the next page. My codes are as shown below:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="jquery.mobile.theme-1.4.3.min.css" />
<link rel="stylesheet" href="jquery.mobile-1.4.3.min.css" />
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).on("pageinit", function(){
$.mobile.allowCrossDomainPages = true;
$.support.cors = true;
});
</script>
<script type="text/javascript" src="jquery.mobile-1.4.3.min.js"></script>
<script type="text/javascript" src="cordova.js"></script>
</head>
<body>
<div data-role="page" id="login">
<script>
$(document).bind('mobileinit', '#login', function(){
$(function() {
$("#loginSubmit").on("click", function(e) {
e.preventDefault();
$.ajax({
url: "http://url-address.php",
type: "POST",
cache: false,
dataType: "json",
data: $("#loginForm").serialize(),
success: function(result){
if(result.status == "true")
{
alert('Login Successful! ' + result.user);
$.mobile.changePage("#play");
}
else if(result.status=="false")
{
alert('could not login');
}
},
error: function(){
alert('Could not connect!');
}
});
});
return false;
});
});
</script>
</div>
<div data-role="header">
<h1>App Login</h1>
</div>
<div role="main" class="ui-content">
<h4>New account? Sign Up now!</h4><hr>
<form id="loginForm">
<label for="text-basic">Email:</label>
<input type="text" name="email" id="email" value="">
<label for="text-basic">Password:</label>
<input type="password" name="password" id="password" value="">
<br>
<button type="submit" id="loginSubmit">Submit</button>
</form>
<strong>Forgot Password?</strong>
</div>
<div data-role="footer">
</div>
</div>
<!----------------- SECOND PAGE ---------------------->
<div data-role="page" id="plan">
<script>
$(document).on('pagebeforeshow', '#plan' ,function() {
//e.preventDefault();
$('#gamebuttons').empty();
$.ajax({
url: 'http://url-address.php',
dataType: 'json',
Cache: false,
success: function(data) {
$.each(data, function(i,item) {
$('#gamebuttons').append('<button type="button" class="ui-btn ui-btn-inline" name="plannumber" id="gamepanelbutton" value="'+item+'">' + item + '</button>');
});
$('#gamebuttons').refresh();
},
error: function(){
$('#gamebuttons').append('error importing data');
}
});
});
$(document).on("pageshow", "#plan", function(){
$(function(){
$("#playSubmit").on("click", function(e) {
e.preventDefault();
$.ajax({
url: "http://url-address.php",
data: $("#play").serialize(),
type: "POST",
cache: false,
dataType: "json",
data: {"am": am, "rl": rl},
//data: {action: 'login', formData: $('#submitForm').serialize()},
success: function(result){
if(result.status == "true") {
alert(result.message);
//$.mobile.changePage("#play");
} else if(result.status=="false") {
alert(result.message);
}
},
error: function() {
alert('Could not send play request: Error executing request!');
}
});
});
return false;
});
});
</script>
<div data-role="header">
<h1>Main page</h1>
Options
Help
</div>
<div role="main" class="ui-content">
<p>
</p>
<form id="play">
<!---the other form elements go here-->
<p>
<button type="submit" class="ui-btn ui-shadow" id="playSubmit">Play</button>
</p>
</form>
</div>
<div data-role="footer">
</div>
</div>
</body>
</html>
You should clean up your code and take care about indentation. I edited your first post with good indent. You will see that there is a that should not be here in your code, before the <div data-role="header"> of your 1st page:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="jquery.mobile.theme-1.4.3.min.css" />
<link rel="stylesheet" href="jquery.mobile-1.4.3.min.css" />
<script type="text/javascript" src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(document).on("pageinit", function(){
$.mobile.allowCrossDomainPages = true;
$.support.cors = true;
});
</script>
<script type="text/javascript" src="jquery.mobile-1.4.3.min.js"></script>
<script type="text/javascript" src="cordova.js"></script>
</head>
<body>
<div data-role="page" id="login">
<script>
$(document).bind('mobileinit', '#login', function(){
$(function() {
$("#loginSubmit").on("click", function(e) {
e.preventDefault();
$.ajax({
url: "http://url-address.php",
type: "POST",
cache: false,
dataType: "json",
data: $("#loginForm").serialize(),
success: function(result){
if(result.status == "true")
{
alert('Login Successful! ' + result.user);
$.mobile.changePage("#play");
}
else if(result.status=="false")
{
alert('could not login');
}
},
error: function(){
alert('Could not connect!');
}
});
});
return false;
});
});
</script>
<div data-role="header">
<h1>App Login</h1>
</div>
<div role="main" class="ui-content">
<h4>New account? Sign Up now!</h4><hr>
<form id="loginForm">
<label for="text-basic">Email:</label>
<input type="text" name="email" id="email" value="">
<label for="text-basic">Password:</label>
<input type="password" name="password" id="password" value="">
<br>
<button type="submit" id="loginSubmit">Submit</button>
</form>
<strong>Forgot Password?</strong>
</div>
<div data-role="footer">
</div>
</div>
<!----------------- SECOND PAGE ---------------------->
<div data-role="page" id="plan">
<script>
$(document).on('pagebeforeshow', '#plan' ,function() {
//e.preventDefault();
$('#gamebuttons').empty();
$.ajax({
url: 'http://url-address.php',
dataType: 'json',
Cache: false,
success: function(data) {
$.each(data, function(i,item) {
$('#gamebuttons').append('<button type="button" class="ui-btn ui-btn-inline" name="plannumber" id="gamepanelbutton" value="'+item+'">' + item + '</button>');
});
$('#gamebuttons').refresh();
},
error: function(){
$('#gamebuttons').append('error importing data');
}
});
});
$(document).on("pageshow", "#plan", function(){
$(function(){
$("#playSubmit").on("click", function(e) {
e.preventDefault();
$.ajax({
url: "http://url-address.php",
data: $("#play").serialize(),
type: "POST",
cache: false,
dataType: "json",
data: {"am": am, "rl": rl},
//data: {action: 'login', formData: $('#submitForm').serialize()},
success: function(result){
if(result.status == "true") {
alert(result.message);
//$.mobile.changePage("#play");
} else if(result.status=="false") {
alert(result.message);
}
},
error: function() {
alert('Could not send play request: Error executing request!');
}
});
});
return false;
});
});
</script>
<div data-role="header">
<h1>Main page</h1>
Options
Help
</div>
<div role="main" class="ui-content">
<p>
</p>
<form id="play">
<!---the other form elements go here-->
<p>
<button type="submit" class="ui-btn ui-shadow" id="playSubmit">Play</button>
</p>
</form>
</div>
<div data-role="footer">
</div>
</div>
</body>
</html>
For your request problem, have you changed the URL to map the real server mapping?

Ajax call fail when I can trying to pass the special characters as data

This is the code I am using to add a comment using Ajax call.
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile- 1.1.0-rc.1.min.css" />
<script type="text/javascript" charset="utf-8" src="js/cordova-1.5.0.js">
</script>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.0-rc.1/jquery.mobile-1.1.0-rc.1.min.js"></script>
<script src="js/global.js" type="text/javascript"></script>
</head>
<script>
var msgId = window.localStorage.getItem("clickedId");
processLogInData = function(){
var comment = ($("#comment").val());
temp = 'messageId=' + msgId +'&';
temp += 'uniqueId=' + device.uuid + '&';
temp += 'comments=' + comment;
var s= global1 +"rest/Comment/createCommentBO?"+temp;
$.ajax({
url:global1 +"rest/Comment/createCommentBO?",
data: temp,
dataType: 'xml',
timeout: 10000,
async: false,
cache: false,
type: 'POST',
success: function(data){
if($(data).find("isException").text() == "false")
{
//alert('No Exceptions found');
onTrue();
}
else
{
onFalse();
}
},
error:function(XMLHttpRequest,textStatus, errorThrown) {
// alert("Error status :"+textStatus);
// alert("Error type :"+errorThrown);
alert("Error message :"+XMLHttpRequest.responseXML);
$("#messagelist").append( XMLHttpRequest.responseXML);
}
});
}
function onTrue(){
location.replace("comments.html");
}
function onFalse()
{
console.log("onFalse Method");
alert("Unable to create Comment!");
}
function cancel(){
location.replace("comments.html");
}
</script>
<body>
<div data-role="page" data-theme="a">
<div data-theme="a" data-role="header">
<img src="images/logo_header.png" alt="Orange"/>
</div>
<div data-role="content">
<form method="post" name="login" data-ajax="false">
<label for="textarea"><h3><u>Add Comment</u> : </h3></label>
<textarea cols="15" rows="15" name="textarea" id="comment"></textarea>
</form>
<div>
<div class="ui-block-a"><button type="submit" data-theme="d" onclick="cancel();" data-mini="true" data-icon="delete">Cancel</button></div>
<div class="ui-block-b"><button type="submit" data-theme="a" onclick="processLogInData();" data-mini="true" data-icon="check" >Submit</button></div>
</div>
</div>
</div>
</body>
When I enter special character as content as pass it to Ajax call I am getting an error :( Ajax call works fine with out any special characters...
Is there any way to encode the data before passing it to ajax call???Please help me on this...
Thanks in advance.
(1.)Either you should put your data into a form and serialize it and then send to the server
(2.)Second way is you can use the js inbuilt function encodeURIComponent().

Resources