POST variable from SELECT into sql query to output to an INPUT - php

Using Chain SELECT works great from SELECT to SELECT, I'm trying to do SELECT to INPUT.
My mainpage.php
<label>Manufacturer</label>
<select>My Select statement is here</select>
<label>Model</label>
<select name="modelname">My Select statement is fed from the select above</select>
<label>Rating</label>
<input name="rating"></input>
This is the jQuery I have in the <head> section on the mainpage.php
<script>
$(document).ready(function(){
$("select#modelname").change(function(){
var id = $("select#modelname option:selected").attr('value');
$.post("assets/configs/getdata.php", {id:id}, function(data){
$("input[name='rating']").html(data);
console.log(data);
});
});
});
</script>
and finally the getdata.php
<?php
include "db.php";
$modelid = $_POST[id];
$sql = "SELECT EfficiencyRating FROM AllModels WHERE ModelID = '$modelid' ";
$res = odbc_exec($cnn, $sql);
while ($row = odbc_fetch_array($res)) {
$row_array[] = $row['EfficiencyRating'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>
Using the console log when this message is returned, how can I fix this?
HP Warning: array_push() expects parameter 1 to be array, null given in assets\configs\getdata.php on line 12

Try with this.
$res = odbc_exec($cnn, $sql);
$return_arr = array();
while ($row = odbc_fetch_array($res)) {
$return_arr[] = $row['EfficiencyRating'];
}
echo json_encode($return_arr);
JS Part
// Slightly modify the Request
$.post("assets/configs/getdata.php", {id:id}, function(data){
// JSON Object
console.log(data);
$("input[name='rating']").val(data);
}, 'json');

You need to declare $return_arr before the while statement. Also, I personally feel what you are doing is just not right. The proper way would be this...
$res = odbc_exec($cnn, $sql);
$return_arr = array(); //<----------- Here
while ($row = odbc_fetch_array($res)) {
array_push($return_arr,$row['EfficiencyRating']);
}
echo json_encode($return_arr);

Related

jQuery function doesn't update data when it is updated in the database

I would like to update the data in the frontend when it is changed in the database. The code I'm using is given below:
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<div id="test">
<?php
include('conn.php');
$query = "SELECT name FROM user_details WHERE user_id = 1;";
if(mysqli_fetch_assoc(mysqli_query($conn, $query))["name"] == "MyName")
echo 'Hi <b>MyName!</b>';
else
echo 'You are not <b>MyName</b>.';
?>
</div>
<script>
setInterval(function(){
$.get("/test.php", function(data){
let $data = $(data);
$("#test").append($data.find("#test > *"));
});
}, 1000);
</script>
However, when the data is updated, it does not get updated in the frontend unless refreshed. When I use jQuery's load() function, it works perfectly. Why does this not work?
As I suggested in the comment, if you create a stand alone PHP Script, it might be like:
getUserName.php
<?php
$id = (int)$_GET['id'];
include('conn.php');
$query = "SELECT name FROM user_details WHERE user_id = $id;";
$myName = "";
if ($result = mysqli_query($conn, $query)) {
while ($row = mysqli_fetch_assoc($result)) {
$myName = $row;
}
}
mysqli_free_result($result);
mysqli_close($conn);
header('Content-Type: application/json');
echo json_encode($myName);
?>
This is a very basic example and I would strongly advise you switch to using prepared statements to avoid the risk of SQL Injection.
In your HTML you can now do:
<script>
setInterval(function(){
$.getJSON("/getUserName.php", { id: 1 }, function(data){
$("#test").append(data.name);
});
}, 1000);
</script>
This will ping the script every second and you will have a list of names appearing.

retrieve multiple data from various queries with ajax php mysql

I'm new in Ajax and JSON notation, so I'm trying to get data from differents tables of a Database, data like country names, state names, departament name, job position etc. and I've seen examples how through JSON can get data but just from a single table, can you give me a little help how can I do it with more than one table and keep it in an array.
<?php
$host = "localhost";
$user = "usuer";
$pass = "password";
$databaseName = "jsonExample";
$tableName = "variables";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName"); //query
//$array = mysql_fetch_row($result); //fetch result
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array[] = $obj;
}
}
echo json_encode($array);
?>
Html file:
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>-->
<h2> Client example </h2>
<h3>Output: </h3>
<div id="output">this element will be accessed by jquery and this text will be replaced</div>
<script id="source" language="javascript" type="text/javascript">
$(function ()
{
$.ajax({
url: 'api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var id = data[0]; //get id
var vname = data[1]; //get name
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname); //Set output element html
//recommend reading up on jquery selectors they are awesome http://api.jquery.com/category/selectors/
}
});
});
</script>
</body>
</html>
If you want to have the results from multiple queries in one array you can add each result to a key. F.i. if you querying table table1 to tablen ...
// define the array that will contain all result sets
$array = [];
// create an array for the result set coming from table 1
$array['table1']= [];
$result = mysql_query("SELECT * FROM table1");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['table1'][] = $obj;
}
}
// create an array for the result set coming from table 2
$array['table2']= [];
$result = mysql_query("SELECT * FROM table2");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['table2'][] = $obj;
}
}
::
::
// create an array for the result set coming from table n
$array['tablen']= [];
$result = mysql_query("SELECT * FROM tablen");
if(mysql_num_rows($result) <= 0){
}else{
while($obj = mysql_fetch_row($result)){
$array['tablen'][] = $obj;
}
}
// return the results formatted as json
return json_encode($array);
In javascript you can access the results for table1 with data->table1.
Tip
Use mysqli instead of mysql. It is the improved version of mysql. Check the answers for this question for some background.

