I am passing the $place variable to a query in listplace.php using a ajax call. The ajax call works perfectly in php1.php code, but the $place value is not passed over the query. Please help!
listplace.php too works perfectly but when i try to pass $place in where condition it fails.
php1.php code
<select id="name">
<option selected disabled>Please select</option>
</select>
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET['place'] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>
<?php } ?>
listplace.php
<?php
//connect to the mysql
$db = #mysql_connect('localhost', 'root', 'password') or die("Could not connect database");
#mysql_select_db('test', $db) or die("Could not select database");
$place = $_POST['place'];
$sql = #mysql_query("select product_name from products_list where product_name = '$place'");
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r['product_name'];
}
if (count($rows)) {
echo json_encode(['option'=> $rows]);
}else {
echo json_encode(['option'=> false]);
}
?>
An improvement will be to start using prepared statements. This is just an addition to Exprator's answer
This will prevent SQL injection attacks.
$sql_con = new mysqli('localhost', 'root', 'password', 'test');//get connection
$place = $_POST['place'];//posted variable
if($stmt = $sql_con->prepare("select product_name from products_list where product_name =?")) {//prepare returns true or false
$stmt->bind_param("s", $place); //bind the posted variable
$stmt->execute(); //execute query
$stmt->bind_result($product_name);//bind the result from query securely
$rows = array();//create result array
while ($stmt->fetch()) {//start loop
$rows[] = $product_name;//grab everything in array
}
if (count($rows)) {//check for number
echo json_encode(['option'=> $rows]);
} else {
echo json_encode(['option'=> false]);
}
change this line
data: {place: '<?= $_GET['place'] ?>'},
to
data: {place: '<?= $_GET["place"] ?>'},
Related
i have this code:connection to database
<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$conn = new mysqli("localhost", "root", "", "jquery");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
now i already have data indatabase in table called city witch it have only id and desc and this is the code
if (isset($_POST['city'])) {
$sql = "SELECT * FROM city";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$results = [];
while($row = $result->fetch_assoc()) {
$results[] = $row;
}
echo json_encode($Results);
}
else
{
echo "empty";
}
}
here is the html part:
<select required="required" id="city">
<option disabled selected value=''> select a city </option>
</select>
and here is the function:
function city() {
$.ajax({
"url": "divs.php",
"dataType": "json",
"method": "post",
//ifModified: true,
"data": {
"F": ""
}
})
.done(function(data, status) {
if (status === "success") {
for (var i = 0; i < data.length; i++) {
var c = data[i]["city"];
$('select').append('<option value="'+c+'">'+c+'</option>');
}
}
})
.always(function() {
});
}
so the problem is that there is nothing in select list its always empty, any help? thank u
One small mistake is here:
You are using
echo json_encode($Results);
instead of
echo json_encode($results);
In PHP variable names are case sensitive. So, use proper case for all the variables.
You are not getting the response data in HTML <SELECT> TAG here is what you can do.
image to table
HTML FILE CODE:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form action="" method="post">
<select>
</select>
</form>
<script>
$(document).ready(function(){
city();
});
function city(){
$.ajax({
type:'POST',
url: 'divs.php',
data: {city:1},
success:function(data){
var res = JSON.parse(data)
for(var i in res){
var showdata = '<option value="'+res[i].city_name+'">'+res[i].city_name+'</option>';
$("select").append(showdata);
}
}
});
}
</script>
</body>
</html>
HERE IS THE PHP CODE
`
<?php
$conn = new mysqli('localhost','root','','demo');
if($conn->connect_error){
die ("Connection Failed".$conn->link->error);
}
if(isset($_POST['city'])){
$sql = "SELECT * FROM city";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$results[] = $row;
}
echo json_encode($results);
}
else
{
echo "no city available";
}
}
?>
`
HERE IS THE OUTPUT IMAGE
You have used $results but while echoing you are using $Results which is a different variable so use,
echo json_encode($results);
Also, you are telling that city has only id and desc so in JS code use desc instead of city
$.ajax({
type:'POST',
url: 'divs.php',
data: {city:1},
success:function(data) {
var res = JSON.parse(data);
$(res).each(function(){
var c = this.city_name; // use city_name here instead of city
$('select').append('<option value="'+c+'">'+c+'</option>');
});
}
});
I am having an issue where i get a timeout if i run a certain php script with parameters sent from a Jquery Ajax reequest. However if i simply run this script with no parameters I.E just run it on its own its fine.
The php file the Ajax request is in is noteContent.php
noteContent.php:
<script type="text/javascript">
// Submit generalNote to the database
function submitNoteText()
{
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
var notetext = $("#ta1").val();
var dataString = 'noteid1=' + noteid + '¬etext1=' + notetext;
if(noteid == ''||notetext == '')
{
alert("NoteID or Text is blank");
}
else
{
$.ajax({
type: "POST",
url: "submitNoteText.php",
dataType: 'json',
data: dataString,
cache: false,
success: function(result){
alert("Success");
}
});
}
return false;
};
</script>
The script its trying to run
submitNoteText.php:
<?php include 'connectionDetails.php'; ?>
<?php
if (isset($_POST['noteid1'], $_POST['notetext1']))
{
var_dump($_POST['notetext1']);
$noteid2 = $_POST['noteid1'];
$notetext2 = $_POST['notetext1'];
$stmt = "UPDATE Notes SET Note = '?' WHERE NoteID = ?";
$params = array($noteid2, $notetext2);
$stmt = sqlsrv_query($conn, $stmt, $params);
if ($stmt === false)
{
die( print_r(sqlsrv_errors(), true));
}
}
else
{
echo "No Data";
}
?>
they are all connected with an include to
connectionDetails.php(which has never returned an error before):
<?php
$myServer = "Test";
$connectionInfo = array('Database' => 'Test', 'UID' => 'Test', 'PWD' => 'test');
//connection to the database
$conn = sqlsrv_connect($myServer, $connectionInfo)
or die("Couldn't connect to SQL Server on $myServer");
//Test connection to server
// if ($conn)
// {
// echo "connection successful"; # code...
// }
?>
<?php
//Defining my queries
$getNotes = "SELECT NoteID, NoteName, Note FROM Notes ORDER BY NoteName ASC";
$getTemplateNotes = "SELECT TemplateNoteID, TemplateNoteName, TemplateNote FROM TemplateNotes ORDER BY TemplateNoteName ASC";
$getReplaceVariables = "SELECT ReplaceVariableID, ReplaceVariableName, ReplaceVariableNote FROM ReplaceVariables ORDER BY ReplaceVariableName ASC";
$resultNotes = sqlsrv_query($conn, $getNotes);
$resultTemplate = sqlsrv_query($conn, $getTemplateNotes);
$resultVariables = sqlsrv_query($conn, $getReplaceVariables);
if( $resultNotes === false)
{
die( print_r( sqlsrv_errors(), true) );
}
if( $resultTemplate === false)
{
die( print_r( sqlsrv_errors(), true) );
}
if( $resultVariables === false)
{
die( print_r( sqlsrv_errors(), true) );
}
?>
When i click the button to run the request i get this:
All the text to be submitted is in the params:
Ajax data parameter should be an array :
$.ajax({
type: 'POST',
url: "your urls",
data: {
id: youridval,
anothervar: anothervalvalue
},
beforeSend: function() {
},
complete: function() {
},
success: function(_result) {
}
});
Hello im doing some try and error. This is the code where select-option populate from database but this gives me null value
echo "<option value=\"\">"."Select"."</option>";
$qry = "select * from try where name = '".$_POST['name']."'";
$result = mysqli_query($con,$qry);
while ($row = mysqli_fetch_array($result)){
echo "<option value='".$row['trynum']."'>".$row['tryname']."</option>";
}
$.ajax({
type: "POST",
url: "json_php_sub.php",
data: {instructor:$(this).val()},
datatype: 'json',
success: function(result){
alert(result);
document.getElementById("sub").innerHTML = result;
}
});
<select id="sub" name="subb"></select>
my problem is whether i select from dropdown the content is there but no value. pls help..
PHP:
$ajaxAnswer = "<option value=\"\">"."Select"."</option>";
$instructor = mysqli_real_escape_string($conn,$_POST['instructor']);
$qry = "select * from try where name = '".$instructor."'";
$result = mysqli_query($con,$qry);
while ($row = mysqli_fetch_array($result)){
$ajaxAnswer .= "<option value='".$row['trynum']."'>".$row['tryname']."</option>";
}
echo $ajaxAnswer;
Jquery:
$.ajax({
type: "POST",
url: "json_php_sub.php",
data: {instructor:$(this).val()},
success: function(result){
$("#sub").html(result);
}
});
data: {instructor:$('#SELECT_ELEMTN_ID').val()},
Depending on scope and stuff, you may not wanna use "this".
Jquery
$(document).ready(function () {
$.ajax({
type: "GET",
url: "phpfile.php",
dataType: "json",
success: function (data) {
$.each(data, function (idx, obj) {
$('#selectdata').append('<option value="'+obj.user_id+'">'+obj.user_name+'</option>' )
});
}
});
});
</script>
</head>
<body>
<select id="selectdata">
</select>
</body>
phpfile.php
<?php
$host = "localhost";
$user = "root";
$password ="";
$database= "databasename";
$con = mysqli_connect($host , $user , $password);
$database_connect = mysqli_select_db($con, $database);
$result = mysqli_query($con, "select Id as user_id,Name as user_name from users");
$data = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($data);
?>
I have here a ajax. What I need to know if it possible to send back the post value and store it in php variable in the mainpage depending in onchange event? $_POST["mainlist_id"] store in php var?
getajax.php
<?php
if (isset($_POST["mainlist_id"])) {
$mysqli = new mysqli("localhost", "root", "", "2015");
$main = $mysqli->real_escape_string($_POST["mainlist_id"]);
$result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");
$option1 = '';
while($row = $result1->fetch_assoc())
{
$option1 .= '<option value = "'.$row['item'].'">'.$row['item'].'</option>';
}
echo $option1;
}
?>
Mainpage
<script type="text/javascript">
$('#main').change(function () {
$.ajax({
url: 'getajax.php',
data: {
mainlist_id: $(this).val()
},
dataType: 'html',
type: 'POST',
success: function (data) {
$('#languages').html(data);
}
});
});
</script>
getajax.php
<?php
session_start();
if (isset($_POST["mainlist_id"])) {
$mysqli = new mysqli("localhost", "root", "", "2015");
$main = $mysqli->real_escape_string($_POST["mainlist_id"]);
$_SESSION['mainlist_id']=$main;
$result1 = $mysqli->query("SELECT * FROM code WHERE cat_code='$main' GROUP BY item_code ORDER BY item");
$option1 = '';
while($row = $result1->fetch_assoc())
{
$option1 .= '<option value = "'.$row['item'].'">'.$row['item'].'</option>';
}
echo $option1;
}
?>
Mainpage
<?php session_start();
$main_id=$_SESSION['mainlist_id'];
?>
<script type="text/javascript">
$('#main').change(function () {
$.ajax({
url: 'getajax.php',
data: {
mainlist_id: $(this).val()
},
dataType: 'html',
type: 'POST',
success: function (data) {
$('#languages').html(data);
}
});
});
</script>
What I'm trying to do is calling some database data via ajax and php. But the ajax call doesn't work, and I can't find out a solution on the web.
So here is my code:
test.php
<?php
include_once 'db_class.php';
$cat = $_GET['cat'];
$dbconn = new dbconn('localhost', 'root', 'somepsw', 'blog');
$dbconn->set_query("select * from posts where category = '".$cat."'");
echo '<br/>'.$dbconn->query.'<br/>';
$result = $dbconn->result;
$num = $dbconn->num_results;
$array = mysqli_fetch_assoc($result);
echo json_encode($array);
?>
If i type that url on browser: http://127.0.0.1:82/blog/ws/test.php?cat=css
The data returned via jsonEncode is correct, but when i'm loading it on a html page with jquery he can't read the data.
test.html
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
function ajaxCall() {
var css;
$.ajax({
url: 'test.php',
type: "GET",
data: {cat: css},
dataType: 'json',
success: function(rows)
{
alert(rows);
},
error: function() { alert("An error occurred."); }
});
}
ajaxCall();
</script>
</head>
<body></body>
</html>
Thanks in advance.
I just rewrote the php code using PDO, should be more safe now.
db.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpsw = "somepsw";
$dbname= "blog";
try {
#$dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpsw);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
}
catch(PDOException $e) {
echo "Connection failed, an error occured! Please contact server administrator."; //user friendly message
getErrorsLog($e->getMessage());
}
function closeDbConn () {
$dbh = null;
}
function getErrorsLog($message) {
$file = 'dberrors.log';
$date = date("d/m : H:i :");
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new error message to the file
$current .= $date.$message;
$current .= "\r\n";
// Write the contents back to the file
file_put_contents($file, $current);
exit();
}
?>
blogdata.php
<?php
include_once "db.php";
$tableName = "posts";
$data = array();
#$view = $_GET["view"];
if (isset($_GET["view"])) {
$stmt = $dbh->prepare("SELECT * FROM $tableName WHERE category =? ORDER BY created DESC");
}
else {
try {
$stmt = $dbh->prepare("SELECT * FROM $tableName ORDER BY created DESC");
}
catch (PDOException $e) {
getErrorsLog($e->getMessage());
}
}
$stmt->bindValue(1, $view, PDO::PARAM_STR);
$stmt->execute();
$affected_rows = $stmt->rowCount(); //Rows count
if ($affected_rows == 0) {
echo "The data you looking for no longer exist, please contact the administrator.";
exit();
}
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
$data[] = $row;
}
echo json_encode($data);
closeDbConn();
?>
Your variable css has no value. You wanted to use the string 'css'. Maybe you want to be able to load other categories, too. So change your ajaxCall function to
function ajaxCall(category)
{
$.ajax({
url: 'test.php',
type: "GET",
data: {cat: category},
dataType: 'json',
success: function(rows) {
alert(rows);
},
error: function() {
alert("An error occurred.");
}
});
}
and call it using
ajaxCall('css');