<form method="POST" class="userform" id="loginForm">
<div data-role="content">
<h2> Login:</h2>
<div data-role="fieldcontain">
<input name="email" placeholder="put your name" type="email" data-mini="true">
</div>
<div data-role="fieldcontain">
<input name="password" placeholder="enter your password" type="password" data-mini="true">
</div>
<input type="submit" data-theme="a" value="submit" id="submitButton">
<h5 align="center">
Forget password?
</h5>
</div>
</form>
this is my login.js
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
var $bro = $('#loginForm');
$('#submitButton').click(function(e) {
//console.log("submit button has been clicked");
e.preventDefault(); //cancel form submit
var jsObj = $bro.serializeObject()
, ajaxObj = {};
//console.log(jsObj);
ajaxObj = {
type: "POST",
url: "http://192.168.0.100:8080/AdvancedLibrarySystem/api/v1/login",
data: JSON.stringify(jsObj),
contentType:"application/json",
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error " + jqXHR.getAllResponseHeaders() + " " + errorThrown);
},
success: function(data) {
console.log(data);
if(data[0].status == '200') {
alert("Welcome!!!")
$('#div_ajaxResponse').text( data[0] );
$.mobile.changePage('home.html');
}
else{
alert("Incorret Username or Password!!!")
}
},
complete: function(XMLHttpRequest) {
//console.log( XMLHttpRequest.getAllResponseHeaders() );
},
dataType: "json" //request JSON
};
$.ajax(ajaxObj);
});
I'm trying to use an authentification in phonegap via ajax but if i'm trying to run that code in chrome console it works fine but when i'm using it in my phonegap application it's not giving response in the server... Anyone can help me out please...
I am not sure what you mean by 'not giving response in the server', but one thing worth checking out is the cross-domain options in the config.xml of your phonegap project. There should be an "access" tag in there that specifies what domains can be accessed. Try setting it to "*" and try again.
Related
I am trying to do a form validation function with Ajax submission. For some reason the validation doesn't work and when it submits, my server gets the empty fields (when I am testing for the validation) but it shows that it tried to post to the same page... I don't know why.
Form:
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">
<form id='form' novalidate method="post" class='m-2 p-1'>
<div class='row'>
<div class='col p-1'>
<div class="form-floating mb-3">
<input required type="text" name='First Name' class="form-control" id="fname" placeholder="First Name">
<label for="fname">First Name<span class='red' aria-label='required'> *</span></label>
</div>
</div>
<div class='col p-1'>
<div class="form-floating mb-3">
<input required type="text" name='Last Name' class="form-control" id="lname" placeholder="Last Name">
<label for="lname">Last Name</label>
</div>
</div>
</div>
<div class='row'>
<div class='col p-1'>
<div class="form-floating mb-3">
<input required type="email" name='Email' class="form-control" id="email" placeholder="Email">
<label for="lname">Email <span class='red' aria-label='required'> *</span></label>
</div>
</div>
<div class='col p-1'>
<div class="form-floating mb-3">
<select required name='Reason For Contacting' class="form-control" id="reason" placeholder="Reason For Contacting">
<option value='Feedback' selected>Feedback</option>
<option value='other'>Other</option>
</select>
<label for="why">Reason For Contacting<span class='red' aria-label='required'> *</span></label>
</div>
</div>
</div>
<div class='row'>
<div class='col p-1'>
<div class="form-floating mb-3">
<textarea required name='Comments' class="form-control" id="comment" placeholder="Your Comments"></textarea>
<label for="comment">Your Comments<span class='red' aria-label='required'> *</span></label>
</div>
</div>
</div>
<div class='row'>
<div class='col p-1'>
<button class='form-control btn btn-outline-primary' id='submit'>Send</button>
</div>
</div>
</form>
My JS File:
$(document).ready(() => {
autosize($('textarea'))
$('#submit').click((e) => {
if (validate() == true) {
sendForm();
} else {
error(validate())
}
})
})
var errors;
window.onerror = function(msg, url, linenumber) {
alert('Error message: ' + msg + '\nURL: ' + url + '\nLine Number: ' + linenumber);
return true;
}
function validate() {
elements = $(':input')
elements.each((element) => {
element = $(element).get()
if (element.value === '' || !email(element)) {
errors += element.name + " is invalid."
} else {
return;
}
})
if (errors) {
return errors
} else true;
}
function sendForm() {
name = $('input[name="First Name"]').val().trim() + " " + $('input[name="Last Name"]').val().trim()
email = $('input[name="Email"]').val().trim()
why = $("select").val().trim()
comments = $('textarea').val().trim()
data = {
"name": name,
"email": email,
"reason": why,
"text": comments
}
$.ajax({
type: 'POST',
url: 'https://admin.bekesbikes.tk/contact',
crossDomain: true,
data: data,
dataType: 'json',
success: (responseData, textStatus, errorThrown) => {
new Notify({
title: 'Submitted!',
text: 'Your feedback has been recorded!\n\nWe will get back to your email shortly!\n\nHope to see you soon!',
effect: 'slide',
status: 'success',
speed: 1000,
autoclose: true
})
$(':input').val('');
$('select').val('Feedback')
},
error: (responseData, textStatus, errorThrown) => {
new Notify({
title: 'Could not submit!',
text: 'The form could not be submitted.\n\nPlease try again or come back later!\n\nSorry for the inconvenience.',
effect: 'slide',
customIcon: "<img src='https://www.flaticon.com/svg/vstatic/svg/753/753345.svg?token=exp=1616679486~hmac=4f66bb69b263e9e4d9be5038a16cc41d' width='50px'>",
status: 'error',
speed: 1000,
autoclose: true
})
}
});
}
function error(text) {
new Notify({
title: 'Form Fields Are Not Correct',
text: text,
effect: 'slide',
status: 'info',
speed: 1000,
autoclose: true
})
}
function send() {
if (validate()) {
sendForm()
} else {
error(validate())
}
}
function email(element) {
if (element.type === 'email' && /^[^\s#]+#[^\s#]+$/.text(element.value)) {
return true;
} else if (element.type !== 'email') {
return true;
} else {
return false;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Where I go when I submit (the form is at this URL):
Any Idea what I should do? I am using node.js with express.js.
I added: e.preventDefault() to my submit event handler but now when I submit the form without filling in anything, I get this notification:
I changed your click handler:
default prevention,
validate() as variable so that it runs only once,
the errors declaration
empty string instead of undefined,
your validate() function
excluded button using :not(),
changed arrow function to ordinary anonymous function,
used this instead of element, which was only an index,
added a return to the last else,
and your email() function
sourced the email validation out to an own function.
I also deleted send(), as it was not used, declared the variables in sendForm() with var and added many semicolons -> maybe in your code one is already missing and you are hoping that the js error correction will add them automatically...
Finally i added the param showIcon to your Notify objects (that was the 'undefined' part ;)
$(document).ready(() => {
autosize($('textarea'))
$('#form').submit((e) => {
e.preventDefault();
var validated = validate();
if (validated == true) {
sendForm();
} else error(validated);
});
var errors = '';
window.onerror = function(msg, url, linenumber) {
alert('Error message: ' + msg + '\nURL: ' + url + '\nLine Number: ' + linenumber);
return true;
}
function validate() {
elements = $(':input:not(button)');
elements.each(function() {
if (this.value === '' || !email(this)) {
errors += this.name + " is invalid.";
} else return;
});
if (errors) {
return errors;
} else return true;
}
function sendForm() {
var name = $('input[name="First Name"]').val().trim() + " " + $('input[name="Last Name"]').val().trim();
var email = $('input[name="Email"]').val().trim();
var why = $("select").val().trim();
var comments = $('textarea').val().trim();
var data = {
"name": name,
"email": email,
"reason": why,
"text": comments
};
$.ajax({
type: 'POST',
url: 'https://admin.bekesbikes.tk/contact',
crossDomain: true,
data: data,
dataType: 'json',
success: (responseData, textStatus, jqXHR) => {
new Notify({
title: 'Submitted!',
text: 'Your feedback has been recorded!\n\nWe will get back to your email shortly!\n\nHope to see you soon!',
effect: 'slide',
status: 'success',
speed: 1000,
autoclose: true,
showIcon: false
});
$(':input').val('');
$('select').val('Feedback');
},
error: (jqXHR, textStatus, errorThrown) => {
new Notify({
title: 'Could not submit!',
text: 'The form could not be submitted.\n\nPlease try again or come back later!\n\nSorry for the inconvenience.',
effect: 'slide',
customIcon: "<img src='https://www.flaticon.com/svg/vstatic/svg/753/753345.svg?token=exp=1616679486~hmac=4f66bb69b263e9e4d9be5038a16cc41d' width='50px'>",
status: 'error',
speed: 1000,
autoclose: true,
showIcon: true
});
}
});
}
function error(text) {
new Notify({
title: 'Form Fields Are Not Correct',
text: text,
effect: 'slide',
status: 'info',
speed: 1000,
autoclose: true,
showIcon: false
})
}
function validateEmail(email) {
const re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function email(element) {
if (element.type === 'email' && validateEmail(element.value)) {
return true;
} else if (element.type !== 'email') {
return true;
} else return false;
}
});
I am developing a process which involves multiple forms. The idea is that whenever you click the send button of any form, after checking all the inputs have been filled, my js will hide the already completed form in order to show the new one.
The issue is that whenever I click send, the request launches six times inserting the same data over and over. There is no loop involved in the code, so my guess is that this has something to do with this listener:
contactForm.addEventListener('submit', function(event) {
located here:
var validation = Array.prototype.filter.call(contactForm, function(form) {
contactForm.addEventListener('submit', function(event) {
if (contactForm.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
I am not sure however, since I've later tried to make some changes to no avail.
In any case, this is the code I started with:
(function() {
'use strict';
window.addEventListener('load', function() {
var contactForm = document.getElementById('contactForm');
var customerForm = document.getElementById('customerForm');
var validation = Array.prototype.filter.call(contactForm, function(form) {
contactForm.addEventListener('submit', function(event) {
if (contactForm.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
contactForm.classList.add('was-validated');
if (contactForm.checkValidity() === true) {
customerForm.style.display = 'block';
contactForm.style.display = 'none';
event.preventDefault();
(function() {
var contactEmail = document.getElementById('contactEmail').value;
var contactResellerId = 2;
var contactName = document.getElementById('contactName').value;
var contactLastName = document.getElementById('contactLastName').value;
var contactCompany = document.getElementById('contactCompany').value;
var contactRegNum = document.getElementById('contactRegNum').value;
$.ajax({
url: url,
method: 'POST',
crossDomain: true,
withCredentials: true,
data: JSON.stringify({
firstname: contactName,
lastname: contactLastName,
company: contactCompany,
email: contactEmail,
reseller_id: contactResellerId,
comregnum: contactRegNum
}),
dataType: 'json',
contentType: 'application/json',
headers: {
'Authorization': 'Basic '+token,
}
})
.done(function (response) { alert('Se ha creado el contacto!'); })
.fail(function (jqXHR, textStatus, errorThrown) { alert(jqXHR); });
})();
}
}, false);
});
}, false);
})();
And this is what I have right now:
(function() {
'use strict';
window.addEventListener('load', function() {
var contactForm = document.getElementById('contactForm');
var customerForm = document.getElementById('customerForm');
var submitContact = document.getElementById('submitContact');
var validation = Array.prototype.filter.call(contactForm, function(form) {
submitContact.addEventListener('click', function(event) {
if (contactForm.checkValidity() === false) {
event.preventDefault();
event.stopPropagation();
}
contactForm.classList.add('was-validated');
if (contactForm.checkValidity() === true) {
event.preventDefault();
customerForm.style.display = 'block';
contactForm.style.display = 'none';
(function() {
var contactEmail = document.getElementById('contactEmail').value;
var contactResellerId = 2;
var contactName = document.getElementById('contactName').value;
var contactLastName = document.getElementById('contactLastName').value;
var contactCompany = document.getElementById('contactCompany').value;
var contactRegNum = document.getElementById('contactRegNum').value;
$.ajax({
url: url,
method: 'POST',
crossDomain: true,
withCredentials: true,
data: JSON.stringify({
firstname: contactName,
lastname: contactLastName,
company: contactCompany,
email: contactEmail,
reseller_id: contactResellerId,
comregnum: contactRegNum
}),
dataType: 'json',
contentType: 'application/json',
headers: {
'Authorization': 'Basic '+token,
}
})
.done(function (response) { alert('Se ha creado el contacto!'); })
.fail(function (jqXHR, textStatus, errorThrown) { console.log(jqXHR); });
})();
}
}, false);
});
}, false);
})();
This is the form this is getting the info from:
<form class="needs-validation provisioningForm" id="contactForm" novalidate>
<h2 class="title">Crear Contacto</h2>
<div class="form-row">
<div class="col-md-12 mb-3">
<label for="contactName">Nombre</label>
<input type="text" class="form-control" id="contactName" required>
<div class="invalid-feedback">
Debes introducir el nombre del contacto.
</div>
</div>
<div class="col-md-12 mb-3">
<label for="contactLastName">Apellidos</label>
<input type="text" class="form-control" id="contactLastName" required>
<div class="invalid-feedback">
Debes introducir los apellidos del contacto.
</div>
</div>
</div>
<div class="form-row">
<div class="col-md-12 mb-4">
<label for="contactEmail">Email</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroupPrepend">#</span>
</div>
<input type="text" class="form-control" id="contactEmail" aria-describedby="inputGroupPrepend" required>
<div class="invalid-feedback">
Debes introducir un correo vĂ¡lido.
</div>
</div>
</div>
<div class="col-md-12 mb-3">
<label for="contactCompany">Empresa</label>
<input type="text" class="form-control" id="contactCompany" required>
<div class="invalid-feedback">
Debes introducir el nombre de la empresa.
</div>
</div>
<div class="col-md-12 mb-3">
<label for="contactRegNum">C.I.F.</label>
<input type="text" class="form-control" id="contactRegNum" required>
<div class="invalid-feedback">
Debes incluir el CIF de la empresa.
</div>
</div>
</div>
<button id="submitContact" class="btn btn-success" type="submit">Enviar</button>
</form>
A few notes:
Everything is working fine. There are no warnings/errors displayed on console. The issue lies in the fact that the POST request is executing 6 times.
There are 5 forms with 5 submit buttons and a total of 5 functions. All have different id's. As I was saying in the beginning, I believe the cause to be the event listener placed on the 'submit'. I think that since the other forms are just hidden, but there, it may be taking the other submits. But after trying to store them in separate variables and to place a .click listener on them and still get the same result I am even more confused.
If you need any extra info I'll post it right away. Thank you all for your time and help.
It looks like you may be adding multiple "submit" events as you surmised. This line appears to be unnecessary:
var validation = Array.prototype.filter.call(contactForm, function(form) {
If you remove it (and the closing }), your submit event should be added only once, on window.load.
I'm working on a simple CRUD application where I have a sign in, sign up, and account section for the user. Once the user signs in, then clicks account, there is the option to edit and save your changes. You'll notice I have "here is where you want to change the disable to true" and "here is where you will update the user information in the database". This is where I am supposed to implement the code. How do I actually get those edit and save buttons to work through javascript? Here is my code:
HTML:
<nav>
<div>HOME</div>
<div>ABOUT</div>
<div>SPEAKERS</div>
<div>INFO</div>
<div class="join-button">
JOIN IN
<div class="join-holder">
<div class="sign-in">
<form>
<h2>Sign In</h2>
<label>User Name:</label>
<input id="username" type="text" value="name#name.com">
<label>Password:</label>
<input id="siPW" type="password" value="12345678">
<input class="submit-button si-submit" type="submit">
</form>
</div>
<div class="sign-up">
<form>
<h2>Sign Up</h2>
<label>Name:</label>
<input id="fullName" type="text" value="name">
<label>Email:</label>
<input id="email" type="email" value="name#name.com">
<label>Password:</label>
<input id="pw" type="password" value="12345678">
<input class="submit-button su-submit" type="submit">
</form>
</div>
</div>
</div>
<div class="account">Account</div>
<div class="signOut">Sign Out</div>
</nav>
<div class="home">
Home
</div>
JS:
function setBindings() {
$(".account").click(function (e) {
var ui = DATA.getUserInfo();
if($.isEmptyObject(ui)){
swal("Oops...", "You need to sign in!", "error");
}else{
$(".home").html('<label>Name:</label><input disabled="true" id="userFullName" value="' + ui.fullName +'" type="text"><button class="edit">Edit</button><button class="save">Save</button>');
$(".edit").click(function (e) {
//here is where you want to change the disable to true
});
$(".save").click(function (e) {
//here is where you will update the user information in the database
})
}
});
$(".signOut").click(function (e) {
DATA.signOut();
});
$(".su-submit").click(function (e) {
e.preventDefault();
var fullName = $("#fullName").val(),
email = $("#email").val(),
pw = $("#pw").val(),
cpw = $("#cPw").val();
if(fullName == ""){
swal("Oops...", "You need a name!", "error");
}else if(!validateEmail(email)){
swal("Oops...", "Your email is not valid!", "error");
}else if(pw == "" || pw.length < 8){
swal("Oops...", "Your password needs to be longer than 8!", "error");
}else if(cpw == "" || cpw.length < 8 || pw != cpw){
swal("Oops...", "Your passwords don't match!", "error");
}else{
var info = {
"fullName": fullName,
"email": email,
"password": pw
};
DATA.addUser(info, addedUser);
// swal("Congrats", "You are signed up!", "success");
}
});
$(".si-submit").click(function (e) {
e.preventDefault();
var username = $("#username").val(),
pw = $("#siPW").val();
if(username == "" || validateEmail(username) == false){
swal("Oops...", "You need a username!", "error");
}else if(pw == "" || pw.length < 8){
swal("Oops...", "Your password needs to be longer than 8!", "error");
}else{
DATA.checkUser(username, pw, userSignIn);
}
});
}
function addedUser(data) {
console.log("data " , data);
}
function userSignIn(data) {
console.log(data.fullName);
swal("Congrats", data .fullName + " You are signed in!", "success");
};
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
$(document).ready(function () {
setBindings();
});
Data JS:
var userLoggedIn = {};
var _checkUser = function (username, password, callback) {
$.ajax({
url: _baseQueryURL + 'q={"email":"' + username + '","password":"' + password +'"}' + _queryApiKey,
type: "GET",
contentType: "application/json"
}).done(function (data) {
userLoggedIn = data[0];
callback(data[0]);
}).fail(function (error) {
console.log("error " + error);
});
};
var _addUser = function (userInfo, callback) {
console.log(userInfo.email + ' ' + userInfo.password);
$.ajax({
url: _baseQueryURL + 'q={"email":"' + userInfo.email + '","password":"' + userInfo.password +'"}&c=true' + _queryApiKey,
type: "GET",
contentType: "application/json"
}).done(function (data) {
if(data == 0){
$.ajax({
url: _baseURL + _apiKey,
data: JSON.stringify( userInfo ),
type: "POST",
contentType: "application/json"
}).done(function (data) {
userLoggedIn = data;
callback(data);
}).fail(function (error) {
swal("Oops...", "You have an error!", "error");
});
}else if(data == 1){
swal("Oops...", "You are already signed up. Please Sign in!", "error");
}
}).fail(function (error) {
console.log("error " + error);
});
};
var _signOut = function () {
userLoggedIn = {};
};
var _getUserInfo = function () {
return userLoggedIn;
};
return {
checkUser: _checkUser,
addUser: _addUser,
signOut: _signOut,
getUserInfo: _getUserInfo
}
})();
I submit a form data using $.ajax() method, data contains image files.
while submitting I encountered with below issues:
form is not getting submitted in IE10,11
though it is submitting in chrome and FF, ajax() executing both success and error methods
I am able to submit the data in chrome and FF but it is displaying only error message
data is submitted to DB from Chrome and FF
Below is the code I am using to submit the data
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('form').submit(function() {
var senddata = JSON.stringify($('form').serializeObject());
$('#result').text(senddata);
var form_data = new FormData($(this)[0]);
form_data.append('jsonString', senddata);
var settings = {
"async": true,
"crossDomain": true,
"url": "google.com",//sample url
"method": "POST",
"processData": false,
"contentType": false,
"headers": {
"Access-Control-Allow-Origin": "*",
"cache-control": "no-cache"
},
"mimeType": "multipart/form-data",
"cache": false,
"data": form_data//,
//"dataType": "jsonp"
};
$.ajax(settings).done(function (data) {
console.log(data);
})
.success(function (data) {
alert("submitted");
})
.error(function (data){
alert("failed");
console.log(data);
});
return false;
});
});
<!-- language: lang-html -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="">
<input type="hidden" name="profileTypeId" value="112" maxlength="36" size="12"/>
First Name:<input type="text" name="firstName" value="Hydtest" maxlength="12" size="12"/> <br/>
Last Name:<input type="text" name="lastName" value="3SparrowTest" maxlength="36" size="12"/> <br/>
email:<input type="text" name="emailId" value="jackSparrow#testmail.com" maxlength="36" size="12"/> <br/>
Address1:<input type="text" name="address1" value="PiratesTest" maxlength="36" size="12"/> <br/>
<input type="hidden" name="address2" value="PiratesTest" maxlength="36" size="12"/>
<input type="hidden" name="city" value="caribbean" maxlength="36" size="12"/>
Profile Image: <input name="file" type="file" /><br />
<p><input type="submit" /></p>
</form>
<!-- end snippet -->
I think the form is not submitting because of images. Could you try base64 encoding the images before submitting them to the server.
Here is a reference to base64 encode images using javascript:
https://davidwalsh.name/convert-image-data-uri-javascript
The AJAX post works when passing the predefined data as follow:
//var data = {"name" : "Testing", "email" : "testing#gmail.com", "cpf" : "9876543210"};
But I am unable to pass the data dynamically from the form.
Please help me figure this out.
POST function
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$("#post").click(function() {
$("#dataIn").text(JSON.stringify($("form").serializeObject()));
$(function() {
//var data = {"name" : "Testing", "email" : "testing#gmail.com", "cpf" : "9876543210"};
var data = ("#dataIn");
$.ajax({
type: "POST",
url: "http://myhost:8080/mypath-rs/rest/beneficiaries",
//data: JSON.stringify(data),
contentType: "application/json",
});
});
});
});
The Form
<form action="" method="post" class="form-inline">
<label class="sr-only">Name</label>
<input type="text" name="name" class="form-control" id="name" placeholder="Name">
<label class="sr-only">Email</label>
<input type="text" name="email" class="form-control" id="email" placeholder="Email">
<label class="sr-only">CPF</label>
<input type="text" name="cpf" class="form-control" id="cpf" placeholder="CPF">
<button id="post" type="submit" type="button">Add </button>
</form>
<p >Json Result</p>
<pre id="dataIn" ></pre>
I am not sure if I have to serialize the form or if the JSON.stringify(data) can already do this.
Below code works perfectly:
Non dynamically, But working
$("#post1").click(function(){
var data = {"name" : "Testing", "email" : "testing#gmail.com", "cpf" : "9876543210"};
$.ajax({
type: "POST",
url: "http://myhost:8080/mypath-rs/rest/beneficiaries",
data: JSON.stringify(data),
contentType: "application/json",
});
console.log("Loaded");
});
Thank you.
The best solution I could think of at the moment:
$(function() {
$("#post").click(function() {
var data = JSON.stringify($("form").serializeObject());
$("#dataIn").text(data);
$(function() {
$.ajax({
type: "POST",
url: "http://myhost:8080/mypath-rs/rest/beneficiaries",
data: data,
contentType: "application/json",
});
});
});
});
You don't need to use JSON.stringify() twice, because you already did it on .serializeObject() returned value. Next you print it to your #dataIn container and send it via ajax request.
You can try this https://jsfiddle.net/sjc79b55/2/
Please update <button id="post" type="button">Add </button> line also
<form action="" method="post" class="form-inline">
<label class="sr-only">Name</label>
<input type="text" name="name" class="form-control" id="name" placeholder="Name">
<label class="sr-only">Email</label>
<input type="text" name="email" class="form-control" id="email" placeholder="Email">
<label class="sr-only">CPF</label>
<input type="text" name="cpf" class="form-control" id="cpf" placeholder="CPF">
<button id="post" type="button">Add </button>
</form>
<p >Json Result</p>
<pre id="dataIn" ></pre>
JS.......
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$("#post").click(function() {
var jsonData = JSON.stringify($(".form-inline").serializeObject());
$("#dataIn").text(jsonData);
$(function() {
//var data = {"name" : "Testing", "email" : "testing#gmail.com", "cpf" : "9876543210"};
// var data = $("#dataIn").text();
//alert(jsonData);
$.ajax({
type: "POST",
url: "http://myhost:8080/mypath-rs/rest/beneficiaries",
data: jsonData,
contentType: "application/json",
});
});
});
});