I am having a problem getting values assigned for fname, lname and etc, these do not exist on the page until the success function is called and it posts to template/orderForm.php. if i for example console.log(fname) i get an empty field.
The first thing that happens is on login button submit it checks the information against the database via phpscripts/login.php, on success of that it posts to another page to get form data, such as their name and etc which are auto-populated with php echos.
$("#loginSubmit").click(function() {
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
type: "POST",
url: "phpscripts/login.php",
dataType: 'text',
data: {
username: username,
password: password
},
success: function(data){
if(data == 'worked') {
$("#loginForm").hide(500);
$("#loginBtn").hide(500);
$("#registerBtn").hide(500);
$("#forgotPasswordBtn").hide(500);
$.post('template/orderForm.php', function(data) {
$('#approveData').html(data);
$("#updateInfo").click(function() {
var fname = $('#fname').attr('value');
var lname = $('#lname').attr('value');
var address = $('#address').attr('value');
var city = $('#city').attr('value');
var state = $('#state').attr('value');
var zip = $('#zip').attr('value');
var phone = $('#phone').attr('value');
console.log(fname);
$.ajax({
type: "POST",
//change to update script that is in myaccount.php
url: "phpscripts/update.php",
data: {
fname: fname,
lname: lname,
address: address,
city: city,
state: state,
zip: zip,
phone: phone
},
success: function(){
//do nothing
}
});
});
});
}
else {
}
}
});
});
Try $('#fname').val() instead of $('#fname').attr('value'), and same with others.
I don't know what's going on with your HTML so here's my guess:
This line:
$('#approveData').html(data);
contains your html which houses the element with an id of fname.
This js:
$("#updateInfo").click(function() { ... });
should be this:
$("#updateInfo").live('click', function() { ... });
And be outside in a ready statement or something. Not defined within the results of another listener.
This link explains .live:
http://api.jquery.com/live/
It registers newly inserted dom elements where as your basic listener you provided will not IF the fname element is written in by your request - an assumption, so don't yell if I am wrong here.
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 an AJAX post method that works in two places both on "Ladder" page, but not another, a "matches" page. This method sets posts the "player ID" which php picks up and sets a session variable
$("form .singles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Working page form:
<form><button type='submit' id='playerInfo' class='singles-player-name' name='viewPlayer' value='",$sglsPlayerID,"'>", $curSGLSRankLName, ", ", $curSGLSRankFName, "</button></form>
Sets session variable
if (!empty($_POST['viewPlayerID'])){
$viewPlayer = isset($_POST['viewPlayerID']) ? $_POST['viewPlayerID'] : 'No data found';
$viewPlayerSql = "SELECT * FROM `PLAYERS` WHERE `ID` LIKE '".$viewPlayer."'";
$viewPlayerQuery = #$conn->query($viewPlayerSql);
$viewPlayerRow=mysqli_fetch_assoc($viewPlayerQuery);
$_SESSION['playerID'] = $viewPlayerRow["ID"];
echo "", $_SESSION['playerID'],"";}
Second working version that lives on the same page as the first but is for doubles players:
$("form .doubles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Form for that ajax method:
<form><button type='submit' id='playerInfo' class='doubles-player-name' name='viewPlayer' value='",$dblsPlayerID,"'>", $curDBLSRankLName, ", ", $curDBLSRankFName, "</button></form>
Then on complete, the ajax methods redirect to the player page and pulls up that players info on that page (ex. https://urlexample.com/Player). This part, from this point-up, works! However, I have another page, the "Matches" page, where I want it to do the same exact thing, and set that session variable, then redirect to the player page, so I have this method below. But for some reason, this one does not work:
$("form .singlesMatch-player1-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
console.log(data);
window.location.href = "Player";
});
});
Not working form:
<form><button type='submit' id='playerInfo' class='singlesMatch-player1-name' name='viewPlayer' value='",$sglsPlayer1ID,"'>", $P1LN, ", ", $P1FN, "</button></form>
For some reason, all this second method does is post it to the URL (ex. https://urlexample.com/WeeklyMatchUps?viewPlayer=1) instead of setting the session variable and redirecting to the player page (ex. https://urlexample.com/Player). All thats different between the 2 is the class name of the button.
$sglsPlayer1ID should probably be $sglsPlayerID.
Also, try adding a success and error condition to your AJAX conditions instead of just using a done operator. This will allow you to dump helpful error codes on a failure to better resolve these kinds of issues in the future.
I had a function being called on the page that was commented out causing an error before jQuery was added in a script at the bottom of the page. removing that function from being called fixed the issue.
S/O to #line88 for the assistance!
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!
So I want to detect if the value a user is typing in an input exists in the database, if so, display an error message. I've gotten pretty close except when the input is empty, the empty value is being submitted instead of what is GOING to be typed.
$("#email").on("blur", function(){
var val = $(this).val(), id = $("#id").val();
$.ajax({
method: 'GET',
url: '/msg',
data: {
action: "check_title",
email: val,
id: id
},
success: function(data) {
$(".error-msg").text(data);
}
})
});
I've also tried one with a keyup function and it's still doing the same, evaluating the empty field. How can I have it so it's constantly evaluating what is being typed?
Along the same lines as Jeff Puckett's answer, I would perform the empty test and return an instructional message if empty:
$("#email").on("blur", function(){
var val = $(this).val(), id = $("#id").val();
if (val.length < 1 || val==""){
alert('Please complete all fields');
$('#email').css('background','yellow').focus();
return false;
}
$.ajax({
method: 'GET',
url: '/msg',
data: {
action: "check_title",
email: val,
id: id
},
success: function(data) {
$(".error-msg").text(data);
}
});
});
This snippet creates an input with the id of "in" and checks if there is something in in's value. I guess that is answering your question a bit more specifically. And thanks "Jeff Puckett II" for pointing this out.
$('#in').on('input focusout', function(){
var val = $('#in').val();
if (val != ""){
console.log('someones typing');
} else {
console.log('empty');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<input id="in" type="text">
</body>
try .on('input') instead of .on('blur')
$("#email").on("input", function(){//do something});
//in your function just add
if(!val) {
$(".error-msg").text("Empty!");
}
//or
if(val) {
//your ajax code
}
simply check if input is empty first
$("#email").on("blur", function(){
var val = $(this).val(), id = $("#id").val();
// check if val is empty
if (val != "")
$.ajax({
method: 'GET',
url: '/msg',
data: {
action: "check_title",
email: val,
id: id
},
success: function(data) {
$(".error-msg").text(data);
}
})
});
use this:
$('input').keyup(function(){
console.log($(this).val());
});
keyup or keydown to get data every time when a user type in the focused input.
This code will submit the information from the form to a php file, everything works as it should, but when i write "hello this a text + - * " it remove the " + " sign from what i wrote, always. I dont know why, please help me out guys
$(document).ready(function(){
$("form#submit").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var fname = $('#fname').attr('value');
var lname = $('#lname').attr('value');
$.ajax({
type: "POST",
url: "Mail.php",
data: "fname="+ fname + "&lname=" + lname,
success: function(){
$('form#submit').show();
//$('form#submit :input').val("");
$('div.success').fadeIn();
}
});
return false;
});
});
Change this line:
data: "fname="+ fname + "&lname=" + lname,
to:
data: "fname="+ encodeURIComponent(fname) + "&lname=" + encodeURIComponent(lname),
You need to escape special characters for use in URL strings.
if fname and lname are text boxes, why not use the .val() to retrieve them?
var fname = $('#fname').val();
var lname = $('#lname').val();
or better, use form .serialize() directly on the ajax:
$(function () {
$("form#submit").submit(function () {
var form = $(this)
$.ajax({
type: "POST",
url: "Mail.php",
data: form.serialize() //turns the form data into a query string
success: function () {
$('form#submit').show();
$('div.success').fadeIn();
}
});
return false;
});
});
That's because the pluses are converted to spaces. Use encodeURIComponent to escape the input. Always use some kind of escaping to avoid injections.
Or you could use serialize():
$.ajax({
...
data: $(this).serialize()
...
});
This takes all the :input elements inside your form and encodes them properly for sending to a remote server. You could also do this:
data: {
fname: fname,
lname: lname
}
jQuery understands that you're trying to send an array of values and will automatically escape it.
Btw, this is not very portable:
var fname = $('#fname').attr('value');
The better way is this:
var fname = $('#fname').val();
var email = $('#email').val();
var data = 'email=' + encodeURIComponent(email);
var url = 'test.php'
var type = 'post'
var success = function(output){}
var error = function(){}
$.ajax({
url:url,
type:type,
data:data,
success:success,
error:error
});
work great for me