Query in Jquery IF statement

I have a jquery save script like :
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Your file is save as : '+ naam);
window.location.replace("index.php?id=latest");
}
else
{
alert('Not saved');
}
I save a div in save.php which creates an new id in the database
What I want to achive is were
window.location.replace("index.php?id=latest");
id=latest must become (id=id from last saved file).
I tried
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
window.location.replace("index.php?id="+MBId);
and
var MBID =
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo $MBId ?>
window.location.replace("index.php?id="+MBId);
They both failed.
How can I run the query in the if(naam !=null) statement?
At first place you must fix your jQuery POST... You don't use POST respond which is wrong.. You should wait for it and then continue with other actions
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam }, function(responde){
if(responde.id)
window.location.replace("http://yoururl.com/index.php?id="+responde.id);
else
alert("No responde...");
}, "json");
}
else
{
alert('Not saved');
}
For better results I suggest you to use JSON data in that post/respond..
At your PHP code you have to set:
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo json_encode(array('id'=>$MBId));
exit();
?>
P.S. For window.location.replace please set your FULL url: "http://localhost/index.php?id=" OR atleast put slash at start of it "/index.php?id="
Solution
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Uw moodboard is opgeslagen als '+ naam);
window.location.replace("index.php?id=<?php $q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = ($data[0] + 1); echo "$MBId";?>");
}
This Works for me , i didnt need to make a jquery var i could echo the variable in php.
And i had to add 1 cause the sql query is loaded when the page is loaded.
So the file isn't saved yet when i get the highest id.

getJSON need help passing values

I am trying to use getJSON to load the ids that are stored into a database, i am passing the values from PHP to JavaScript by echoing it out. I am trying to alert the value that i passed through but it didn't work
The PHP and JavaScript are on the same page. Any guidance would be appreciated
I printed the JSON file and it is in this format
Array
(
[0] => 213
[1] => 214
[2] => 215
)
PHP
$result = mysql_query("SELECT * FROM address");
$arra = array();
while ($row = mysql_fetch_array($result)){
$arra[] = $row['id'];
}
Javascript
<script>
var test= <?php echo json_encode($arra); ?>
var url = test;
$.getJSON(url, function(data) {
alert(url);
})
</script>
Make new php file called "Data.php" and make it return your JSON data.
<?php
$con = mysql_connect('localhost', 'root', '');
mysql_select_db('test');
$result = mysql_query("SELECT * FROM address ORDER BY id DESC");
$arra = array();
while ($row = mysql_fetch_array($result)){
$arra[] = $row['id'];
}
echo json_encode($arra);
?>
Then where you call your $.getJSON, Do:
$.getJSON(data.php, function(data) {
alert(data);
})
url is json object in your case. It should be url of a page! something like this should work:
$.getJSON("<?=$_SERVER["PHP_SELF"]?>", test, function(data) {
alert(data);
})

Assign multiple column values to JSON php array using mysql

I have to make a JSON ajax request and have an array in return.
i found this code on multiple other questions (edited to my problem):
var hej[];
function ajax_search(){
$.getJSON('test.php',function(response){
var data = response.get_response;
for (i in data){
hej.push([i,data[i]]);
}
alert(hej[0]);
}
In the php part, i have a database from which i need the data i have have 5 columns pr. row. I only have one row, and i need all five columns in the array.
$sql = "SELECT * FROM 'table'
LIMIT 1 OFFSET $i"; //random offset
$result = mysql_query($sql);
$storeArray = Array();
while($row = mysql_fetch_array($result))
{
$storeArray[0]=$row['column1'];
$storeArray[1]=$row['column2'];
$storeArray[2]=$row['column3'];
$storeArray[3]=$row['column4'];
$storeArray[4]=$row['column5'];
}
$json = json_encode($storeArray);
echo $json;
I know im doing something wrong, and i am new to programming. I need to be able to access all column values in my javascript after the call and use them in other functions, but i cant get it to return.
I would really appriciate help, with both the javascript and the php if there are errors in either.
It should be:
function ajax_search(){
$.getJSON('test2.php',function(response){
// response.column1
// response.column2
// response.column3
// for array push:
var hej = [];
$.each(response, function(key, val) {
hej.push(val);
});
alert(hej[0]); // it will alert column1
});
}
and MySQL:
$sql = "SELECT `column1`, `column2`, `column3`, `column4`, `column5` FROM `table` LIMIT 1 OFFSET $i"; //random offset
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
$json = json_encode($row);
echo $json;
Try this:
Javascript Code:
var hej[];
function ajax_search(){
$.getJSON('test.php',function(response){
$.each(response.results, function(key, val) {
hej.push(val);
});
alert(hej[0]);
});
}
PHP Code:
<?php
$sql = "SELECT * FROM 'table' LIMIT 1 OFFSET $i"; //random offset
$result = mysql_query($sql);
$storeArray = array();
while($row = mysql_fetch_array($result)) {
$storeArray[0]= $row['column1'];
$storeArray[1]=$row['column2'];
$storeArray[2]=$row['column3'];
$storeArray[3]=$row['column4'];
$storeArray[4]=$row['column5'];
}
$json = json_encode( array('results' => $storeArray ) );
echo $json;
?>
Hope this helps.
Why use response.get_response?
var hej[];
function ajax_search(){
$.getJSON('test.php',function(data){
$.each(data, function (i,item) {
hej.push([i,item]);
}
alert(hej[0]);
}

Categories