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 a php file saven on a different domain, and Im using this piece of code to send the username and with that get the info of the user.
Im trying to do something like this, but this is not working is there a way to do it.
var dataString = "username="+username+"";
var url = "";
$.ajax({
type: "POST",
url: url,
data: dataString,
crossDomain: true,
cache: false,
success: $.getJSON(url, function(result)
{
console.log(result);
$.each(result, function(i, field)
{
var id = field.id;
var username = field.username;
var email = field.email;
$('#profile-info').append("ID: " + id + "<br>Username: " + username + "<br>Email: " + email + "<br><br>");
});
})
});
Replace the $.getJSON() function you have for the success calback provided by the jQuery ajax function, and you can pass directly the username through the data parameter as { username : username }, because it's already defined.
Then when you receive successfully your data you can iterate over each result using the jQuery $.each function.
Do you really need to set the cache parameter to false?, just to know.
Also if you want use let instead of var, those variables will be just within the $.each "block".
<script>
var url = '';
$.ajax({
type: "POST",
url: url,
data: { username: username },
crossDomain: true,
cache: false,
success: function(result) {
console.log(result);
$.each(result, function(i, field) {
let id = field.id,
username = field.username,
email = field.email;
$('#profile-info').append("ID: " + id + "<br>Username: " + username + "<br>Email: " + email + "<br><br>");
});
}
});
</script>
Trying to do a GET on the values entered for some text fields but when console logging data ( i thought defined in the ajax) it just returns my whole page html.
<script>
/*<![CDATA[*/
$(document).ready(function() {
var submit = document.getElementById("submit");
var firstName = $("#firstName").val();
var LastName = $("#LastName").val();
var Phone = $("#Phone").val();
var Party = $("#Party").val();
var dateof = $("#dateof").val();
var Timeof = $("#Timeof").val();
submit.onclick = function(){
$.ajax({
type: "GET",
url: "reserve.html",
data: firstName, LastName, Phone, Party, dateof, Timeof,
cache: true,
success: function(data){
console.log(data);
}
});}})
;
/*]]>*/
</script>
I am also a bit lost as how to post the results to say a console.log (not setting up a server yet...) would I use ajax type post? how does this differ from get?
THANKS!
I have my contact form ready to go but for some reason when i gulp it with uglify it returns an error and won't minify. My javascript seems correct and it will uglify when I remove the ajax call but with the ajax call it breaks. Any insight? Here's my js:
$('.contact-form').on('valid.fndtn.abide', function() {
var name = $(".contact-form input#name").val();
var email = $(".contact-form input#email").val();
var message = $(".contact-form textarea#message").val;
// Data for response
var dataString = 'name=' + name +
'& email =' + email +
'& message =' + message;
//Begin Ajax Call
$.ajax({
type: "POST",
url: "php/mail.php",
data: dataString,
success: function() {
$('.contact-form').html("<div id ='success'></div>");
$('#success').html("<h2>Thanks!</h2>")
.append("<p>Dear" + name + "!, I look forward to working with you.</p>")
.hide()
.fadeIn(1500);
},
}); //ajax call
return false;
});
JsLint throws error on this code. Removing the trailing comma seems to clear it up:
.fadeIn(1500);
}, /* <-- remove this comma */
I was trying to submit data to database without redirecting the page.is there any error in this code?
$('#saving').on('click', function() {
var fname = $('#fname').val();
var lname = $('#lname').val();
var company = $('#company').val();
var mnum = $('#mnum').val();
var dataString = 'fname=' +fname + '&lname=' + lname + '&company=' + company + '&mnum=' + mnum;
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
success: function() {
alert('');
$('#dialog-message').dialog('open');
}
});
});
I think you want preventDefault:
function(event) {
// ... ajax ...
event.preventDefault();
}
The documentation states:
If this method is called, the default action of the event will not be triggered.