I am trying to figure out how I can check if any values in the object are blank, and then show the corresponding error.
The form inputs look like this:
<form role="form" action="home.php" class="addLaneForm" id="addLaneForm" name="addLaneForm">
<label for="addlanepartnercode">Partner Code</label><span id="addlanepartnercodeError" class="text-danger laneError" style="display:none;"> * </span>
<input type="text" class="form-control validation" id="addlanepartnercode" placeholder="Enter Partner Code" />
<label for="addlanepartnername">Partner Name</label><span id="addlanepartnernameError" class="text-danger laneError" style="display:none;"> * </span>
<input type="text" class="form-control validation" id="addlanepartnername" placeholder="Enter Partner Name" />
<label for="addlaneipicy">IPI/CY</label><span id="addlaneipicyError" class="text-danger laneError" style="display:none;"> * </span>
<select class="form-control validation" id="addlaneipicy">
<option></option>
<option value="YES">YES</option>
<option value="NO">NO</option>
</select>
// few more inputs and selects
<button type="button" class="btn btn-default btn-flat addLaneSubmit" id="addLaneSubmit" name="addLaneSubmit">Add</button>
</form>
Here is the onClick event:
$('#addLaneSubmit').on('click', function(e){
e.preventDefault();
let partnerCode = $('#addlanepartnercode').val();
let partnerName = $('#addlanepartnername').val();
let ipiCy = $('#addlaneipicy').val();
let addlane = new ProcessLane();
let addlanecriteria = {
partnerCode: partnerCode,
partnerName: partnerName,
ipiCy: ipiCy
}
// how I typically would check the values below:
if(addlanecriteria.partnerCode == ""){
$('#addlanepartnercodeError').show();
return false;
}
if(addlanecriteria.partnerName == ""){
$('#addlanepartnernameError').show();
return false;
}
else{
addlane.addLaneProcessing(addlanecriteria);
}
});
The way I typically check the values is redundant and time consuming.
I did add a class to the inputs called 'laneError'. I was trying to use that to display the errors by calling a function, as follows:
function showAllErrors(){
if($(".addLaneForm .validation") == ""){
$('.laneError').show();
}
}
For one, I wasn't sure where I could put the function call.
But when I was able to call the function, I can only get the first error to show, which is "addlanepartnercodeError".
There has to be a simpler way to check the values in the object.
You can just have a reusable function like below:
showErrorMsg(elemId) {
if($.trim($('#' + elemid).val()) === '') {
$('#' + elemId + 'Error').show()
return true;
}
return false;
}
So your code would just be:-
$('#addLaneSubmit').on('click', function(e){
e.preventDefault();
let Error = false,
addlane = new ProcessLane();
$('form')
.find("input[id^='add']")
.each((i , e){
if(!Error) {
Error = showErrorMsg($(e).attr('id'))
}
})
if(!Error) {
// Your form has no errors , do your thing here
addlane.addLaneProcessing(addlanecriteria);
}
});
I have code a simple form in which I retrieve data dynamically and then sending it to another page. Using that data i want some divs to be displayed on my page. It is returning divs when I check it simply without using AJAX. But now I have applied some AJAX and it is not working. Any suggestions please.
AJAX
$("document").ready(function() {
$("#search_keyword").on("submit", function (e) {
e.preventDefault();
$.post("keyword_search.php?query="+encodeURIComponent($("#keyword").val())+"category="+encodeURIComponent($("#category").val())+"store="+encodeURIComponent($("#store").val()), function (data) {
var res = JSON.parse(data);
if (res.divs) {
$('#search_result').html("");
for (var i = 0; i < res.divs.length; i++) {
$('#search_result').append(res.divs[i]);
}
} else {
$('#search_result').html("No matched coupons found !");
}
});
});
});
form
<form class="form-horizontal select-search" id="search_keyword" method="post">
<label class="control-label ">Keyword</label>
<input class="form-control" id="keyword" name="keyword" type="text">
<!-- Select Category -->
<label class="control-label " for="category">Select category</label>
<select class="category" id="category" name="category">
<?php
$sm=mysqli_query($con,"select * from categories ");
while ($row1 = mysqli_fetch_array($sm,MYSQLI_ASSOC)){
$cat_id = $row1['cat_id'];
$name = $row1['cat_name'];
echo '<option value="' . $cat_id . '">' . $name . '</option>';
}
?>
</select>
<label class="control-label " for="store">Select a store</label>
<select class="storesname" id="store" name="store">
<option selected="selected">Select Stores</option>
</select>
<button id="search_btn" name="search_btn" class="btn btn-danger">Search coupons</button>
</form>
<div id="search_result"> </div>
You need to change from button to submit type so that it can actually submit.
So change:-
<button id="search_btn" name="search_btn" class="btn btn-danger">Search coupons</button>
To:-
<input type="submit" id="search_btn" name="search_btn" class="btn btn-danger" value="Search coupons"/>
Note:- Make sure that jQuery library added before your script code so that it will work.
Change your code like below:-
$("document").ready(function() {
$("#search_keyword").on("submit", function (e) {
e.preventDefault();
var data = {'query':encodeURIComponent($("#keyword").val()),'category':encodeURIComponent($("#category").val()),'store':encodeURIComponent($("#store").val())};
$.post("keyword_search.php",data, function (data) {
var res = JSON.parse(data);
if (res.divs) {
$('#search_result').html("");
for (var i = 0; i < res.divs.length; i++) {
$('#search_result').append(res.divs[i]);
}
} else {
$('#search_result').html("No matched coupons found !");
}
});
});
});
And in your keyword_search.php check like this:-
<?php
echo "<pre/>";print_r($_POST); //check that how post data are coming
// rest do code accordingly
?>
Also remove method="post" from your current <form>
You just to change some thing in jQuery.
I have just changed "submit" to "click" and "#search_keyword" to "#search_btn"
$("document").ready(function() {
$("#search_btn").on("click", function (e) {
e.preventDefault();
$.post("keyword_search.php?query=" + encodeURIComponent($("#keyword").val())+encodeURIComponent($("#category").val())+encodeURIComponent($("#store").val()), function (data) {
var res = JSON.parse(data);
if (res.divs) {
$('#search_result').html("");
for (var i = 0; i < res.divs.length; i++) {
$('#search_result').append(res.divs[i]);
}
} else {
$('#search_result').html("No matched coupons found !");
}
});
});
});
It might help you
For starters this is an internal website for my company, running sql serv. This is my first time ever doing anything with AJAX. I am literally a month into PHP, SQL, Javascript.. haven't messed with jQuery in ages and what I know is from codeacademy.. lol.
Below I have the jQuery script, HTML, and the SQL. The issue is residing around the EDIT / UPDATE portion of the jQuery. I put the HTML and SQL for reference.
The deal is.. if I click Edit on User1, it'll store the EeNumberID (1) as well as all his data from hidden inputs (any recommendations on better method?), then I click User2 it'll store his EeNumberID (2). Then when I update User2 - it'll also update User1 with his information - even though his EeNumberID is different.. it's like it's passing two lines of updateData to the management-queries.php and calling for two lines in the database to be updated.. but why?
Is it creating EeNumberID into an array once I select a second user to edit? Does it store this variable multiple times locally? I tried various ways to display the variable and it is displaying as how it should be sent to the SQL update.
Help! :(
JQUERY
$(document).ready(function(){
//LETS HIDE WHAT WE DON'T INITIALLY NEED TO SEE
$("#updateuser, #canceledit").hide();
//BY DEFAULT WHEN THE PAGE LOADS SHOW ALL USERS
//WE ALSO PASS LOCATION AND PERMISSION SO BY DEFAULT USER CAN ONLY SEE WHAT THEY'RE ALLOWED TO
function showUsers(){
$.ajax({
type: "post",
url: "admin/management-queries.php",
data: "action=showusers&location=<?php echo $location?>&permission=<?php echo $permission?>",
success:function(data){
$("#userlist").html(data);
//EVERY TIME A LIST OF USERS IS GENERATED WE NEED TO HIDE CANCEL EDIT BUTTONS
$(".cancel-button").hide();
}
});
}
showUsers();
//ADD USER
$("#adduser").click(function(){
//EVERYTIME 'ADD USER' IS CLICKED WE NEED TO CLEAR ANY PREVIOUS ERROR MESSAGES
$("#UserFullName,#UserPassword,#UserPassword2,#UserEmail,#UserLocation,#UserPermission").removeClass("form-error");
$("span.label").remove();
var fullname = $("#UserFullName").val();
var password = $("#UserPassword").val();
var password2 = $("#UserPassword2").val();
var email = $("#UserEmail").val();
var location = $("#UserLocation").val();
var permission = $("#UserPermission").val();
//BEFORE WE PASS THE DATA WE NEED TO CHECK IF IT'S ALL THERE
if (fullname == "" || password != password2 || email == "" || location == null || permission == null) {
if (fullname == "") {
$("#UserFullName").addClass("form-error").after("<span class='label label-danger'>This field is required.</span>");
};
if (password != password2) {
$("#UserPassword").addClass("form-error");
$("#UserPassword2").addClass("form-error").after("<span class='label label-danger'>Passwords do not match.</span>");
} else if (password == "" || password2 == "") {
$("#UserPassword").addClass("form-error");
$("#UserPassword2").addClass("form-error").after("<span class='label label-danger'>These fields are required.</span>");
};
if (email == "") {
$("#UserEmail").addClass("form-error").after("<span class='label label-danger'>This field is required.</span>");
};
if (location == null) {
$("#UserLocation").addClass("form-error").after("<span class='label label-danger'>This field is required.</span>");
};
if (permission == null) {
$("#UserPermission").addClass("form-error").after("<span class='label label-danger'>This field is required.</span>");
};
} else {
var addData = "UserEmail="+email+"&UserPassword="+password+"&UserLocation="+location+"&UserFullName="+fullname+"&UserPermission="+permission+"&action=adduser";
$.ajax({
type: "post",
url: "admin/management-queries.php",
data: addData,
success:function(data){
//IF THE DATA IS ADDED WE NEED TO CLEAR THE INPUT FIELDS
$("#UserFullName, #UserPassword, #UserPassword2, #UserEmail, #UserLocation, #UserPermission").val('');
showUsers();
}
});
};
});
//DELETE USER
$("body").on("click", "#userlist .delete-button", function(e) {
e.preventDefault();
var clickedID = this.id.split('-');
var DbNumberID = clickedID[1];
var delData = 'deleteuser='+ DbNumberID;
jQuery.ajax({
type: "post",
url: "admin/management-queries.php",
data: delData,
success:function(data){
showUsers();
}
});
});
//EDIT USER
$("body").on("click", "#userlist .edit-button", function(e) {
$(".edit-button").show();
var EeNumberID = $(this).attr('name');
//GET ALL THE VARIABLES VIA HIDDEN INPUTS POPULATED BY SQL
var EditName = $("#Name-"+EeNumberID).val();
var EditPassword = $("#Password-"+EeNumberID).val();
var EditEmail = $("#Email-"+EeNumberID).val();
var EditLocation = $("#Location-"+EeNumberID).val();
var EditPermission = $("#Permission-"+EeNumberID).val();
//LETS ADJUST VISUALS AS WE ARE IN EDIT MODE
$("#adduser, .cancel-button, #edit-"+ EeNumberID).hide();
$("#canceledit, #updateuser, #cancel-"+ EeNumberID).show();
$(".row").removeClass("sel-edit");
$("#user-"+ EeNumberID).addClass("sel-edit");
//PASS VARIABLE VALUES TO INPUT FIELDS
$("#UserFullName").val(EditName);
$("#UserPassword, #UserPassword2").val(EditPassword);
$("#UserEmail").val(EditEmail);
$("#UserLocation").val(EditLocation);
$("#UserPermission").val(EditPermission);
//CANCEL EDIT (FROM WITHIN ROW)
$("#cancel-"+ EeNumberID).click(function(){
//ADJUST VISUALS FOR CANCEL
$("#canceledit, #updateuser, .cancel-button").hide();
$("#adduser, .edit-button").show();
$(".row").removeClass("sel-edit");
//CLEAR INPUT FIELDS
$("#UserFullName, #UserPassword, #UserPassword2, #UserEmail, #UserLocation, #UserPermission").val('');
});
//UPDATE USER (THIS MUST BE NESTED WITHIN 'EDIT USER' SO WE KNOW THE ROW CURRENTLY OPENED)
$("#updateuser").click(function(){
//EVERYTIME 'UPDATE USER' IS CLICKED WE NEED TO CLEAR ANY PREVIOUS ERROR MESSAGES
$("#UserFullName,#UserPassword,#UserPassword2,#UserEmail,#UserLocation,#UserPermission").removeClass("form-error");
$("span.label").remove();
var ID = EeNumberID;
var fullname = $("#UserFullName").val();
var password = $("#UserPassword").val();
var password2 = $("#UserPassword2").val();
var email = $("#UserEmail").val();
var location = $("#UserLocation").val();
var permission = $("#UserPermission").val();
//BEFORE WE PASS THE DATA WE NEED TO CHECK IF IT'S ALL THERE
if (fullname == "" || password != password2 || email == "" || location == null || permission == null) {
if (fullname == "") {
$("#UserFullName").addClass("form-error").after("<span class='label label-danger'>This field is required.</span>");
};
if (password != password2) {
$("#UserPassword").addClass("form-error");
$("#UserPassword2").addClass("form-error").after("<span class='label label-danger'>Passwords do not match.</span>");
} else if (password == "" || password2 == "") {
$("#UserPassword").addClass("form-error");
$("#UserPassword2").addClass("form-error").after("<span class='label label-danger'>These fields are required.</span>");
};
if (email == "") {
$("#UserEmail").addClass("form-error").after("<span class='label label-danger'>This field is required.</span>");
};
if (location == null) {
$("#UserLocation").addClass("form-error").after("<span class='label label-danger'>This field is required.</span>");
};
if (permission == null) {
$("#UserPermission").addClass("form-error").after("<span class='label label-danger'>This field is required.</span>");
};
} else {
var updateData = "ID="+ID+"&UserEmail="+email+"&UserPassword="+password+"&UserLocation="+location+"&UserFullName="+fullname+"&UserPermission="+permission+"&action=updateuser";
$.ajax({
type: "post",
url: "admin/management-queries.php",
data: updateData,
success: function(data){
$("#UserFullName, #UserPassword, #UserPassword2, #UserEmail, #UserLocation, #UserPermission").val('');
$("#canceledit, #updateuser, .cancel-button").hide();
$("#adduser, .edit-button").show();
showUsers();
}
});
};
});
});
//CANCEL EDIT (GLOBAL)
$("#canceledit").click(function(){
//ADJUST VISUALS FOR CANCEL
$("#canceledit, #updateuser, .cancel-button").hide();
$("#adduser, .edit-button").show();
$(".row").removeClass("sel-edit");
//CLEAR INPUT FIELDS
$("#UserFullName, #UserPassword, #UserPassword2, #UserEmail,#UserLocation, #UserPermission").val('');
});
});
HTML INCLUDE(BOOTSTRAP DRIVEN)
<div class="container-fluid">
<div class="row">
<div class="col-xs-4 panel-container">
<div class="panel panel-default">
<div class="panel-heading"> </div>
<div class="panel-body">
<form>
<div class="row input-padding">
<div class="col-xs-12"><input class="form-control" type="text" name="UserFullName" id="UserFullName" placeholder="Full Name"></input></div>
</div>
<div class="row input-padding">
<div class="col-xs-12"><input class="form-control" type="password" name="UserPassword" id="UserPassword" placeholder="Password"></input></div>
</div>
<div class="row input-padding">
<div class="col-xs-12"><input class="form-control" type="password" name="UserPassword2" id="UserPassword2" placeholder="Confirm Password"></input></div>
</div>
<div class="row input-padding">
<div class="col-xs-12"><input class="form-control" type="text" name="UserEmail" id="UserEmail" placeholder="E-Mail"></input></div>
</div>
<div class="row input-padding">
<div class="col-xs-12">
<select name="UserLocation" id="UserLocation" class="form-control">
<?php
$sqlresult = sqlsrv_query($connection, "SELECT * FROM MESCO_locations");
echo '<option value="" disabled'; if(!isset($VALLocation)) {echo' selected';} echo ' hidden>Select User Location</option>';
while($row = sqlsrv_fetch_array($sqlresult)) {
echo '<option value="'.$row['location_id'].'">'.$row['location_name'].'</option>';
}
?>
</select>
</div>
</div>
<div class="row input-padding">
<div class="col-xs-12">
<select name="UserPermission" id="UserPermission" class="form-control">
<option value="" disabled selected hidden>Select User Permission</option>
<option value="0">Disabled</option>
<?php
if ($_SESSION['Permission'] == 1) {
echo ' <option value="1">Administrator</option>';
}
if ($_SESSION['Permission'] <= 2) {
echo ' <option value="2">Branch Manager</option>';
}
if ($_SESSION['Permission'] <= 3) {
echo ' <option value="3">Warehouse Manager</option>
<option value="4">Warehouse Employee</option>
';
}
if ($_SESSION['Permission'] <= 2) {
echo ' <option value="5">Purchasing</option>
<option value="6">Inside Sales</option>
<option value="7">Outside Sales</option>
<option value="8">Accounts Receivable</option>';
}
?>
</select>
</div>
</div>
<div class="row input-padding input-button">
<div class="col-xs-12">
<button type="button" class="btn btn-sm btn-info" id="updateuser">UPDATE USER</button>
<button type="button" class="btn btn-sm btn-warning" id="canceledit">CANCEL</button>
<button type="button" class="btn btn-sm btn-success" id="adduser">ADD USER</button>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="col-xs-8 panel-container">
<div class="panel panel-default">
<div class="panel-heading">
<strong><i class="fa fa-users"></i> User Management</strong>
</div>
<div class="panel-body">
<div class="row row-heading error-data">
<div class="col-xs-2">Full Name</div>
<div class="col-xs-4 center">E-Mail</div>
<div class="col-xs-1 center">Location</div>
<div class="col-xs-3 center">Permission</div>
<div class="col-xs-2 center">EDIT / DEL</div>
</div>
<hr class="margin-reset" />
<div class="row row-data error-data">
<div class="col-xs-12" id="userlist"></div>
</div>
</div>
</div>
</div>
</div>
</div>
PHP/SQL
////----------------------- INITIATE -----------------------////
set_time_limit(0); //SETS TIME LIMIT FOR SCRIPT EXECUTION - 0 = UNLIMITED
require_once('C:\inetpub\wwwroot\connection.php'); //CUSTOM ROOT FOR AJAX QUERIED CONNECTIONS
$connectionInfo = array("UID" => $myUser, "PWD" => $myPass, "Database" => $myDB, "ReturnDatesAsStrings" => true);
$connection = sqlsrv_connect($myServer, $connectionInfo);
//IF CONNECTION IS NOT ESTABLISHED THROW MESSAGE AND END SCRIPT
if( !$connection ) {
die("Connection to MS SQL could not be established.\n");
}
//AJAX POST ON WHAT QUERY ACTION TO TAKE (Example: ?action=showusers)
$action = $_POST["action"];
//CURRENT USER PERMISSION AND LOCATION
$permission = $_POST["permission"];
$location = $_POST["location"];
////----------------------- USER MANAGEMENT -----------------------////
//USER MANAGEMENT - DISPLAY FOR WHAT THEY USER ALWAYS SEES
if($action == "showusers") {
//WE NEED TO ASSESS WHAT THE USER HAS THE ABILITY TO SEE
if ($permission == 1) {
//BY DEFAULT ADMINISTRATORS CAN SEE ALL USERS FOR ALL BRANCHES
$sqlresult = sqlsrv_query($connection, "SELECT * FROM MESCO_logins ORDER BY Location ASC, Name ASC");
} else if ($permission == 3) {
//BY DEFAULT WAREHOUSE MANAGERS CAN ONLY SEE DISABLED USERS, WAREHOUSE MANAGERS, AND WAREHOUSE EMPLOYEES FOR THEIR BRANCH
$sqlresult = sqlsrv_query($connection, "SELECT * FROM MESCO_logins WHERE Location = '$location' AND Permission_Level in (3,4,0) ORDER BY Location ASC, Name ASC");
} else {
//ALL OTHER USERS CAN SEE ALL USERS FOR THEIR BRANCH (TEMPORARY)
$sqlresult = sqlsrv_query($connection, "SELECT * FROM MESCO_logins WHERE Location = '$location' ORDER BY Location ASC, Name ASC");
}
while($row = sqlsrv_fetch_array($sqlresult)) {
echo '
<div class="row row-data" id="user-'.$row[ID].'">
<div class="col-xs-2"><input type="hidden" id="Name-'.$row[ID].'" value="'.$row[Name].'">'.$row['Name'].'</div>
<div class="col-xs-4 center"><input type="hidden" id="Email-'.$row[ID].'" value="'.$row[Email].'">'.$row['Email'].'</div>
<div class="col-xs-1 center"><input type="hidden" id="Location-'.$row[ID].'" value="'.$row[Location].'">'.$row['Location'].'</div>
<div class="col-xs-3 center"><input type="hidden" id="Permission-'.$row[ID].'" value="'.$row[Permission_Level].'">';
//LETS CONVERT PERMISSION NUMERICS TO TEXT
//THIS IS TEMPORARY - IDEALLY WE CAN HAVE A JOINED TABLE OR STORE THE TEXT DIRECTLY IN THE USER LOGIN TABLE FOR LESS CODE
if ($row['Permission'] == '0') {
echo 'Disabled / Inactive';
} else if ($row['Permission_Level'] == '1') {
echo 'Administrator';
} else if ($row['Permission_Level'] == '2') {
echo 'Branch Manager';
} else if ($row['Permission_Level'] == '3') {
echo 'Warehouse Manager';
} else if ($row['Permission_Level'] == '4') {
echo 'Warehouse Employee';
} else if ($row['Permission_Level'] == '5') {
echo 'Purchasing';
} else if ($row['Permission_Level'] == '6') {
echo 'Inside Sales';
} else if ($row['Permission_Level'] == '7') {
echo 'Outside Sales';
} else if ($row['Permission_Level'] == '8') {
echo 'Accounts Receivable';
}
echo'
</div>
<div class="col-xs-2 center action-buttons">
<input type="hidden" id="Password-'.$row[ID].'" value="'.$row[Password].'">
<button type="button" class="btn btn-xs btn-warning cancel-button" name="Cancel Edit" id="cancel-'.$row['ID'].'"><i class="fa fa-ban"></i></button>
<button type="button" class="btn btn-xs btn-info edit-button" name="'.$row['ID'].'" id="edit-'.$row['ID'].'"><i class="fa fa-pencil"></i></button>
<button type="button" class="btn btn-xs btn-danger delete-button" name="Delete User" id="delete-'.$row['ID'].'"><i class="fa fa-times"></i></button>
</div>
</div>';
}
}
//USER MANAGEMENT - ADD USER
if($action == "adduser") {
$ADDEmail = $_POST['UserEmail'];
$ADDPassword = $_POST['UserPassword'];
$ADDLocation = $_POST['UserLocation'];
$ADDFullName = $_POST['UserFullName'];
$ADDPermission = $_POST['UserPermission'];
$sqlquery = "INSERT INTO MESCO_logins (Email, Password, Location, Name, Permission_Level) VALUES ('$ADDEmail', '$ADDPassword', '$ADDLocation', '$ADDFullName', '$ADDPermission')";
$sqlresult = sqlsrv_query($connection, $sqlquery);
}
//USER MANAGEMENT - DELETE USER
if (isset($_POST["deleteuser"])) {
$DELID = $_POST["deleteuser"];
$sqlquery = "DELETE FROM MESCO_logins WHERE ID = '$DELID'";
$sqlresult = sqlsrv_query($connection, $sqlquery);
}
//USER MANAGEMENT - UPDATE USER
if($action == "updateuser") {
$ID = $_POST["ID"];
$UPDATEEmail = $_POST['UserEmail'];
$UPDATEPassword = $_POST['UserPassword'];
$UPDATELocation = $_POST['UserLocation'];
$UPDATEFullName = $_POST['UserFullName'];
$UPDATEPermission = $_POST['UserPermission'];
$sqlquery = "UPDATE MESCO_logins SET Email = '$UPDATEEmail', Password = '$UPDATEPassword', Location = '$UPDATELocation', Name = '$UPDATEFullName', Permission_Level = '$UPDATEPermission' WHERE ID = '$ID'";
$sqlresult = sqlsrv_query($connection, $sqlquery);
}
?>
In your PHP/SQL file, you have a systemic problem with quoting array elements, for instance:
while($row = sqlsrv_fetch_array($sqlresult)) {
echo '
<div class="row row-data" id="user-'.$row[ID].'">
<div class="col-xs-2"><input type="hidden" id="Name-'.$row[ID].'" value="'.$row[Name].'">'.$row['Name'].'</div>
Each and every $row[ID] needs to be corrected to $row['ID']. I'd also recommend turning on error reporting, if it's not already on. There is probably a series of cascading errors compromising the entire script.
Also, I would highly recommend taking a look at jQuery's .data, which allows easy storage of data on DOM elements.
Ohhhh boy! I fixed it! =]
Not sure why it was acting the way it did.. But it was because I nested the 'update' within the 'edit'. To fix the OP I did the following:
Declared a global variable:
var EditID = {};
I then altered the initial edit script from:
var EeNumberID = $(this).attr('name');
to
EeNumberID = $(this).attr('name');
EditID.EeNumberID = EeNumberID;
Now that I have the ID local for grabbing edit information, I then stored it globally so update knows exactly what to target. I think for some reason because it was nested and the page wasnt necessarily 'refreshing' it remember what it had been told to 'edit' previously.. and would pass it ALL to the update function.
Update was un-nested from the EDIT and I altered the following line:
var ID = EeNumberID;
to
var ID = EditID.EeNumberID;
WORKS! :) If anyone else has input on how to write cleaner php/javascript/jquery/sql please let me know! I am still learning and ALL input is appreciated!
Hello guys i have this php jquery ajax create user form that passes the create details to the php script but i keep getting null on the post variables anyhelp would be appreciated! code below
Html:
<form method="post" action="" id="createForm">
<input type="text" name="createUser" class="form-control" placeholder="Brugernavn*" id="createUser">
<input type="email" name="createUserEmail" class="form-control" placeholder="Email*" id="createUserEmail">
<input type="password" name="createUserPass" id="createUserPass" class="form-control" placeholder="Kodeord*" id="createUserPass">
<input type="password" name="confirmUserPass" id="confirmUserPass" class="form-control" placeholder="Bekræft Kodeord*" id="createUserPass">
<h4 id="newsletterText">Vil du have vores nyhedsbrev?</h4>
<select name="newsletter" id="newsletter" class="form-control"><option value="yes">Ja tak!</option><option value="nej" selected="">Nej tak</option></select>
<input type="submit" name="submitCreateUser" class="btn btn-success" id="submitCreateUser" value="Opret!">
</form>
jquery:
$(document).ready(function(){
$("#submitCreateUser").click(function(){
var username = $("#createUser").val();
var email = $("#createUserEmail").val();
var pass = $("#createUserPass").val();
var cPass = $("#createUserPassC").val();
var newsletter = $("#newsletter").val();
$.ajax({
type: "POST",
url: "createuserajax.php",
data: "username="+username+"&email="+email+"&pass="+pass+"&cPass="+cPass,
success: function(html){
if(html=='true')
{
alert(username);
}
else
{
}
},
}
);
});
});
PHP:
<?php
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['pass'];
var_dump($username);
$securePassword = md5(($password));
$sqlInsertUser = "INSERT INTO users (username,email,password) VALUES ('$username','$email','$securePassword')";
$result = mysqli_query($con,$sqlInsertUser);
As adeneo says, your html form is likely being submitted the standard way before the ajax call is made because you haven't prevent the default behaviour. try the below instead:
Alternatively, you could remove <input type="submit" name="submitCreateUser" class="btn btn-success" id="submitCreateUser" value="Opret!"> and give the id="submitCreateUser" to some other element like a custom button or link. When you click and input tag with the type submit it will submit the accompanying form the normal way by default. This happens before the click handler hears the click so the form is submitted before your code call the ajax. Use a different element for the click and this wont happen
And don't forget for this to work at all, your php file must echo something which will be returned in your html variable, without that html will never be true and nothing will ever happen.
Part of your problem is that your input elements, specifically the ones for the password and password checks both have two separate id tags the first is duplicated and the second is a different id altogether. Also in your jquery, when you try to get the id check value you use another, different, id.
Here is a test page that address all of these issues and works as expected:
http://dodsoftware.com/sotests/createuserajax.html
The test php code:
<?php
if( isset($_POST) )
{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['pass'];
echo 'username --'.$username.', email --'.$email.', password --'.$password;
}
?>
The html code:
<form method="post" action="" id="createForm">
<input type="text" name="createUser" class="form-control" placeholder="Brugernavn*" id="createUser">
<input type="email" name="createUserEmail" class="form-control" placeholder="Email*" id="createUserEmail">
<input type="password" name="createUserPass" id="createUserPass" class="form-control" placeholder="Kodeord*">
<input type="password" name="confirmUserPass" id="confirmUserPass" class="form-control" placeholder="Bekræft Kodeord*" >
<!-- these lines had duplicated id tags-->
<h4 id="newsletterText">Vil du have vores nyhedsbrev?</h4>
<select name="newsletter" id="newsletter" class="form-control">
<option value="yes">Ja tak!</option>
<option value="nej" selected="">Nej tak</option>
</select>
<input type="submit" name="submitCreateUser" class="btn btn-success" id="submitCreateUser" value="Opret!">
</form>
The jQuery code:
<script>
$(document).ready(function() {
$("#submitCreateUser").click(function( event ) { // add event var here
event.preventDefault(); // add this line to stop the form from submitting the normal way before the ajax call
var username = $("#createUser").val();
var email = $("#createUserEmail").val();
var pass = $("#createUserPass").val();
var cPass = $("#confirmUserPass").val(); // you were using "#createUserPassC" here in error
var newsletter = $("#newsletter").val();
var datastring = "username=" + username + "&email=" + email + "&pass=" + pass + "&cPass=" + cPass +"&newsletter=" + newsletter;
$.ajax({
type: "POST",
url: "createuserajax.php",
data: datastring,
success: function(html) {
if (html) { // changed this line from "if (html == 'true')" just for testing
alert(html); // changed this line from "alert(username);" just for testing
} else {
alert('something went wrong!');
}
},
});
});
});
</script>
I have a page where almost every click is handled by delegate().
http://itsneworleans.com/shows/midnight-menu-plus-1/blogs/after-midnight?preview=1
I set up jQuery validate like so
$(document).ready(function(){
$(".commentform form").validate({
rules: {
antispam: { equalToParam: "INO" }
}
});
jQuery.validator.addMethod("equalToParam", function(value, element, param) {
return value == param;
},
"Anti-spam field does not match requested value.");
});
if I check in console with
$.validator.methods['equalToParam']
I get back
function (value, element, param) { return value == param; }
so that looks good.
The validation works on the form submission BUT the equalToParam method has no effect. Only the "required" events occur for it.
The field HTML is
<input name="antispam" type="text" class="required" id="antispam" size="5" />
Where am I going wrong?
EDIT Here is whole form code (generated from PHP script and added to page via AJAX):
<? if ($post = (int) $_POST['pID']) { ?>
<div class="commentform">
<form>
<div class="commenttext">Comment:<br>
<textarea name="comment" class="required"></textarea>
</div>
<div class="commenttext">Your name:<br>
<input type="text" name="name" class="required">
</div>
<div class="commenttext">Your email (will not be publically visible):<br>
<input type="text" name="email" class="required email">
</div>
<div class="commenttext">Type the letters INO here to help us beat spam!<br>
<input name="antispam" type="text" class="required" id="antispam" size="5" />
</div>
<div class="commenttext">
<input type="button" name="submitcomment" class="submitcomment" value="Submit Comment">
<input type="hidden" name="post" value="<?=$post?>">
<? if ($parentComment = (int) $_POST['cID']) { ?>
<input type="hidden" name="parent" value="<?=$parentComment?>">
<? } ?>
</div>
</form>
</div>
<? } ?>
EDIT AGAIN And here's the click delegation code...
$("body").delegate(".submitcomment", "click", function(e) {
e.preventDefault();
var theform = $(this).closest("form");
console.log('Posting comment');
if ($(".commentform form").valid()) {
$.ajax({
type: "POST",
url: "/addComment.php",
data: theform.serialize()
}).done(function(html) {
if (html == 'OK') {
$(theform).html("<div class='commentposted'>Your comment has been received. Thank you. A moderator will review it for public viewing.</div>");
} else {
alert(html);
}
});
}
});
EDIT Here is the code which populates the form into the space where the Reply to Post link was:
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
});
When you need to apply the .validate() method to more than one form, you must wrap it within a jQuery .each().
$(".commentform form").each(function() {
$(this).validate({
rules: {
antispam: {
equalToParam: "INO"
}
}
});
});
EDIT:
You need to initialize the plugin AFTER the form is inserted into the page. Assuming this code properly inserts the form... put your .validate() call as the last item inside...
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
$(".commentform form").validate({ // <- initialize plugin AFTER form is inserted
// your rules & options
});
});
EDIT 2:
Include the equalToParam function someplace on your page within a DOM ready event handler.