I've got a jQuery $.post script which isn't passing all of the data to the php script it's calling. It worked fine when I only passed two parameters into the data field, but now that I've got more than just two, it's not working any more. The console is showing the values of the fields, but the data isn't being inserted into the database for some reason.
HTML Form
<fieldset for="center">
<label>Center:</label>
<div class="select" name="center" id="center">
<div class="arrow"></div>
<div class="option-menu">
<?php
$query = "SELECT * FROM $centers";
$result = mysqli_query($connect, $query);
$center_name;
while($row = mysqli_fetch_assoc($result)){
$center_name = "{$row['center']}";
echo "<div class='option'>" .$center_name ."</div>";
}
?>
</div>
</div>
</fieldset>
<fieldset for="initials">
<label>Initials:</label>
<input type="text" name="initials" id="initials" />
</fieldset>
<fieldset for="recurrent">
<label>Type:</label>
<div class="select" name="recurrent" id="recurrent">
<div class="arrow"></div>
<div class="option-menu">
<?php
$query = "SELECT * FROM $recurrent";
$result = mysqli_query($connect, $query);
while($row = mysqli_fetch_assoc($result)){
$type = "{$row['type']}";
echo "<div class='option'>" .$type ."</div>";
}
?>
</div>
</div>
</fieldset>
PHP Script
ob_start();
require("../includes/header.php");
if($_SERVER["REQUEST_METHOD"] == "POST"){
$center = $_POST["center"];
$recurrent = $_POST["recurrent"];
$initials = $_POST["initials"];
$query = "INSERT INTO `$scenarios`(`initials`, `center`, `recurrent`) VALUES('" .$initials ."', " .$center ."', '" .$recurrent ."')";
mysqli_query($connect, $query);
}
ob_clean();
echo json_encode(array("success" => 1));
jQuery Script
$("input[id='save']").on("click", function(){
var initials = $("#initials").val();
var center = $("#center_menu").val();
var recurrent = $("#recurrent_menu").val();
console.log(initials);
console.log(center);
console.log(recurrent);
$.post("../php/processing.php", {initials: initials, center: center, recurrent: recurrent}, function(response){
if(response.success == "1"){
}
}, "json");
})
First, confirm that you aren't getting the proper values back by writing out the values of the three post variables. Be sure that its a problem with the jquery post.
If it is a jquery problem, which parameter isn't getting passed back?
In your php script, the single quotes are the wrong type of single quotes.
Change:
$query = "INSERT INTO `$scenarios`(`initials`, `center`, `recurrent`) VALUES('" .$initials ."', " .$center ."', '" .$recurrent ."')";
To:
$query = "INSERT INTO '$scenarios'('initials', 'center`, 'recurrent') VALUES('" .$initials ."', " .$center ."', '" .$recurrent ."')";
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
I am trying to create a live search using ajax, jquery, php and mysql.
The user enter some inputs, it send the search to form_livesearch.php. I got that part worked. Else if the input is empty, then display other query. (I need help with this part)
<div id="container" class="col-md-12">
<div class="row">
<h2>Quick Search</h2>
<input class='form-control' type="text" id='live_search' placeholder='Search our inventory'>
<br>
<br>
<h2 class="" id="searchresult">
</h2>
</div>
</div>
$(document).ready(function(){
$("#live_search").keyup(function(){
var input = $(this).val();
if(input != ""){
$.ajax({
url:"form_livesearch.php",
method:"POST",
data:{input:input},
success:function(data){
$("#searchresult").html(data);
$("#searchresult").css("display","block");
}
});
} else {
// If the input field is empty
// How display another php query here?
}
});
});
Here is the php and mysql I am trying to display when the input field is empty.
<?php
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_category = 'policy' ORDER BY id ASC";
$result = mysqli_query($db,$query);
if(!$result){
die("Query Failed " . mysqli_error($db));
}
if(mysqli_num_rows($result) > 0){
?>
<h3>Policies</h3>
<ul>
<?php
while($row = mysqli_fetch_assoc($result)){
$id = $row['id'];
$s_url = $row['s_url'];
$s_name = $row['s_name'];
$s_category = $row['s_category'];
?>
<li><?php echo $s_name?> <img src="https://www.xxxxxxx.xxx/xxxx/images/pdf.gif" alt="PDF"></li>
<?php
}
?>
</ul>
<?php
}
?>
form_livesearch.php:
if(isset($_POST['input'])){
$input = $_POST['input'];
//to prevent from mysqli injection
// x'='x
$input = stripcslashes($input);
$input = mysqli_real_escape_string($db, $input);
$input = str_replace('%', ' #', $input);
$input = str_replace("'", ' #', $input);
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_name LIKE '%{$input}%' ORDER BY id ASC";
$result = mysqli_query($db,$query);
if(mysqli_num_rows($result) > 0){?>
<table class="table table-bordered table-striped mt-4">
<!--
<thead>
<tr>
<th>id</th>
<th>name</th>
</tr>
</thead>
-->
<tbody>
<?php
while($row = mysqli_fetch_assoc($result)){
$id = $row['id'];
$s_url = $row['s_url'];
$s_name = $row['s_name'];
$s_category = $row['s_category'];
?>
<tr>
<td style="font-size: 14px;"><?php echo $s_name;?> <img src="https://www.xxxxx.xxxx/xxxxx/images/pdf.gif" alt="PDF"></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}else{
echo "<h6 class='text-danger text-center mt-3'>No data Found</h6>";
}
}
?>
You should handle this stuff in the PHP file. and by the way, the input can not be empty as you put the ajax in keyup event.
it just happened when the user use the backspace to delete what he search.
So the form_livesearch.php PHP file should be something like this.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$output = "";
if(isset($_POST['input'])){
$input = $_POST['input'];
if(!empty($input)){
$input = str_replace('%', ' #', $input);
$input = str_replace("'", ' #', $input);
$input = "%$input%"; // prepare the $input variable
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_name LIKE ? ORDER BY id ASC";
$stmt = $conn->prepare($query);
$stmt->bind_param("s", $input); // here we can use only a variable
$stmt->execute();
}else{
$query = "SELECT * FROM `my_db` . `my_table` WHERE s_category = 'policy' ORDER BY id ASC";
$stmt = $conn->prepare($query);
$stmt->execute();
}
$result = $stmt->get_result(); // get the mysqli result
if($result->num_rows > 0){
if(empty($input))
$output = '<table class="table table-bordered table-striped mt-4"><tbody>';
else
$output = '<h3>Policies</h3><ul>';
while($row = $result->fetch_assoc()){
$id = $row['id'];
$s_url = $row['s_url'];
$s_name = $row['s_name'];
$s_category = $row['s_category'];
if(empty($input))
$output .= '
<tr>
<td style="font-size: 14px;">' . $s_name .' <img src="https://www.xxxxx.xxxx/xxxxx/images/pdf.gif" alt="PDF"></td>
</tr>';
else
$output .= '<li>' . $s_name . ' <img src="https://www.xxxxxxx.xxx/xxxx/images/pdf.gif" alt="PDF"></li>';
}
if(empty($input))
$output .= '</tbody></table>';
else
$output .= '</ul>';
echo $output;
}else{
echo "<h6 class='text-danger text-center mt-3'>No data Found</h6>";
}
}
?>
You can use a separate file to handle 2 types but as they are all about products it's better to have one file.
It's a good practice to return the data and let the frontend build the HTML output but if you want to build HTML in the PHP file, it's better to wrap them in a string.
Also, use the prepare statement of MySQLi to prevent SQL injection. take a look at this example for more information.
And the html file should be something like this:
<div id="container" class="col-md-12">
<div class="row">
<h2>Quick Search</h2>
<input class='form-control' type="text" id='live_search' placeholder='Search our inventory'>
<br>
<br>
<h2 class="" id="searchresult">
</h2>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
// will execute once the page load
getData();
$("#live_search").keyup(function(){
let input = $(this).val();
getData(input);
});
});
function getData(input = ''){
$.ajax({
url:"form_livesearch.php",
method:"POST",
data:{input:input},
success:function(data){
$("#searchresult").html(data);
$("#searchresult").css("display","block");
}
});
}
</script>
I have this simple insert query that basically add one row to the db table. but it is not only adding the row but its not redirecting neither. i tried redirecting through javaScript, it gets redirected but still not adding the row. the page is live at:
http://arj-profile.com/public/new_subject.php
(when you go the link click on about widget and then click on add a subject.
i was originally trying this on mamp and i have tried turning on output buffering on php.ini too, still no luck.
any help appreciated. if you need additional information just console log on the above link or let me know i can provide it my entire tables and db as well.
the form page has the following code:
<!-- including functions -->
<?php include("../includes/db_connect.php") ?>
<?php require_once("../includes/functions.php"); ?>
<!-- query -->
<!-- end of query -->
<!-- including header -->
<?php include("../includes/header.php") ?>
<?php find_selected_page();?>
<div class="container-fluid">
<div class="row">
<!-- menu -->
<div class="col-md-3 sidebar">
<?php echo navigation(); ?>
</div>
<!-- body -->
<div class="col-md-9 body">
<form action="create_subject.php" method="post">
<p>Subject name:
<input type="text" name="menu_name" value=""/>
<p>
<p>Position
<select name="position">
<?php
$subject_set = find_all_subjects();
$subject_count = mysqli_num_rows ($subject_set);
for ($count = 1; $count <= ($subject_count + 1); $count++){
echo "<option value=\"{$count}\">{$count}</option>";
}
?>
</select>
</p>
<p>Visible:
<input type="radio" name="visible" value="0" />No
 
<input type="radio" name="visible" value="1" />Yes
</p>
<input type="submit" name="submit" value="Submit">
</p>
<br />
<!-- redirect -->
Cancel
</form>
</div>
</div>
</div>
<!-- footer -->
<?php include("../includes/footer.php") ?>
please try adding but filling out the form, as you see it goes to the following page which actually contains the query but it is not supposed to go there, it should just redirect back to the create_subject.php.
<?php include("../includes/db_connect.php") ?>
<?php require_once("../includes/functions.php"); ?>
<?php
if (isset($_POST['submit'])){
$menu_name = mysqli_prep($_POST["menu_name"]);
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$menu_name = mysqli_prep($menu_name);
$query = "insert into subjects(";
$query = " menu_name, position, visible";
$query = ") values (";
$query = " '{$menu_name}', {$position}, {$visible}";
$query = ")";
$result = mysqli_query($connection, $query);
if ($result){
$msg = "Subject created";
redirect_to("manage_subject.php");
}
}else {
$msg = "Subject creation failed";
redirect_to("new_subject.php");
}
?>
<?php
if (isset($connection)){mysqli_close($connection); }
?>
in my function.php i have:
<?php
function redirect_to($new_location){
header("Location: " . $new_location);
exit;
}
function mysqli_prep($string){
global $connection;
$escape_string = mysqli_real_escape_string($cnnection, $string);
return $escape_string;
}
function confirm_query($result_set){
if (!$result_set){
die("DB Query Failed");
}
}
function find_all_subjects(){
global $connection;
$query = "select * ";
$query .= "from subjects ";
$query .= "where visible = 1 ";
$query .= "order by position asc";
$subject_set = mysqli_query($connection, $query);
confirm_query($subject_set);
return $subject_set;
}
function find_pages_for_subjects($subject_id){
global $connection;
$safe_subject_id = mysqli_real_escape_string($connection, $subject_id);
$query = "select * ";
$query .= "from pages ";
$query .= "where visible = 1 ";
// an aditional line to relate pages to the subject, subject_id is what rlate two tables together
// dont forget space between lines
$query .= "AND subject_id = {$safe_subject_id} ";
$query .= "order by position asc";
$page_set = mysqli_query($connection, $query);
// the result captured can not be used twice for two different queries
// so result varibale should have unique names
confirm_query($page_set);
return $page_set;
}
function find_subject_by_id($subject_id){
global $connection;
$safe_subject_id = mysqli_real_escape_string($connection, $subject_id);
$query = "select * ";
$query .= "from subjects ";
$query .= "where id = {$safe_subject_id} ";
$query .= "limit 1";
$subject_set = mysqli_query($connection, $query);
confirm_query($subject_set);
if ($subject = mysqli_fetch_assoc($subject_set)){
return $subject;
}else {
return null;
}
}
function find_page_by_id($page_id){
global $connection;
$safe_page_id = mysqli_real_escape_string($connection, $page_id);
$query = "select * ";
$query .= "from pages ";
$query .= "where id = {$safe_page_id} ";
$query .= "limit 1";
$page_set = mysqli_query($connection, $query);
confirm_query($page_set);
if ($page = mysqli_fetch_assoc($page_set)){
return $page;
}else {
return null;
}
}
function find_selected_page(){
global $current_subject;
global $current_page;
if (isset($_GET["subject"])){
$current_subject = find_subject_by_id($_GET["subject"]);
$current_page = null;
} elseif (isset($_GET["page"])){
$current_page = find_page_by_id($_GET["page"]);
$current_subject = null;
} else{
$current_subject = null;
$current_page = null;
}
}
function navigation(){
$output = "<ul>";
$subject_set = find_all_subjects();
while($subject = mysqli_fetch_assoc($subject_set)){
$output .= "<li><a href=\"manage-content.php?subject=";
$output .= urlencode($subject["id"]);
$output .= "\">";
$output .= $subject["menu_name"];
$output .= "</a>";
$page_set = find_pages_for_subjects($subject["id"]);
$output .= "<ul>";
while($page = mysqli_fetch_assoc($page_set)){
$output .= "<li><a href=\"manage-content.php?page=";
$output .= urlencode($page["id"]);
$output .= "\">";
$output .= $page["menu_name"];
$output .= "</a></li>";
}
mysqli_free_result($page_set);
$output .= "</ul></li>";
}
mysqli_free_result($subject_set);
$output .= "</ul>";
return $output;
}
?>
function mysqli_prep( $string ){
global $connection;
return mysqli_real_escape_string( $connection, $string );
}
<?php include("../includes/db_connect.php") ?>
<?php require_once("../includes/functions.php"); ?>
<?php
$redir='new_subject.php';
if ( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['submit'] ) ){
$menu_name = mysqli_prep( $_POST["menu_name"] );
$position = (int) $_POST["position"];
$visible = (int) $_POST["visible"];
$query = "insert into subjects
( menu_name, position, visible )
values
( '{$menu_name}', {$position}, {$visible} )";
$result = mysqli_query( $connection, $query );
if ( $connection ) mysqli_close( $connection );
if( $result ) $redir='manage_subject.php';
}
redirect_to( $redir );
?>
I have connected and pull retrieve some data using PHP but I would like to know:
It is PHP or Javascrip , JS better to interacts with Postgresql
It is an easy way to do the same as my PHP code in Javascrip or JS? if so, how?
In my example: I'm inserting the name, last name and email and retrieving the country.
Thank you very much
<!DOCTYPE HTML>
<html>
<body>
<?php
// define variables and set to empty values
$nameErr = $emailErr = $surnameErr = $AddressErr = "";
$name = $email = $surname = $address = "";
<select name="countryselect" id="countryselect">
<?php
$db = pg_connect('host=localhost dbname=test user=myuser password=mypass');
$query = "SELECT country FROM countries";
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
printf ("<option value=Select>Select a Country</option>");
while($myrow = pg_fetch_assoc($result)) {
printf ("<option value=$myrow[country]>$myrow[country]</option>");
}
?>
</select>
<input type="submit" name="submit" value="SAVE">
</form>
<?php
if ($nameErr == '' && $emailErr == '' && $surnameErr == '')
{
$db = pg_connect('host=localhost dbname=test user=myuser password=mypass');
$firstname = pg_escape_string($_POST['name']);
$surname = pg_escape_string($_POST['surname']);
$emailaddress = pg_escape_string($_POST['email']);
$query = "INSERT INTO host(firstname, surname, emailaddress) VALUES('" . $firstname . "', '" . $surname . "', '" . $emailaddress . "')";
$result = pg_query($db, $query);
if (!$result) {
$errormessage = pg_last_error();
echo "Error with query: " . $errormessage;
exit();
}
//printf ("These values were inserted into the database - %s %s %s", $firstname, $surname, $emailaddress);
pg_close();
}
?>
</body>
</html>
How to get my AJAX results from the input of a textbox populated from mysql live on the page.
I already got it to work with the use of textboxes, so if you check them then the page gets updated with the results of mysql.
The same I would like to use for my textboxes as soon as you type something in or select something from the autocomplete list (this would be even beter).
I have the following code that I want to use for the textbox:
HTML:
<input type="text" name="naam_klant" size="20" id="naam_klant" onkeyup="lookup(this.value);" onblur="fill();" >
<div class="suggestionsBox" id="suggestions" style="display: none;">
<div class="suggestionList" id="autoSuggestionsList">
</div>
</div>
PHP:
$pdo = new PDO('mysql:host=localhost;dbname=records', 'root', '***');
$select = 'SELECT *';
$from = ' FROM overboekingen';
$where = ' WHERE FALSE';
$opts = isset($_POST['filterOpts'])? $_POST['filterOpts'] : array('');
if (in_array("naam_klant", $opts)){
$where .= " OR naam_klant = [$queryString%] ";
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
I am using a form with javascript which is used to add n numbers of rows dynamical and post data to mysql.
now i want to post more information to mysql using where clause (form data) in sql statement.
This is my code to submit and post data.
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var addDiv = $('#addinput');
var i = $('#addinput p').size() + 1;
$('#addNew').live('click', function() {
$('<p><select name="stockid[]' + i +'" onchange="showUser(this.value)"> <?php echo $item; ?></select> <select name="desc[]' + i +'" id="txtHint"> <?php echo $description; ?></ </select>Remove </p>').appendTo(addDiv);
i++;
return false;
});
$('#remNew').live('click', function() {
if( i > 2 ) {
$(this).parents('p').remove();
i--;
}
return false;
});
});
</script>
<body>
<?php if (!isset($_POST['submit_val'])) { ?>
<h1>Add your Hobbies</h1>
<form method="post" action="">
<div id="container">
<p id="addNew"><span>Add New</span></p>
<div id="addinput">
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php } ?>
<?php
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description) VALUES ('$stockid[$a]','$desc[$a]')", $connection );
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
its working fine now when am trying to use a select statement and post data to mysql its not working
here is code
<?php
$con=mysqli_connect("localhost","root","","inventory");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
}
mysqli_close($con);
?>
then i modify the post code of above file like this
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$price = $row['price'];
foreach($stockid as $a => $B)
{
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection);
}
echo "<i><h2><strong>" . count($_POST['stockid']) . "</strong> Hobbies Added</h2></i>";
}
?>
but nothing is inserted in to database in price column
Change your code to store the price value in a new variable:-
<?php
$con=mysqli_connect("localhost","root","","inventory");
$price = array(); //declare
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
{
echo $row['price'];
$price = $row['price']; //initiate
}
mysqli_close($con);
?>
<?php
if (isset($_POST['submit_val']))
{
$stockid = $_POST["stockid"];
$desc = $_POST["desc"];
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid','$desc','$price')", $connection);
}
?>
Your $row['price'] variable will only exist within the while loop so you have to store it in something that is present beforehand and use that variable instead.
Assuming that both code snippets are in the same file, that is. Take a look over the code and see the changes on line 3 and line 27.
Also, as the other guys have said remove the double $$ and just use one on this line:-
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
Hope this is of some help to you :)
As said by aconrad in comments, replacing $$_POST by $_POST would probably solve your problem.
But I suggest you to change mysqli_query() to mysqli_prepare (and to change all mysql_* by the equivalent mysqli_* function)
I suggest you to transform all into mysqli_ and use prepared statements instead of direct query like this :
Change this:
<?php
$result = mysqli_query($con,"SELECT * FROM 0_stock_master where id = '".$$_POST['stockid']."'");
while($row = mysqli_fetch_array($result))
to this:
<?php
$stmt = mysqli_prepare($con,"SELECT price FROM 0_stock_master where id = ?");
mysqli_stmt_bind_param($stmt, 'i', $_POST['stockid']);
$result = mysqli_stmt_execute($stmt);
if (!$result)
echo 'Mysql error : '.mysqli_stmt_error($stmt);
mysqli_stmt_bind_result($stmt, $price); // values will
mysqli_stmt_fetch($stmt); // this call send the result in $price
mysqli_stmt_close($stmt);
Change this:
<?php
$query = mysql_query("INSERT INTO 0_stock_master (stock_id,description,price) VALUES ('$stockid[$a]','$desc[$a]','$price[$a]')", $connection );
to this :
<?php
$stmt = mysqli_prepare($connection, "INSERT INTO 0_stock_master (stock_id,description,price) VALUES (?, ?, ?)");
// I assume stock_id must be int, desc must be string, and price must be float
mysqli_stmt_bind_param($stmt, 'isf', $stockid[$a],$desc[$a],$price[$a]);
$query = mysqli_stmt_execute($stmt);
$affected_rows = mysqli_stmt_affected_rows($stmt);
EDIT :
Some documentation:
MySQLi
mysqli_prepare (sql queries more protected from sql injection)
mysqli_stmt_bind_param
mysqli_stmt_execute
mysqli_stmt_bind_result
mysqli_stmt_fetch