Everything works perfectly except the submit button typically takes three to four times before it works. So I'll have the necessary cid number, plug it into the form, and hit submit. It might work the first time, but it also might take me seven attempts. I've got a bit of a deadline on this thing, and I have no idea how to even go about troubleshooting this so any help at all would be hugely appreciated!
So I've got this form:
<form action="" onsubmit="redirect()">
<input type="text" name="val1" id="val1" placeholder="CID (ten digits)">
<br>
<input type="submit" value="Submit" id="submit">
</form>
Which triggers this javascript function:
function redirect() {
var userID = document.getElementById("val1").value;
var userID = userID.replace(/-/g, "");
//alert(userID);
//var userID = "9183179265";
$.ajax({
type: "POST",
url: './getNetworkType.php',
data: "userID=" + userID,
success: function(data) {
//alert(data);
if(data.indexOf("Search") > -1) {
//alert(data.substr(data.length - 10));
window.location = "http://jumpsixdashboard.com/Reporting/display_search.php?cid=" + data.substr(data.length - 10);
}
else {
//alert(data.substr(data.length - 10));
window.location = "http://jumpsixdashboard.com/Reporting/display_report.php?cid=" + data.substr(data.length - 10);
}
}
});
}
Which executes this script:
<?php
$val1 = $_POST['userID'];
$mysqli = new mysqli(HOST, USER, PASSWORD, DATABASE);
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
$sql3 = "SELECT * FROM account_type WHERE cid ='" . $val1 . "'";
$result3 = $mysqli->query($sql3);
if ($result3->num_rows > 0) {
while($row3 = $result3->fetch_assoc()) {
echo $row3["network"];
}
}
?>
I think the problem is in your function onsubmit.
You should try something like this.
Set ID to form to example "myForm". Remove onsubmit from Form.
And add this code. This should send data successfull and avoid the submit that you don't won't.
$("#myForm").submit(function() {
redirect();
return false; // this avoid submit.
});
Related
My requirement is to check whether a text variable is equal or not to an mysql output array.
The mysql output array I have taken as follows,
$connect = mysqli_connect("localhost", "root", "", "newbooks");
$query = "SELECT book_name FROM takenbooks order by ID DESC";
$result = mysqli_query($connect, $query);
while( $row = mysqli_fetch_assoc( $result)){
$avail_books[] = $row['book_name']; // Inside while loop
}
Now I need to check whether user have entered any book from which included in above array.So I have implemented as below.
$(document).ready(function(){
$('#insert_form').on("submit", function(event){
event.preventDefault();
$('#book_name').val()=$book_required;
if(in_array($book_required,$avail_books))
{
alert("Not Available");
}
else{
$.ajax({
url:"books.php",
method:"POST",
data:$('#insert_form').serialize(),
beforeSend:function(){
$('#insert').val("Inserting");
},
success:function(data){
$('#insert_form')[0].reset();
$('#add_data_Modal').modal('hide');
$('#employee_table').html(data);
}
});
}
}
}
But this is not working. Can someone show where I have messed this?
There can be other ways to accomplish what you want.
For example, use the following query:
SELECT count(*) FROM takenbooks where book_name = ?
But for How to check whether a text variable is equal to an Array and based on your original code, the normal way will be to pass the user input data (I believe is $('#book_name').val()) thru ajax to a PHP file to check whether this data is in the array , then return the result back (or do further processing)
For the HTML
<script
src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
<form id=insert_form>
<input type=text id="book_name">
<input type=submit>
</form>
<script>
$(document).ready(function(){
$('#insert_form').on("submit", function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: 'checkdata.php',
data: {data1: $('#book_name').val()},
success: function(data){
alert(data);
},
error: function(xhr, status, error){
console.error(xhr);
}
});
})
})
</script>
For the PHP (checkdata.php)
<?php
if (isset($_POST["data1"])){
$connect = mysqli_connect("localhost", "root", "", "newbooks");
$query = "SELECT book_name FROM takenbooks order by ID DESC";
$result = mysqli_query($connect, $query);
while( $row = mysqli_fetch_assoc( $result)){
$avail_books[] = $row['book_name']; // Inside while loop
}
if(in_array($_POST["data1"],$avail_books)) {
echo "Not Available";
} else {
// Place insert query here
echo "New Record inserted";
}
}
?>
You can first get the list of books once, then write a Javascript array from which to search for the entered book name. (This may not be practical if the list of books changes quite often, or the list is extremely long.)
<?php
$connect = mysqli_connect("localhost", "root", "", "newbooks");
$query = "SELECT book_name FROM takenbooks order by ID DESC";
$result = mysqli_query($connect, $query);
$avail_books = [];
while( $row = mysqli_fetch_assoc( $result)){
$avail_books[] = $row['book_name']; // Inside while loop
}
?>
<!DOCTYPE html>
<html>
<body>
<form id="insert_form">
Book name: <input type="text" name="book_name">
<input type="submit" value="Check for availability">
</form>
<div id="available"></div>
<script>
const avail_books = <?php json_encode($avail_books); ?>;
document.querySelector('#insert_form').addEventListener(function (evt) {
evt.preventDefault();
let book_name = evt.target.book_name.value;
let not_available = (-1 === avail_books.indexOf(book_name))? 'not': '';
document.querySelector('#available').innerHTML = book_name + " is " + not_available + " available.";
});
</script>
</body>
</html>
PHP, on the server, gets the books and stores the list in a PHP array. And when writing out HTML and Javascript use PHP to write out a Javascript avail_books array containing the book names retrieved from the database.
Now the server can send the client the HTML/Javascript code for rendering. Once loaded in the browser, and if you "View Source", the Javascript code will look something like this:
const avail_books = ["To Kill a Mockingbird", "Animal Farm", "Atlas Shrugged"];
With that the user can check the list of books without having to send a query to the server with every inquiry. It's faster and uses less resources.
It might have some Syntax error but thats the basic concept of what you are trying to achieve. Someones enters text, script searches the database and returns the results.
<html>
<body>
<form action="" method="POST">
<input type="text" name"book" required placeholder="Type the name of the Book" />
<input type="submit" value="Search Book" />
</form>
<div><h2>Results:</h2>
<?php
if(isset($_POST['book'] && !empty($_POST['book'])){
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connect = new mysqli("localhost", "root", "", "newbooks");
$stmt = $mysqli->prepare("SELECT ID, book_name FROM takenbooks WHERE book_name LIKE ? ORDER BY ID DESC;");
$stmt->bind_param("s", "%" + $_POST['book'] + "%");
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
echo '<p>Book \"' . $row['book_name'] . '\" was found.<br/></p>';
}
}
?>
</div>
</body>
</html>
I am validating a sign In form through ajax. After successful validation the form is not redirecting to the required page.
Ajax Codes
function login_submit(){
var stat="";
$("#submit").val("Loging in...");
$.ajax({
type: "POST",
url: "php/login.php",
data: {
uname: $("#uname").val(),
pass : $("#pass").val()
},
success: function(result) {
if(result=="parent"){
window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index";
}
else if(result == "sucess_normal"){
window.location.assign("../normal_admin");
}
else if(result == "deactivated account") {
window.location.assign("reactivate_account/");
}
else if(result == "banned account") {
window.location.assign("banned_account/");
}
else{
$("#submit").val("Login");
$("#error_msg").css({color: 'red'});
document.getElementById("error_msg").innerHTML= result;
stat = false;
}
}
});
if(!stat)
return false;
}
The php code
if(isset($_POST['uname']) && isset($_POST['pass'])){
$username = encode($_POST['uname']);
$password = encrypt(encode($_POST['pass']));
// check if entered username and password is in the database
$result = mysqli_query($conn,"SELECT * From admin_account where admin_account.username = '$username' AND admin_account.password = '$password' ");
if($row = mysqli_num_rows($result) == 1){
$found = mysqli_fetch_array($result);
if($found['state'] == 1){
$account_id = $found['account_id'];
setcookie("admin_id", $account_id, time() + (86400 * 30), "/");
$_SESSION['admin_id'] = $account_id;
$result1 = mysqli_query($conn,"SELECT role_id From admin where admin_id = '$account_id'");
$found1 = mysqli_fetch_array($result1);
$_SESSION['account_type'] = $found1['role_id'];
if($found1['role_id'] == "1"){
echo "parent";
//header("Location: http://localhost:90/auction/augeo/admin/parent_admin/index");
}else{
echo "sucess_normal";
}
}
elseif($found['state'] == 2){
echo "banned account";
}
else{
$_SESSION['deactivated_id'] = $found['account_id'];
echo "deactivated account";
}
}
else{
echo "Incorrect Username or Password";
}
}
I have tried all I could do but to no avail. I want to check if result=="parent" and if result=="parent" it should redirect to window.location = "http://localhost:90/auction/augeo/admin/parent_admin/index"; but instead it is echoing out parent.
You say "it is echoing out parent". But this should never happen with the AJAX code you supplied.
So I'm suspecting that you have a form that's running its own default submit, and that is what you're seeing.
You may want to check out this answer:
$('#idOfYourForm').submit(function() {
var $theForm = $(this);
// This is a button or field, right? NOT the form.
$("#submit").val("Logging in...");
$.post(
'php/login.php',
{
uname: $("#uname").val(),
pass : $("#pass").val()
}
).done(function(result) {
// check the result
alert("Server said: " + result);
});
// prevent submitting again
return false;
});
You get the button with
$("#submit")
This is ok, but if the button is defined as:
<input type="submit" id="submit" value="..." />
You'll get a subsequent submit of the form the button is defined in.
To avoid this, a far easier solution to the other suggested, is to not use a submit button at all. Instead, use a simple action button. These are two examples, the second of which is probably better because it is easier to design with bootstrap/HTML5/CSS...
<input type="button" id="submit" value="..." />
or better:
<button type="button" id="submit">...</button>
In case of slow server/network, you'll probably want to aid AJAX usability by disabling the button:
$("#submit").val("Logging in...").prop("disable", "disable");
This helps avoiding multiple submits when the server is slow and the user impatient.
So, I'm new to using PHP but want to add whatever a user enters into this form into a database.
However, I'm getting an error for each index of name, role, and wage. It seems that it isn't picking that up.
HTML:
<form id="input" name="input" action="employees.php" method="post">
<div id="boxes">
<input type="text" name="name" placeholder="Input" class="name" required><br/>
<input type="text" name="role" placeholder="Role" class="role" required><br/>
<input type="number" step="any" name="wage" placeholder="Wage" class="wage" required>
<br />
<br />
</div>
<button type="submit" onsubmit="return ajaxFunction()" class="button">Submit</button>
<button type="reset" class="button">Reset</button>
</form>
PHP:
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "employees";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br/>";
$name2 = $_POST['name'];
$role2 = $_POST['role'];
$wage2 = $_POST['wage'];
if (mysql_query("INSERT INTO employees VALUES ('$name2', '$role2', '$wage2')"))
echo "Successfully inserted";
else
echo "Insertion failed";
$conn->close();
?>
I also have some javascript set up to catch the values of each field and to send them to the PHP file. I'm probably doing something very wrong... but anyway here's the JS:
function ajaxFunction() {
var name = $('.name').val();
var role = $('.role').val();
var wage = $('.wage').val();
var dataString = '&name1' + name + '&role1' + role + '&wage1' + wage;
$.post('employees.php', {name1:name, role1:role, wage1:wage}, function(data){
$('#main').html(data);
});
if (name == '' || role == '' || wage == '') {
alert("Please fill in all fields.");
} else {
$.ajax({
type: "POST",
url: "employees.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
}
In your Ajax dataString is
var dataString = '&name1' + name + '&role1' + role + '&wage1' + wage;
But in your PHP
$name2 = $_POST['name'];
$role2 = $_POST['role'];
$wage2 = $_POST['wage'];
Should be
$name2 = $_POST['name1'];
$role2 = $_POST['role1'];
$wage2 = $_POST['wage1'];
The undefined error means that your data is not found, this is happening because your php is looking for a POST index of "name" whereas javascript is sending "name1".
There are a few issues with the setup that can be greatly improved here.
Firstly the onsubmit needs moved into the form tag.
<form onsubmit="return isFormValid()" id="input" name="input" action="employees.php" method="post">
Secondly you don't actually need to actually make an ajax request from Javascript because the return on submit is saying if the returned value of the js function is true submit the form otherwise don't. Therefore we just need to return a true or false based on form validation.
Here is the updated JS function.
function isFormValid(){
var name = $('.name').val(),
role = $('.role').val(),
wage = $('.wage').val(),
data = [name, role, wage],
isValid = true;
data.forEach(function(el){
if( isValid && !el.trim() ){
alert("Please fill in all fields.");
isValid = false;
}
});
return isValid;
}
There are also some security concerns regarding MySQL injection from how the form data is being entered into the database without being escaped.
A quick solution is to add a basic PHP method to escape the strings before hitting the database.
// add at the top of your php file
function escape($value){
return mysql_real_escape_string($value);
}
// then update your variables
$name2 = escape($_POST['name']);
$role2 = escape($_POST['role']);
$wage2 = escape($_POST['wage']);
You can read more about mysql injection and how to prevent it here:
http://php.net/manual/en/function.mysql-real-escape-string.php
EDIT ---------------------------
I've simplified the JS and removed the token issue you were having. If you add more input fields you can simply add a new variable to store it's value and add that variable name to the data array.
I've also updated the function name in both the JS and the html as it relates more to the purpose of the task.
Here is a working example:
http://codepen.io/davidbattersby/pen/LVabQe
obviously the php file doesn't exist so will point to a blank page if submission passes validation, it will alert and not send if invalid.
Code Logic:
1) User types in username and password, user clicks submit.
2) jQuery script pulls the php script below.
3) jQuery determines which php value is returned.
4) if value 1 is returned, jquery and php will process what's in the if statement.
5) if value 0 is returned, jquery and php will process whats in the else statement.
How do I successfully make the code below work alongside the logic above? I can't seem to make a connection in my mind.
class1.php
$email = mysql_real_escape_string(strip_tags($_POST["username"]));
$password = sha1($_POST["password"]);
$sql = "SELECT * FROM users WHERE username = '{$email}' AND password = '{$password}'";
$result = mysql_query($sql) or exit("ERROR: " . mysql_error() . "<br>IN QUERY: " . $sql);
if (mysql_num_rows($result) > 0) {
return 1;
$row = mysql_fetch_array($result);
$_SESSION["userid"] = $row['user_pid'];
} else {
return 0;
$userid_generator = uniqid(rand(), false);
mysql_query("INSERT INTO users (user_pid, email, password, datetime_registered, is_leader) VALUES ('$userid_generator', '{$email}', '{$password}', NOW(), 'no')");
$id = mysql_insert_id();
$leaders = mysql_query("SELECT * FROM users WHERE is_leader LIKE '%yes%'");
while($rows = mysql_fetch_array($leaders)) {
if ($rows['is_leader'] == 'yes') {
$leader_id = $rows['user_pid'];
mysql_query("INSERT IGNORE INTO friends (node1id, node2id, friends_since, friend_type)
VALUES('$leader_id', '$userid_generator', NOW(), 'full')");
echo "new user created and logged in";
}
$_SESSION["userid"] = $userid_generator;
}
}
?>
index.html:
<script src="http://code.jquery.com/jquery-latest.js"></script>
<style type="text/css">
.loading {
float:right;
background:url(img/ajax-loader.gif) no-repeat 1px;
height:28px;
width:28px;
display:none;
}
</style>
<script type="text/javascript">
$(document).ready(function() {
$('#submit').click(function () {
var username = $('input[username=username]');
var password = $('input[password=password]');
var data = 'name=' + name.val() + '&email=' + email.val() + '&website='
+ website.val() + '&comment=' + encodeURIComponent(comment.val());
$('.text').attr('disabled','true');
$('.loading').show();
$.ajax({
url: "processing/class1.php",
type: "POST",
//pass the data
data: data,
//Do not cache the page
cache: false,
//success
success: function (html) {
//if process.php returned 1/true (send mail success)
if (html==1) {
alert('success');
//if process.php returned 0/false (send mail failed)
} else { alert('failure');
}
});
return false;
});
});
</script>
<input type="text" id="username" name="username" />
<input type="password" id="password" name="password" />
<input type="submit" id="submit" />
<div class="loading"></div>
<div id="display"></div>
Ajax is effectively a "blind client". So, think of what you would see if you were to manually view the php script, and interpret that as what your ajax callback would be parsing.
Having said that, the "0/1" return you're looking for is dependent on one (of many) echos going on in your script (most notably the following):
echo "new user created and logged in";
if you want the ajax callback to recognize a 0/1, this would need to only echo a "1" (not verbiage), where as errors would simply return a "0" (such as your or exit("ERROR...).
EDIT
Also, looking further, your var data = 'name=' component (assuming you want it to align with the PHP $_POST["username"]) should probably be renamed to var data ='username=' (the data property of the ajax call is what' populating your PHP's $_POST variables, so names need to align).
I am getting no responses when I try to fire this ajax request from jquery:
/********************************
CHANGE USER SETTINGS
*********************************/
$(".submitUserSetting").live('click', function() {
//get values
var department = $("#us_department").val();
var sortOrder = $("input[#name=us_sortOrder]:checked").val();
$.ajax({
type: "POST",
url: "lib/includes/updateUserSettings.php",
data: "empname=" + empname + "&department=" + department + "&sortOrder=" + sortOrder,
success: function(data) {
alert(data);
}
});
});
I mean nothing. No javascript errors, no errors on the MySQL query, not even POST data in the console.log. Just a taunting batch o' silence. Even if I comment out all the code in the PHP page and just echo the data I sent over to it, nothing. Here's the PHP page (the class exists, the functions work, I'm using them on a dozen or so other pages)
<?php
require_once("../classes/mysqlconnect.php");
$db = new dbconnect();
$db->makeConnections("TimeSheetManager");
$empname = $_POST['empname'];
$department = $_POST['department'];
$sortOrder = $_POST['sortOrder'];
//get the department id
$dQuery = "SELECT id FROM departments WHERE department = '" . $department . "'";
$dResults = $db->getResults($query);
if (mysql_num_rows($dResults) > 0) {
while($rows = mysql_fetch_array($dResults) {
$deptID = $rows['id'];
}
}
//update database
$query = "UPDATE users SET `department` = '" . $department "', `displayOrder` = '" . $sortOrder . "' WHERE username = '" . $empname . "'";
$results = $db->getResults($query);
if ($results) {
echo "!success";
} else {
echo "!fail";
}
?>
Here's the form code:
<div id="userSettingsForm">
<form name="userSetting">
<p><label for="sortOrder">Display Order:</label></p>
<p class="userSettingElement">Oldest First <input type="radio" name="us_sortOrder" value="asc"> Newest First <input type="radio" name="us_sortOrder" value="dsc"></p>
<p><label for="us_department">Department:</label></p>
<p class="userSettingElement">
<select id="us_department" name="us_department">
<option value="null">Select A Department</option>
<?php
$query = "SELECT * FROM departments";
$results = $db->getResults($query);
while($row = mysql_fetch_array($results)){
if (count($results) > 0) {
//get department and id
$department = $row['department'];
$deptID = $row['id'];
print "<option value=\"" . $deptID . "\">" . $department . "</option>";
}
}
?>
</select>
</p>
<p>Submit</p>
</form>
</div>
Thanks for all the help and suggestions. I rebooted Firefox and the error was in empname, I wasn't setting it (doh!). Beluga was on to that but it took a bit for it to dawn on me. Wish I could award everyone with the answer.
How can you tell you're not getting an error? Add an error handler to your .ajax() call:
$.ajax({
type: "POST",
url: "lib/includes/updateUserSettings.php",
data: "empname=" + empname + "&department=" + department + "&sortOrder=" + sortOrder,
success: function(data) {
alert(data);
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
OK, some more investigation shows that the error is actually in a peculiar combination of pieces of code that you are using.
Apparently, href="javascript:void(0)" prevents event propagation. The event is triggered on the element itself (so handlers bound with .click(fn) work) but ancestor elements are not notified of the event.
Since you are using the .live() method, which relies upon event propagation, this doesn't work here.
I would suggest the following instead:
Submit
and JS:
$(".submitUserSetting").live('click', function(e) {
e.preventDefault(); // disable the link action
[snip]
});
See jsFiddle demonstrating this.
The issue is the way you send the data.
Try enclosing the property in { } 's and changing the variable format to
{ "propertyName" : "value", "propertyName" : "value" }
i.e
data: { "empname" : empname ,"department" : department, "sortOrder" :sortOrder }
alternatively if it is a form you can even say
data : { $("#form").serialize() }
you need to return some value in your php function
data: "empname=" + empname + "&department=" + department + "&sortOrder=" + sortOrder,
define empname in your call which is missing.
this gives you Uncaught ReferenceError