So, basically I am trying to send a request from my ajax post to my node js backend. Then I am trying to get the response back from the node js and update my view. Now, this is something that happens. Instead of just updating the resulttoken in the view, I can see in the console that whole html is loaded like a page. I am really confused. Please kindly point my error. This is what I tried so far.
<!DOCTYPE html>
<html>
<body>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<form id="registerSubmit">
Phonenumber:<br>
<input type="text" name="phonenumber" id="phonenumber">
<br>
Review:<br>
<input type="text" name="review" id="review">
<br><br>
<input type="submit" value="Submit" onclick="gettoken()">
<br>
Token: <%=resulttoken%>;
</form>
<script type="text/javascript">
function gettoken() {
event.preventDefault();
var phonenumber = $("#phonenumber").val();
var review = $("#review").val();
$.ajax({
url: '/home',
data: {
"phonenumber": phonenumber,
"review": review
},
error: function (err) {
console.log("ERROR",err)
},
success: function (info) {
console.log("info",info);
},
type: 'POST',
});
}
</script>
</body>
</html>
server
app.post("/home", function (req, res) {
var s = -1;
var t = -1;
var m = -1;
var phonenumber = req.body.phonenumber;
var review = req.body.review;
console.log(phonenumber);
fd.insertreview(phonenumber,review).then(function(v) {
if(v=="1") {
console.log("Your review has been inserted successfully");
s = md.getRand();
console.log("Unique number is",s);
fd.checkifuniquenumberexists(s).then(function(u){
if(u!="1"){
console.log("Unique number doesnt exist");
fd.inserttoken(s,phonenumber).then(function (p) {
if(p=="1"){
console.log("Token has been inserted successfully");
res.render('trial',{"resulttoken":s});
}
})
}
});
}
});
});
This is what loads on the console log
info <!DOCTYPE html>
<html>
<body>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<form id="registerSubmit">
Phonenumber:<br>
<input type="text" name="phonenumber" id="phonenumber">
<br>
Review:<br>
<input type="text" name="review" id="review">
<br><br>
<input type="submit" value="Submit" onclick="gettoken()">
<br>
Token: 35055;
</form>
<script type="text/javascript">
function gettoken() {
event.preventDefault();
var phonenumber = $("#phonenumber").val();
var review = $("#review").val();
$.ajax({
url: '/home',
data: {
"phonenumber": phonenumber,
"review": review
},
error: function (err) {
console.log("ERROR",err)
},
success: function (info) {
console.log("info",info);
},
type: 'POST',
});
}
</script>
</body>
</html>
The issue is this line
res.render('trial',{"resulttoken":s});
You're returning the entire page as your response, if you just need the token you can return this as part of a JSON response e.g.
res.status(200).json({ token: s });
then at the client
$.post('/home', { phonenumber, review }, res => {
// use res.token
console.log(`Token: ${res.token}`);
})
.fail(console.error);
Related
$(document).ready(function() {
$("#loginForm").on('submit', function() {
var mail = document.getElementById("mail").value;
var password = document.getElementById("password").value;
req = $.ajax({
url: '/api/login',
type: 'POST',
data: {
email: email,
password: password
}
});
req.done(function(data) {
if (data.result == "failed") {
let messageHandler = document.getElementById("message-handler");
messageHandler.innerHTML = `<h3> username or password incorrect </h3>`;
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="POST">
<input type="mail" id="mail" name="mail">
<input type="text" id="password" name="password">
<input type="submit" id="loginForm">
</form>
<div id="message-handler">
</div>
When I click the button, it simply says Method not allowed because I am sending a post request from form. The js never detects the on submit event.
Thanks
What happens here in /api/login? Try to point a file like form.php or something else.
req = $.ajax({
**url: '/api/login',**
type: 'POST',
data: {
email: email,
password: password
}
});
Maybe this is the path you need to follow for your answer ;)
Use action='url' Or action='#' this will help to detect your request in browser.
The following code is working fine when the form is submitted correctly with all valid data in the first attempt. If there is any server side error after submitting the form then when user resubmits the form the recaptcha does not reset.
Following is the sample code:
html-form
<script src="https://www.google.com/recaptcha/api.js"></script>
<div>
<form name="signupForm" method="POST" action="/signup">
<div class="form-group mobile-number">
<input type="tel" id="mobileNo" class="form-control" name="mobileNumber" maxlength="10"
autofocus>
<label for="mobile"> Your Mobile no. </label>
</div>
<div class="g-recaptcha"
data-sitekey="{key}"
data-callback="setResponse"
data-badge="inline"
data-size="invisible">
</div>
<input type="hidden" id="captcha-response" name="captcha-response"/>
<button id="submitButon" type="submit">Sign me up!</button>
</form>
</div>
javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
function setResponse(response) {
document.getElementById('captcha-response').value = response;
submitForm();
}
function submitForm() {
var $form = $("form");
var data = JSON.stringify($form.serializeObject());
var myJsonObject = JSON.parse(data);
data = JSON.stringify(myJsonObject);
$.ajax({
type: "POST",
url: "dummy url",
contentType: "application/json",
xhrFields: {withCredentials: true},
data: data,
success: function (data, textStatus, request) {
// success
},
error: function (xhr, err) {
// logics here
grecaptcha.execute();
setResponse;
}
});
}
</script>
<script>
jQuery(document).ready(function () {
//homepage form
$('form[name="signupForm"]').validate({
onfocusout: function (element) {
$(element).valid();
},
rules: {
mobileNumber: {
required: true,
minlength: 10,
maxlength: 10
}
},
// Specify validation error messages
messages: {
mobileNumber: "A valid mobile number is of 10-digit",
},
//submit handler
submitHandler: function (form) {
submitForm();
}
});
});
</script>
I think the error is in ajax call but not able to figure out why the captcha is not resetting again.
I want to do a POST but I still have a GET on the browser.I'm using node and angular.
This is my HTML with the form.
HTML
<form ng-app="formApp" ng-controller="formCtrl">
nome:<input type="text" ng-model="nome" name="nome"><br>
cognome:<input type="text" name="cognome"><br>
ragioneSociale:<input type="text" name="regioneSociale"><br>
partitaIva:<input type="text" name="partitaIva"><br>
<input type="submit" value="Submit" ng-click="send()">
</form>
angular
this is my angular function:
<script>
var fmApp = angualr.module('formApp', []);
fmApp.controller('formCtrl', function($scope){
$scope.send = function($http){
var data = $.params(){
soggetto: JSON.stringify({
nome: $scope.nome,
cognome: $scope.cognome,
regioneSociale: $scope.regioneSociale,
partitaIva: $scope.partitaIva
});
console.log('ok');
$http({
method: "POST",
url: "/ins/sogg",
data:'data',
dataType: 'json'
}).then(function successCallback(response) {
console.log("sent")
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
// $http.post('/inserimento/soggetto', data).success function(data, status) {
// console.log('status');
})
};
};
});
Your form is submitted without ever touching the $http call, as you don't prevent defaults. Default action of a submit button is to submit the form.
Change
<input type="submit" value="Submit" ng-click="send()">
to
<input type="submit" value="Submit" ng-click="send($event)">
and
fmApp.controller('formCtrl', function($scope){
$scope.send = function($http){
to
fmApp.controller('formCtrl', function($scope, $http){
$scope.send = function(e){
e.preventDefault();
> Solved in this way
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>inserimento Dati</title>
</head>
<body>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<h1>Inserimento</h1>
<h2>Soggetto</h2>
<form ng-app="formApp" ng-controller="formCtrl">
nome:<input type="text" ng-model="nome"/><br>
cognome:<input type="text" ng-model="cognome"/><br>
ragioneSociale:<input type="text" ng-model="ragioneSociale"/><br>
partitaIva:<input type="text" ng-model="partitaIva"/><br>
<input type="button" value="Submit" ng-click="send(nome, cognome, ragioneSociale, partitaIva)"/>
Angular
<script>
var fmApp = angular.module('formApp', []);
fmApp.controller('formCtrl', function($scope, $http){
$scope.nome,
$scope.cognome,
$scope.ragioneSociale,
$scope.partitaIva,
$scope.send = function(nome, cognome, ragioneSociale, partitaIva){
var data = {
"nome": nome,
"cognome": cognome,
"ragioneSociale": ragioneSociale,
"partitaIva": partitaIva,
}; // fine JSON
var str = JSON.stringify(data);
console.log(data);
$http({
method: "POST",
url: "/ins/sogg",
data: data,
}).then(
function successCallback(response){
console.log("sent")},
function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
// $http.post('/inserimento/soggetto', data).success function(data, status) {
// console.log('status');
};
});
</script>
Server.js
app.get('/inserimento', function(req, res){
res.sendFile(__dirname + '/public/inserimento.html');
});
app.post('/ins/sogg', function(req, res){
var sog = req.body; //arriva il dato
app.use(bodyParser.json(sog));//dato in json ordinato
console.log(sog);
client.connect(function (err){
if (err) throw err;
});
var query = client.query('INSERT INTO "Soggetto" (nome, cognome, "regSociale", "partIVA") VALUES($1, $2, $3, $4)', [sog.nome, sog.cognome, sog.ragioneSociale, sog.partitaIva], function(err, result){
if(err){
console.log("Errore");
return onError(err);
}
res.writeHead(200, {'content-type': 'text/plain'});
res.end('Insert ok');
});
});
I am trying to call data from a PHP file where it takes the data entered and tells if it is validated or not. How do you do this in the javascript file using an AJAX call?
$("#PersonForm").submit(function()
{
$.ajax({
url: 'backend.php', type: 'post', data: { act:'validate'},
dataType: 'json',
function(result) {
if($validateData==1){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
}
//});
});
return false;
});
Here is the PHP file
<?php
if ($_REQUEST['act'] == 'validate')
{
$validateData = array();
if (preg_match("/^[A-Za-z]{3,20}$/",$_REQUEST['name'])) $validateData['name'] = 1;
else $validateData['name'] = 0;
if (preg_match("/^[0-9]{10}$/",$_REQUEST['phone'])) $validateData['phone'] = 1;
else $validateData['phone'] = 0;
if (preg_match("/^[A-Z][0-9][A-Z][0-9][A-Z][0-9]$/",
$_REQUEST['postal'])) $validateData['postal'] = 1;
else $validateData['postal'] = 0;
if (preg_match("/^[0-9]{3} [A-Za-z]{3,10} Street$/",
$_REQUEST['address'])) $validateData['address'] = 1;
else $validateData['address'] = 0;
echo json_encode($validateData);
}
else echo "Should not happen";
?>
HTML file:
<html>
<body>
<h1>Form Validation</h1>
<form id="PersonForm">
Name: <input type="text" id="name" name="name"> <br>
Postal Code: <input type="text" id="postal" name="postal"> <br>
Phone Number: <input type="text" id="phone" name="phone"> <br>
Address: <input type="text" id="address" name="address"> <br>
<input id="sub" type="submit">
</form>
Refresh
<a id="InsertDefault" href="">Insert Default Data</a>
<br>
<ul id="errors"></ul>
<p id="success"></p>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</html>
First, you're not sending the any of the inputs in your data: parameter. So $_REQUEST['name'], $_REQUEST['phone'], etc. won't exist.
Second, you can't access PHP variables in Javascript. The JSON that the PHP echoes at the end will be decoded into the result variable in the success: callback function.
Third, your syntax is wrong, the callback function needs to be in the success: option.
So it should be:
$("#PersonForm").submit(function()
{
$.ajax({
url: 'backend.php',
type: 'post',
data: 'act=validate&' + $(this).serialize(),
dataType: 'json',
success: function(result) {
if(result.name && result.phone && result.post && result.address){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
}
});
return false;
});
You should use the success and error callbacks so that you are waiting for the promise from the ajax call to come back. I am assuming you are trying to figure out how to get to the data that comes back. If you need further assistance with then validating the real data, I can help with that as well.
$.ajax({
url: 'backend.php', type: 'post', data: { act:'validate'},
dataType: 'json',
success: function (data) {
if($validateData==1){
$('#success').html('validated');
}
else{
$('#errors').html('Not Correct');
}
},
error: function (request, status, error) {
// Error occurred calling API
}
});
<html>
<body>
<form method="POST">
<label>username</lable>
<input id="username" name="username" type="text">
<label>emailid</lable>
<input id="emailid" name="emailid" type="text">
<button id="enter" type="submit">submit</button>
</form>
<script type="text/javascript">
$(document).ready(function () {
var userName = $("#username").val();
var emailId = $("#emailid").val();
$($enter).click(function () {
$.ajax({
type: 'POST',
url: ".....rest service url....",
dataType: JSON,
data: {
"UserName": userName,
"EmailId": emailId
},
success: function (data) {
alert("success");
}
error: function (e) {
alert("error" + e)
}
});
});
});
</script>
</body>
</html>
I'm trying to post the form field in rest service which expects a JSON response.
I'm getting an alert error message (object Object)
I'm not getting where the error is.
You can try $.post instead of $.ajax
$.post( "your url",{ UserName: userName, EmailId: emailId }, function( data ){
alert("Success");
});
Just make sure that parameters you are passing matches with your REST service.
$($enter).click(function () {
this part of code looks invalid, provide a correct selector to the click function.
First change this
$($enter).click(function to
$("#enter").click(function () {
Are you sure the the service you written for this task is a post service...some times i do the mistake like post data and write service for getting data.If you can show your service structure it will help to have a better insight.