I am working on this script that will filter sql results based on the which checkboxes are checked. My table is set up like so..
id venue imageurl showingads 2kandunder 2kto4k 4kandup
1 venue1 myurl.com yes yes
2 venue2 myurl.com yes yes
3 venue3 myurl.com no yes
4 venue4 myurl.com yes yes
All code is on the same page. Here is the html..
<form id="form" method="post" action="">
<input type="checkbox" name="2kandunder" class="checkbox" <?=(isset($_POST['2kandunder'])?' checked':'')?>/> 2kandunder<br>
<input type="checkbox" name="2kto4k" class="checkbox" <?=(isset($_POST['2kto4k'])?' checked':'')?>/> 2k to 4k<br>
<input type="checkbox" name="4kandup" class="checkbox" <?=(isset($_POST['4kandup'])?' checked':'')?>/> 4k and up<br>
</form>
Javascript code...
<script type="text/javascript">
$(function(){
$('.checkbox').on('change',function(){
$('#form').submit();
});
});
</script>
and php...
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST["2kandunder"])) {
$arguments[] = "`2kandunder` = 'yes'";
}
if (isset($_POST["2kto4k"])) {
$arguments[] = "`2kto4k` LIKE 'yes'";
}
if (isset($_POST["4kandup"])) {
$arguments[] = "4kandup LIKE '%yes%'";
}
if(!empty($arguments)) {
$str = implode(' or ',$arguments);
$qry = "SELECT id, venue, imageurl FROM ads where " . $str . "";
$paginate = new pagination($page, $qry, $options);
} else {
//Whatever happens when there's none checked.
$sql = "SELECT id, venue, imageurl FROM ads WHERE `showingads` = 'yes'";
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<table class='tablebox' width='940' border='1' cellspacing='5'>
<tr><td width='75'>".$row["venue"]."</td></tr>
<tr>
<td width='10'><a href='post_click.php?id=".$row["id"]."'> <img src='".$row["imageurl"]."'></a></td>
</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
When I run this page else query displays which is what I want to happen when page first loads. But when I check any of the checkboxes nothing happens. Here is entire code as it is on page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="JavaScript" type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
</head>
<html>
<body>
<form id="form" method="post" action="">
<input type="checkbox" name="2kandunder" class="checkbox" <?=(isset($_POST['2kandunder'])?' checked':'')?>/> 2k and under<br>
<input type="checkbox" name="2kto4k" class="checkbox" <?=(isset($_POST['2kto4k'])?' checked':'')?>/> 2k to 4k<br>
<input type="checkbox" name="4kandup" class="checkbox" <?=(isset($_POST['4kandup'])?' checked':'')?>/> 4k and up<br>
</form>
<script type="text/javascript">
$(function(){
$('.checkbox').on('change',function(){
$('#form').submit();
});
});
</script>
<?php
$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "mydb";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if (isset($_POST["2kandunder"])) {
$arguments[] = "`2kandunder` = 'yes'";
}
if (isset($_POST["2kto4k"])) {
$arguments[] = "`2kto4k` LIKE 'yes'";
}
if (isset($_POST["4kandup"])) {
$arguments[] = "4kandup LIKE '%yes%'";
}
if(!empty($arguments)) {
$str = implode(' or ',$arguments);
$qry = "SELECT id, venue, imageurl FROM ads where " . $str . "";
$paginate = new pagination($page, $qry, $options);
} else {
//Whatever happens when there's none checked.
$sql = "SELECT id, venue, imageurl FROM ads WHERE `showingads` = 'yes'";
}
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<table class='tablebox' width='940' border='1' cellspacing='5'>
<tr><td width='75'>".$row["venue"]."</td></tr>
<tr>
<td width='10'><a href='post_click.php?id=".$row["id"]."'> <img src='".$row["imageurl"]."'></a></td>
</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>
My first thoughts is 1. The javascript isn't executing at all? 2. My $arguments is formatted wrong for how I have the database set up? (I have 3 different variations for the arguments to try and test out different formats to see if I could get one to work)
Note: The php portion from tutorial I learned from had the argument like if (isset($_POST["2kandunder"]). I have it like this: if (isset($_POST["2kandunder"])) with the extra parenthesis at the end because I was getting a syntax error for each if statement. If that could be the problem why was I getting syntax errors for each if statement line?
All this code and blabbering but I feel like I am close. Can someone PLEASE help me figure out what the problem is?
EDIT
columns are set up like this..
Field Type Null Key Default Extra
id int(5) NO PRI NULL auto_increment
venue varchar(100) NO NULL
imageurl varchar(150) NO NULL
showingads varchar(5) NO NULL
2kandunder varchar(5) NO NULL
2kto4k varchar(5) NO NULL
4kandup varchar(5) NO NULL
UPDATE
So I have the checkboxes working now but now when I load the page and click the top checkbox (2kandunder) it returns 0 results. The else sql still works for when no checkboxes are checked. I changed the first if statement to
if (isset($_POST["2kandunder"])) {
$arguments[] = "`showingads` = 'yes'";
which should make it the same query as the else sql query when the first (2kandunder) box is checked. Still 0 results shows. So I echoed the $qry to display what query was being run when the first checkbox is checked and it is the exact same as the else $sql query but still returns 0 results? How is this possible if that exact same query works for the else query?
Last Update
The problem was the if $results it was only showing results for the sql query thanks for anyone that helped!
http://api.jquery.com/on/
You are right. javascript isn't executed at all. You are using jquery 1.4.1. But "on" is available since 1.7
I hope this will help you.
Related
I want to do text autocomplete using php and html..
i have tried the below code
<?php
$connection = mysqli_connect("localhost", "root", "pass", "data") or die("Error " . mysqli_error($connection));
$sql = "select value from fin";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dna = array();
while ($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
$jj = array_unique($dna);
print_r(array_values($jj));
?>
result is
my html
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/
themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4
/jquery-ui.js">
</script>
</head>
<body>
<form name="vinform" method="get"> <input type="text" name="editor" autocomplete="on"> <input type="submit" value="Show" id="display"> </form>
<div id="div1"></div>
<script type="text/javascript">
$(function() {
$('#div1').autocomplete({
source: "auto.php"
});
});
</script>
</body>
it doesn't show the words from mysql when i type some word in the text field ..i have to show the related words from mysql based on the text field input,when i type a character in the text field..can anyone help me to solve the issue in my code?
tried with Ajax
var se = null;
$(function () {
var minlength = 1;
$("#editor").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
if (se != null)
se.abort();
se = $.ajax({
type: "GET",
url: "auto.php",
data: value,
dataType: "text",
success: function(msg){
if (value==$(that).val()) {
}
}
});
}
});
});
php
<?php
if(isset($_GET['editor']))
{
$con=mysqli_connect("localhost","root","admin321","data");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name=$_GET['editor'];
$sql = "select value from fin where value LIKE '%".$name."'";
$result = mysqli_query($connection, $sql) or
die("Error " . mysqli_error($connection));
$dna = array();
while($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
$jj=array_unique($dna);
print_r ( $jj);
}
?>
no autocomplete action
With option 1 (Jquery UI autocomplete) and try something like that
<?php
$connection = mysqli_connect("localhost", "root", "pass", "data") or die("Error " . mysqli_error($connection));
$sql = "select value from fin";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dna = array();
while ($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
echo json_encode($dna);
?>
Jquery UI autocomplete state about source option
String: When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results. For example, if the source option is set to "http://example.com" and the user types foo, a GET request would be made to http://example.com?term=foo. The data itself can be in the same format as the local data described above.
You can use AJAX and Jquery..in html code call the function on keyup event and send data using ajax request after that get data from database using LIKE query and display it..
in input add id="editor"
<input type="text" id="editor" name="editor" autocomplete="on">
I have a html form where a user is expected to select a keyword that must not exist in the database. Just like checking if a domain exist.
If the keyword exist, i want to echo on the same page (on top of the input field.) that the keyword is available or not.
Edit 1
<?php
//Start session
session_start();
//Include database connection details
require_once('config.php');
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
//Connect to mysql server
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
//Select database
$db = mysql_select_db(DB_DATABASE);
if(!$db) {
die("Unable to select database");
}
//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
$str = #trim($str);
if(get_magic_quotes_gpc()) {
$str = stripslashes($str);
}
return mysql_real_escape_string($str);
}
//Sanitize the POST values
$email = clean($_POST['email']);
//Input Validations
if($email == '') {
$errmsg_arr[] = 'Email missing';
$errflag = true;
}
//Check for duplicate login ID
if($email != '') {
$qry = "SELECT * FROM members WHERE email='$email'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
$errmsg_arr[] = 'Email already in use';
$errflag = true;
}
#mysql_free_result($result);
}
else {
die("Query failed");
}
}
//If there are input validations, redirect back to the registration form
if($errflag) {
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
session_write_close();
header("location: register-form.php");
exit();
}
if() {
header("location: samepage.php");
exit();
}else {
die("Query failed");
}
?>
Here is the html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Login Form</title>
<link href="loginmodule.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php
if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) {
echo '<ul class="err">';
foreach($_SESSION['ERRMSG_ARR'] as $msg) {
echo '<li>',$msg,'</li>';
}
echo '</ul>';
unset($_SESSION['ERRMSG_ARR']);
}
?>
<form id="loginForm" name="loginForm" method="post" action="register-exec.php">
<table width="300" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<th>First Name </th>
<td><input name="email" type="text" class="textfield" id="email" /></td>
</tr>
<td><input type="submit" name="Submit" value="Register" /></td>
</tr>
</table>
</form>
</body>
</html>
I don't know what to do in the last if statement of the php. Can anyone help me with this code?
Edit 2
<?php
//Start session
session_start();
require_once('config.php');
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(count($_POST) > 0){
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
$email = $conn->real_escape_string($_POST['email']);
if($email == '') {
$errmsg_arr[] = 'Email missing';
$errflag = true;
}
$sql = "SELECT * FROM members WHERE email = '$email'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$errmsg_arr[] = 'Email already in use';
$errflag = true;
}
else
{
$errflag = false; // if record not exist.
}
}
$conn->close();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Login Form</title>
<link href="loginmodule.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php
if($errflag){
echo implode(",", $errmsg_arr); // if any error found print error array and use your error stuff like redirection as you are using.
}
else{
echo "Available"; // else print Available message or use your stuff.
}
?>
<form id="loginForm" name="loginForm" method="post" action="register-exec.php">
<table width="300" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<th>Email </th>
<td><input name="email" type="text" class="textfield" id="email" /></td>
</tr>
<td><input type="submit" name="Submit" value="Check" /></td>
</tr>
</table>
</form>
</body>
</html>
Here is the basic example of your code by using MYSQLi Object Oriented:
<?php
//Start session
session_start();
//Include database connection details
require_once('config.php');
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if(count($_POST) > 0){
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$errflag = false;
$email = $conn->real_escape_string($_POST['email']);
if($email == '') {
$errmsg_arr[] = 'Email missing';
$errflag = true;
}
$sql = "SELECT * FROM members WHERE email = '$email'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$errmsg_arr[] = 'Email already in use';
$errflag = true;
}
else
{
$errflag = false; // if record not exist.
}
if($errflag){
echo implode(",", $errmsg_arr); // if any error found print error array and use your error stuff like redirection as you are using.
}
else{
echo "Available"; // else print Available message or use your stuff.
}
}
$conn->close();
?>
Update:
Don't know why are you using $_SESSION for print error, you just need to replace this statement with $_SESSION statement inside your HTML.
if($errflag){
echo implode(",", $errmsg_arr); // if any error found print error array and use your error stuff like redirection as you are using.
}
else{
echo "Available"; // else print Available message or use your stuff.
}
Update 2:
You just need to check error array is set or not and than use your condition like:
<?php
if(isset($errmsg_arr)){
if(count($errmsg_arr) > 0){
echo implode(",", $errmsg_arr); // if any error found print error array and use your error stuff like redirection as you are using.
}
else{
echo "Available"; // else print Available message or use your stuff.
}
}
?>
Basic and Complete Example:
<?php
//Start session
session_start();
require_once('config.php');
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$errflag = false;
$successflag = false;
if(count($_POST) > 0){
//Array to store validation errors
$errmsg_arr = array();
//Validation error flag
$email = $conn->real_escape_string($_POST['email']);
if($email == '') {
$errmsg_arr[] = 'Email missing';
$errflag = true;
}
$sql = "SELECT * FROM members WHERE email = '$email'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$errmsg_arr[] = 'Email already in use';
$errflag = true;
}
else
{
$successflag = true; // if record not exist.
}
}
//$conn->close();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Login Form</title>
<link href="loginmodule.css" rel="stylesheet" type="text/css" />
</head>
<body>
<?php
if($errflag){
echo implode(",", $errmsg_arr); // if any error found print error array and use your error stuff like redirection as you are using.
}
if($successflag){
echo "Available";
}
?>
<form id="loginForm" name="loginForm" method="post" action="register-exec.php">
<table width="300" border="0" align="center" cellpadding="2" cellspacing="0">
<tr>
<th>Email </th>
<td><input name="email" type="text" class="textfield" id="email" /></td>
</tr>
<td><input type="submit" name="Submit" value="Check" /></td>
</tr>
</table>
</form>
</body>
</html>
Side Note:
Use mysqli_* or PDO, because mysql_* deprecated and closed in PHP 7.
I have implemented search box for my website by using php, html and jquery.
Firstly, I have created a database,
using php I have sorted the values and
using jquery and html I have shown the search result in a div below the search box.
My problem is that I am not able to select the result using down or up key, for this I also tried to make the result in list or drop box in php.
Please correct me if I am wrong some where. Below is the code which is I am using.
<body>
<h1>Search web page</h1>
<form action="search_demo.php" method="post" >
<input type="text" name="search" placeholder="search here" onkeydown="searchq();" />
<input type="submit" value=">>" />
<div id="output" style="z-index: 10; position: absolute ; background-color: yellow;">
</div>
<div id="stable" style="">
</div>
</form>
</body>
<script>
function searchq(){
var searchtxt = $("input[name='search']").val();
$.post("search_demo12.php", {searchval : searchtxt}, function(output) {
$("#output").html(output);
});
}
</script>
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST['searchval'])){
$search = $_POST['searchval'];
// $search = preg_replace("#[^0-9a-z]#i","",$search);
$pieces = explode(" ", $search);
$pieces_count = count($pieces);
// $pieces[0] = preg_replace("#[^0-9a-z]#i"," ",$pieces[0]);
// $pieces[1] = preg_replace("#[^0-9a-z]#i"," ",$pieces[1]);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select * from search_demo where fname like '%$search%' or lname like '%$search%'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$pname = $row['fname'];
$purl = $row['lname'];
//if($piece == $row['brand']){
$output .= '<option>'.$pname.' '.$purl.'</option>';
}
}
echo ($output);
Do you mean you cannot select results using up and down keys?
I think it is because you are not wrapping options in select list . Do this
while($row = $result->fetch_assoc()){
$pname = $row['fname'];
$purl = $row['lname'];
//if($piece == $row['brand']){
$output .= '<option>'.$pname.' '.$purl.'</option>';
}
echo "<select>".$output."</select>";
In this case I think that it's better to use onkeyup() JavaScript function as you are implementing live search and need output to be changed dynamically..
New to this group. Need tip to ignore empty search box queries. The following code works fine but when I click the search button with nothing in the text field, it gives me all my page links as results. I would want no action for an empty box search...thanks in advance folks!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<form action='./search.php' method='get'>
<input type='text' name='k' size='15' value='<?php echo isset($_GET['k']) ? $_GET['k'] : ""; ?>' placeholder=' ' />
<input type="image" src="images/magnifier.png" width="14" height="14" border="0" >
</form>
<h2>Search Results</h2>
<hr />
<?php
$k = isset($_GET['k']) ? $_GET['k'] : "";
$terms = explode(" ", $k);
$query = "SELECT * FROM search WHERE ";
$i = 0;
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
// connect to DB
mysql_connect("localhost", "root", "mypwd");
mysql_select_db("busqueda");
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$title = $row['title'];
$description = $row['description'];
$keywords = $row['keywords'];
$link = $row['link'];
echo "<h2><a href='$link'>$title</a></h2>
$description<br /><br />";
//empty query variable before coming back to home page
$k = null;
}
}
else
echo "No results found for \"<b>$k</b>\"";
//empty query variable before coming back to home page
$k = null;
//disconnect from DB
mysql_close();
?>
</body>
</html>
Just don't do anything if you get an empty query
if (empty($_GET['k']) or trim($_GET['k']) == ''){
exit;// or something
}
also you can prevent the form from submitting an empty query with the required attribute
<form action='./search.php' method='get'>
<input type='text' name='k' required size='15' value='<?php echo isset($_GET['k']) ? $_GET['k'] : ""; ?>' placeholder=' ' />
<input type="image" src="images/magnifier.png" width="14" height="14" border="0" >
</form>
before getting to
$terms = explode(" ", $k);
check if $k is not empty
if($k !=''){
// put here your query structure and database stuff
// now we are sure that there is some content in the k field
}
Just wrap the rest of your code after defining $k with and if statement like so:
if($k != ""){
//execute search
}
If required='true' is not enough (at the client-side), as you might want to prevent a submit (codes assumes jQuery usage) and do some stuff:
$(document).ready(function() {
$('form').submit(function() { // replace by form #id selector
if ($(this).find('[name=k]').val().trim() == '') {
return false; // do other stuff, as warn user
}
});
});
My test.php page is as under:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<h3>Setting</h3>
<form>
<p>Name:<input type="text" id="updatetherone1"/></p>
<p>Email:<input type="text" id="updateotherone2"/></p>
<p><input id="updateone" type="button" value="Save"/></p>
</form>
<span id="updateotherotherone"></span>
<script src="js/jquery.js"></script>
<script src="js/ajax.js"></script>
</body>
</html>
My ini.php page is as under:
<?php
session_start();
$_SESSION['state'] ='2';
$conn=new mysqli('localhost','root','','people');
?>
My test1.php page is as under:
<?php
include 'ini.php';
if (isset($_POST['name'], $POST['email'])){
$name = mysqli_real_escape_string(htmlentities($POST['name']));
$email = mysqli_real_escape_string(htmlentities($POST['email']));
$update = mysqli_query("UPDATE state SET Name='$name', email='$email' WHERE Id=".$_SESSION['state']);
if($update === true){
echo 'Setting have been updated.';
}else if ($update === false){
echo 'There was an error updating your setting.';
}
}
?>
My ajax.js page is as under:
$('[id=updateone]').click(function(){
var name=$('[id=updateotherone1]').val();
var email=$('[id=updateotherone2]').val();
$('[id=updateotherotherone]').text('Loading...');
$.post('test1.php',{name:name,email:email},function(data){
$('[id=updateotherotherone]').text(data);
});
});
Ultimately code is not working nor do it is displaying any error, I suspect there is something wrong with test1.php page, can anybody guide please:
Take note that the procedural interface of mysqli_query(), the first parameter need the connection.
$update = mysqli_query($conn, "UPDATE state SET Name='$name', email='$email' WHERE Id=".$_SESSION['state']);
If these are typos $POST, then it should be fixed in your code. It's supposed to read as $_POST. (unless its a typo on the question.) It is a superglobal.
I suggest you just use the object oriented interface. So that you wouldn't need to add it everytime:
<?php
include 'ini.php';
if (isset($_POST['name'], $_POST['email'])){
$name = $conn->real_escape_string(htmlentities($_POST['name']));
$email = $conn->real_escape_string(htmlentities($_POST['email']));
$update = $conn->query("UPDATE state SET Name='$name', email='$email' WHERE Id = " . $_SESSION['state']);
if($conn->affected_rows > 0) {
echo 'Setting have been updated.';
} else {
echo 'There was an error updating your setting.';
}
}
?>
Might as well use prepared statements since mysqli supports it:
if (isset($_POST['name'], $_POST['email'])){
$name = htmlentities($_POST['name']);
$email = htmlentities($_POST['email']);
$sql = 'UPDATE state SET Name = ?, email = ? WHERE Id = ?';
$update = $conn->prepare($sql);
$update->bind_param('ssi', $name, $email, $_SESSION['state']);
$update->execute();
if($update->affected_rows > 0) {
echo 'Setting have been updated.';
} else {
echo 'There was an error updating your setting.';
}
}
On the JS part:
You also have a typo on the form id and the JS:
<p>Name:<input type="text" id="updatetherone1"/></p> <!-- missing o -->
var name=$('[id=updateotherone1]').val();
Should be: <p>Name:<input type="text" id="updatetherone1"/></p>
Sidenote:
If you want to avoid those kind of silly typos, just id and label them properly. Example:
<p>Name:<input type="text" id="name_field"/></p>
<p>Email:<input type="text" id="email_field"/></p>