Fetching records from a form with ajax to insert into mysql with node.js but only the first column works. The rest of the columns do not insert. Below is my code. What am I doing wrong? Thanks
Ajax
$(document).ready(function (e) {
$("#new-user-form").on('submit',(function(e) {
e.preventDefault();
var data = {};
data.title = $('#title').val();
data.fname = $('#fname').val();
data.mname = $('#mname').val();
data.lname = $('#lname').val();
data.mdname = $('#mdname').val();
$('#loading').show();
//toastr.success('Page Loaded!');
$.ajax({
url: "/new-user",
type: "POST",
data: data,
dataType: 'application/json',
cache: false,
success: function(data)
{
console.log('working');
$('#loading').hide();
}
});
}));
});
new-user.js
var express = require('express'),
router = express.Router(),
db = require('./../db');
router.post('/', function (req,res,next) {
var title = req.body.title;
var first_name = req.body.fname;
var middle_name = req.body.mname;
var last_name = req.body.lname;
var maiden_name = req.body.mdname;
db.insert({first_name:first_name},{last_name:last_name}).into('users').then(function(data){
//res.send(data);
})
});
Do you use https://github.com/felixge/node-mysql?
Try pass the object as one:
db.insert({first_name:first_name, last_name:last_name})
Insted of
db.insert({first_name:first_name},{last_name:last_name})
Related
I'm dealing with the project where I need to collect data from user and display on the same page. I've successfully completed the Ajax call using JavaScript, but now I want using Jquery.
This is my JavaScript Code:
var output1 = document.getElementById("output1");
function saveUserInfo() {
var userName = document.getElementById('username').value;
var password = document.getElementById('password').value;
var firstName = document.getElementById('firstname').value;
var lastName = document.getElementById('lastname').value;
var email = document.getElementById('email').value;
var dob = document.getElementById('datepicker').value;
var vars = "username=" + userName + "&password=" + password + "&firstname=" + firstName + "&lastname=" + lastName + "&email=" + email + "&datepicker=" + dob;
var ajax = new XMLHttpRequest();
var url = 'register.jsp';
ajax.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
output1.innerHTML = (ajax.responseText);
}
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax.send(vars);
}
This is my register.jsp :
<%# page import ="java.sql.*" %>
<%# page import ="javax.sql.*" %>
<%
String user = request.getParameter("username");
session.putValue("username",user);
String pwd = request.getParameter("password");
String fname = request.getParameter("firstname");
String lname = request.getParameter("lastname");
String email = request.getParameter("email");
String dob = request.getParameter("dob");
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/user_info2","root","root");
Statement st = con.createStatement();
ResultSet rs;
//int i=st.executeUpdate("insert into user_info value('"+user+"','"+pwd+"','"+fname+"','"+lname+"','"+email+"')");
int i=st.executeUpdate("INSERT INTO `users`(user,pwd,fname,lname,email,dob) VALUE ('"+user+"','"+pwd+"','"+fname+"','"+lname+"','"+email+"','"+dob+"')");
%>
Registration is Successfull. Welcome <%=user %>,
Your Password is : <%=pwd %>,
FirstName : <%=fname %>,
LastName : <%=lname %>,
Email : <%=email %>,
and Date Of Birth is : <%=dob %>,
This is a generalized view of a jQuery ajax request.
$.ajax({
url: 'register.jsp',
type: 'POST',
data : {userName : userName,password: password,....},
contentType: 'yourConentType', // ConentType that your are sending. No contentType needed if you just posting as query string parameters.
success: function(response){
// do whatever you want with response
},
error: function(error){
console.log(error)
}
});
If you want to pass your values as object then as follows:
var formData = {userName : userName, password: password,...};
$.ajax({
url: 'register.jsp',
type: 'POST',
data : JSON.stringify(formData),
contentType: 'application/json',
success: function(response){
// do whatever you want with response
},
error: function(error){
console.log(error)
}
});
For more details: jQuery.ajax()
function saveUserInfo() {
var postData = {
username: $('#userName').val(),
password: $('#firstname').val(),
firstName: $('#ss_unit').val(),
lastName: $('#lastname').val(),
email: $('#email').val(),
dob: $('#datepicker').val()
};
$.post(url, postData).done(function(data) {
output1.innerHTML = data;
});
}
$.ajax({
type: "POST",
url: url,
data: data,
dataType: dataType
}).done(function(){
}).fail(function(){
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can use jQuery's $.post method with .fail and .done. Then you can also use query's selectors to get the values from all your inputs.
Something like the following:
var output1 = $("#output1");
function saveUserInfo() {
var userName = $('#username').val();
var password = $('#password').val();
var firstName = $('#firstname').val();
var lastName = $('#lastname').val();
var email = $('#email').val();
var dob = $('#datepicker').val();
var data = {userName, passWord, firstName, lastName, email, dob};
var url = 'register.jsp';
$.post(url, data)
.done(function(msg) { /* yay it worked */ });
.fail(function(xhr, status, err) {
output1.text(err);
});
}
I also noticed that you are getting many input fields in your code. If all these input fields are located in a form (for instance with the id of formId, you can use $('#formId').serialize() to create the vars string for you. You can read more about .serialize() here.
You can use ajax call of jquery by using following syntax.
Add this on head section of your page for jquery reference.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
For JS:
function saveUserInfo() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "...", // your api or url for fetching data
data: "..", // your data coming from front end in json
dataType: "json",
success: function (data) {
// your action need to perform
},
error: function (result) {
// handle error
}
});
}
However it is not recommended to make your connection or database related information provide on client side. For fetching data from backend it is recommended to make an API or web service for that.
You can use following links for references.
WebService: https://www.c-sharpcorner.com/UploadFile/00a8b7/web-service/
WebAPI: https://www.tutorialsteacher.com/webapi/create-web-api-project
Note: These both are for C# backend. Please mention your language name if anything else you are using.
It is the jQuery syntax of your code
function saveUserInfo() {
var userName = $('username').val();
var password = $('password').val;
var firstName = $('firstname').val;
var lastName = $('lastname').val;
var email =$('email').val;
var dob = $('datepicker').val;
var vars = {'userName':userName ,'password':password ,'firstName':firstName ,'lastName':firstName ,'email':email ,'datepicker':dob }
$.ajax(
{
url:'register.jsp',
data:vars ,
type:'POST'
dataType : "json",
contentType: "application/json; charset=utf-8",
success:function(result)
{
code to use result here
}
});
}
I have been developing an app to connect with an API I recently built for testing (It is working fine) but I deem to be getting an unknown error with my code. I am a newbie trying out jQuery. This is my code:
$(document).ready(function(){
$.ajax({
url: 'api.lynmerc-enterprise.com/requests',
async: false,
type: 'GET',
//dataType: 'json',
success: function(data){
console.log(data);
var data2 = jQuery.parseJSON(data);
console.log(data2);
//assign parsed JSON to variables
var apiStatus = data2.status;
var apiMessage= data2.message;
var apiData = data2.data;
var data3 = $.parseJSON(apiData);
//Here we get Requester info and material JSON
console.log(data3);
var materials = data3.material;
var data4 = $.parseJSON(materials);
console.log(data4);
//loop through the data and assign needed info to table
$.each(data3, function(i,row){
var dateRequested = data3.date;
var projectCode = data3.p_code;
var requestNumber = data3.rq_no;
var materialName = data4.name;
var purpose = data4.purpose;
var quantity = data4.quantity;
var cost = data4.cost;
var total = data4.total;
$("table.table").append("<tr><td>"+dateRequested+"</td><td>"+projectCode+"</td><td>"+requestNumber+"</td><td>"+materialName+"</td><td>"+purpose+"</td><td>"+quantity+"</td><td>"+cost+"</td><td>"+total+"</td></tr>");
});
},
//error: function(){console.log('Error Encountered')},
beforeSend: setHeader()
});
});
//set required headers
function setHeader(xhr){
xhr.setRequestHeader('Api-Key','ZHhjZmIyMHdnazVtdWw=');
xhr.setRequestHeader('Content-Type','application/json')
}
The code is supposed to connect to the API with the Api-Key as a header then fetch Json of format
{
'status':success,
'data':'[{
"p_code":,"requester_id":,
"date":,"rq_no":,
"id":, "materials":[{
"name":,
"purpose":,
"cost":,
"quantity":,
"status":,
"rq_no":,"id":,
"total":},
...
]}
.....
]'
... The data is to be assigned to variables then appended to the main HTML table
I finally had it working perfectly:
<script type="text/javascript">
function fetchJson(){
$(document).ready(function(){
$.ajax({
url: 'http://api.lynmerc-enterprise.com/requests',
headers: {
'Api-Key':'ZHhjZmIyMHdnazVtdWw='
//'Content-Type':'application/json'
},
//async: false, //return value as variable not to make an async success callback
type: 'GET',
dataType: 'json',
success: function(data){
console.log(data);
//var data2 = JSON.parse(data.data);
var data2 = data.data;
var data2Array = [];
$.each(data2, function(idx, data2){
console.log(data2.p_code);
console.log(data2.date);
console.log(data2.rq_no);
var userfo = data2.user;
console.log(userfo.fullname);
console.log(userfo.project_site);
var material = data2.materials;
var dateRequested = data2.date;
var requestNumber = data2.rq_no;
var requester = userfo.fullname;
var projectSite = userfo.project_site;
$.each(material, function(idx, material){
console.log(material.name);
console.log(material.purpose);
console.log(material.quantity);
console.log(material.cost);
console.log(material.total);
console.log(material.status);
var materialName = material.name;
var purpose = material.purpose;
var quantity = material.quantity;
var cost = material.cost;
var total = material.total;
var requestStatus = material.status;
/*$('#dateRequested').append(dateRequested);
$('#requestNumber').append(requestNumber);
$('#requester').append(requester);
$('#projectSite').append(projectSite);
$('#materialName').append(materialName);
$('#purpose').append(purpose);
$('#quantity').append(quantity);
$('#cost').append(cost);
$('#total').append(total);
$('#requestStatus').append(requestStatus); */
var table = $("#requestsTable");
table.append("<tr><td>"+dateRequested+
"</td><td>"+requester+
"</td><td>"+projectSite+
"</td><td>"+requestNumber+
"</td><td>"+materialName+
"</td><td>"+purpose+
"</td><td>"+quantity+
"</td><td>"+cost+
"</td><td>"+total+"</td></tr>");
});
});
},
error: function(){console.log('Error Encountered')},
//beforeSend: setHeader()
});
});
/* var request;
function setHeader(request){
request.setRequestHeader('Api-Key','ZHhjZmIyMHdnazVtdWw=');
request.setRequestHeader('Content-Type','application/json')
}*/
}
</script>
When using dataType:'json' in the code, we dont parse the json again as jQuery does all that so when we try to parse again it returns an error. Then for it to be appended to html we use $(selector).append where the selector is the element id. In this case when appending to table, we append to so it will be $(#tableBodyId).append("what to append");
I have this div
<div class='additional_comments'>
<input type="text" id='additional_comments_box', maxlength="200"/>
</div>
Which will only sometimes appear on the page if jinja renders it with an if statement.
This is the javascript i have to send an ajax request:
$(document).ready(function() {
var button = $("#send");
$(button).click(function() {
var vals = [];
$("#answers :input").each(function(index) {
vals.push($(this).val());
});
vals = JSON.stringify(vals);
console.log(vals);
var comment = $('#additional_comments_box').val();
var url = window.location.pathname;
$.ajax({
method: "POST",
url: url,
data: {
'vals': vals,
'comment': comment,
},
dataType: 'json',
success: function (data) {
location.href = data.url;//<--Redirect on success
}
});
});
});
As you can see i get the comments div, and I want to add it to data in my ajax request, however if it doesnt exist, how do I stop it being added.
Thanks
You can use .length property to check elements exists based on it populate the object.
//Define object
var data = {};
//Populate vals
data.vals = $("#answers :input").each(function (index) {
return $(this).val();
});
//Check element exists
var cbox = $('#additional_comments_box');
if (cbox.length){
//Define comment
data.comment = cbox.val();
}
$.ajax({
data: JSON.stringify(data)
});
I have this table that receive from the server:
(with ajax):
$.each(data, function(i, item) {
$('#MyTable tbody').append("<tr>"d
+"<td>" +data[i].A+ "</td><td>"
+data[i].B
+"</td><td><input type='text' value='"
+data[i].C+"'/></td><td><input type='text' value='"
+ data[i].D+"'/></td>"
+ "</tr>");
});
C and D are edit text, that the user can change. after the changing by the user I want to "take" the all new data from the table and send it by ajax with JSON.
how can I read the data to a JSON?
I start to write one but I am stuck on:
function saveNewData(){
var newData= ...
$.ajax({
type: "GET",
url: "save",
dataType: "json",
data: {
newData: newData},
contentType : "application/json; charset=utf-8",
success : function(data) {
...
},
error : function(jqXHR, textStatus, errorThrown) {
location.reload(true);
}
});
}
thank you
Try something like this,
function getUserData()
{
var newData = new Array();
$.each($('#MyTable tbody tr'),function(key,val){
var inputF = $(this).find("input[type=text]");
var fileldValues = {};
fileldValues['c'] = $(inputF[0]).val();
fileldValues['d'] = $(inputF[1]).val();
//if you want to add A and B, then add followings as well
fileldValues['a'] = $($(this).children()[0]).text();
fileldValues['b'] = $($(this).children()[1]).text();
newData.push(fileldValues);
});
return JSON.stringify(newData);
}
function saveNewData(){
var newData = getUserData();
$.ajax({
type: "GET",
url: "save",
dataType: "json",
data: {
newData: newData},
contentType : "application/json; charset=utf-8",
success : function(data) {
...
},
error : function(jqXHR, textStatus, errorThrown) {
location.reload(true);
}
});
}
http://jsfiddle.net/yGXYh/1/
small demo based on answer from Nishan:
var newData = new Array();
$.each($('#MyTable tbody tr'), function (key, val) {
var inputF = $(this).find("input[type=text]");
var fileldValues = {};
fileldValues['c'] = $(inputF[0]).val();
fileldValues['d'] = $(inputF[1]).val();
newData.push(fileldValues);
});
alert(JSON.stringify(newData));
use the jquery on event binding
try somthing like this. Fiddler Demo
$('#MyTable').on('keyup', 'tr', function(){
var $this = $(this);
var dataA = $this.find('td:nth-child(1)').text() // to get the value of A
var dataB = $this.find('td:nth-child(2)').text() // to get the value of B
var dataC = $this.find('td:nth-child(3)').find('input').val() // to get the value of C
var dataD = $this.find('td:nth-child(4)').find('input').val() // to get the Valur of D
// $.ajax POST to the server form here
// this way you only posting one row to the server at the time
});
I don't normaly do that I would use a data binding libarray such as Knockoutjs or AngularJS
I am trying to do an ajax registration, the following works good, it gets the data from a php function I wrote somewhere else and the registration and messages for both error and success work. But I am basically looking at:
hiding the form once the submit button is pressed
display a rotating icon,
then if success get a success message and no form
otherwise display an error.
Code:
var ajaxurl = '<?php echo admin_url('admin-ajax.php') ?>';
jQuery('#register-me').on('click',function(){
var action = 'register_action';
var username = jQuery("#st-username").val();
var mail_id = jQuery("#st-email").val();
var firname = jQuery("#st-fname").val();
var lasname = jQuery("#st-lname").val();
var passwrd = jQuery("#st-psw").val();
var ajaxdata = {
action: 'register_action',
username: username,
mail_id: mail_id,
firname: firname,
lasname: lasname,
passwrd: passwrd,
}
jQuery.post( ajaxurl, ajaxdata, function(res){
jQuery("#error-message").html(res);
});
Add id="myform" to the form element, then:
$("#myform").hide();
About the icon. When you click the button you could make the icon visible and when succeed or error then hide again.
jQuery('#register-me').on('click',function(){
$("#myform").hide();
jQuery('#loadingmessage').show();
var action = 'register_action';
var username = jQuery("#st-username").val();
var mail_id = jQuery("#st-email").val();
var firname = jQuery("#st-fname").val();
var lasname = jQuery("#st-lname").val();
var passwrd = jQuery("#st-psw").val();
var ajaxdata = {
action: 'register_action',
username: username,
mail_id: mail_id,
firname: firname,
lasname: lasname,
passwrd: passwrd,
}
jQuery.post( ajaxurl, ajaxdata, function(res){
$('#loadingmessage').hide(); // hide the loading message
$("#myform").show();
jQuery("#error-message").html(res);
});
});
An id to the form, and add a div with an image, give it an id and hide it with css.
You could use the deferred options here:
jQuery('#register-me').on('click', function () {
var action = 'register_action';
var username = jQuery("#st-username").val();
var mail_id = jQuery("#st-email").val();
var firname = jQuery("#st-fname").val();
var lasname = jQuery("#st-lname").val();
var passwrd = jQuery("#st-psw").val();
var ajaxdata = {
action: 'register_action',
username: username,
mail_id: mail_id,
firname: firname,
lasname: lasname,
passwrd: passwrd
};
jQuery.post(ajaxurl, ajaxdata)
.beforeSend(function (data, textSttus, jqxhr) {
$('#myform').hide();
alert('Show the spinner');
$('#spinner').show();
})
.done(function (data, jqxhr, settings ) {
alert("success");
})
.fail(function (event, jqxhr, settings, exception) {
alert("oops, fail");
$('#myform').show();
})
.always(function (event, jqxhr, settings ) {
alert('hide the spinner please');
$('#spinner').hide();
});
});