I know that using php inside js is a bad practice, but unfortunately for now my skill is not enough to come up with something else.
$(document).ready(function() {
$("#type").change(function() {
var val = $(this).val();
valSize = "<?php $sql = "SELECT model FROM cars WHERE brand = 'val'";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)){
echo '<option>'.$row['model'].'</option>';
}
?>";
$("#size").html(valSize);
});
});
Is there any way how I could add val variable inside php code?
Your best bet would be to use a JavaScript AJAX call to send a request to another php file on your server.
First, create a separate PHP file on your server, I'll label it query.php (ONLY for the purposes of this explanation, I'd recommend choosing something more meaningful to your application).
<?php
if ($_POST['brand']) {
// Be sure to set up your SQL $conn variable here
$conn = ...;
$sql = "SELECT model FROM cars WHERE brand = '" . $_POST['brand'] . "'";
$result = mysqli_query($conn, $sql);
$data = []; // Save the data into an arbitrary array.
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode($data); // This will encode the data into a variable that JavaScript can decode.
}
Then in your JavaScript, perform the AJAX request:
$(document).ready(function() {
$("#type").change(function() {
var val = $(this).val();
$.post('query.php', {'brand' : val}, function(data){
var jsonData = JSON.parse(data); // turn the data string into JSON
var newHtml = ""; // Initialize the var outside of the .each function
$.each(jsonData, function(item) {
newHtml += "<option>" + item['model'] + "</option>";
})
$("#size").html(newHtml);
});
});
});
You can't execute the php code once the page has loaded. You're going to have to make a ajax call to a php file, that queries the data you need and echos that back to the original file. I would also recommend encoding it using echo json_encode($queryResults); Then you can JSON.parse($data);the return data in the success function of the ajax call.
Related
Lets say I have this table mytable
id | name | x | y
I pull the the rows from mytable and create JavaScript objects with it like so:
PHP
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo '<script type="text/javascript">';
echo "new Object({$row["id"]}, '{$row["name"]}', {$row["desk_x"]}, {$row["desk_y"]});";
echo '</script>';
}
}
JS
function Object(id, name, x, y) {
var obj = {
id:id,
name:name,
x:x,
y:y
};
}
At the moment this is fine but lets say I want to add another column color to mytable
Basically I'm asking what do I write in PHP and JS to make this object dynamically, so you can have any columns and the Object object will just add a new property with the name of the column?
You can use AJAX to send data from serverside to clientside. Lets say you have a PHP file called script.php with your code:
if(isset($_GET['action']) && $_GET['action'] == 'testing'){
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo json_encode($result);
}
}
And lets say you have a JS file called script.js. Here you will do your AJAX call towards the PHP script file like this:
$.ajax({
type: 'GET',
url: 'script.php',
data: { action: 'testing' },
success: function(response){
console.log(response); //here you will have access to the object returned from the PHP script
}
})
I guess what you're looking for is how to do this without AJAX (which you don't really need here).
Put the objects in an array, then output your JS variable:
PHP:
$rows = [];
if ($result->num_rows)
while($row = $result->fetch_assoc()) $rows[] = $row; // append to array
echo "<script> var objArray = " . json_encode($rows) . "; </script>";
I am trying to fill a table using a jquery .get request, the url being a php file. The php gets data from a database, then it should return a json array back to the jquery, array which will fill the table. While the length of the array is returned as it should, the table cells are empty.
Here is my get.php function:
<?php
$mysqli=new mysqli("localhost:3306","root","","leagues");
if (mysqli_connect_errno())
{
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$return_arr = array();
$query = "SELECT * FROM league";
if ($result = $mysqli->query($query)) {
while ($row = $result->fetch_row())
{
$return_arr[] = $row;
}
}
$mysqli->close();
header('Content-Type: application/json');
echo json_encode($return_arr);
?>
And here is my jquery get function
$.get('php/get.php',function(responseJson)
{
if(responseJson!=null)
{
$("#tableleague").find("tr:gt(0)").remove();
var table1 = $("#tableleague");
$.each(responseJson, function(key,value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['teams']);
rowNew.children().eq(1).text(value['playedgames']);
rowNew.children().eq(2).text(value['wongames']);
rowNew.children().eq(3).text(value['tiegames']);
rowNew.children().eq(4).text(value['lostgames']);
rowNew.children().eq(5).text(value['scoredgoal']);
rowNew.children().eq(6).text(value['receivedgoal']);
rowNew.children().eq(7).text(value['points']);
rowNew.appendTo(table1);
});
}
});
Here is how my webpage looks, with the php file response shown.
Since the response is ok, what am I doing wrong that the cells aren't filled? Thank you.
If you look at your JSON data, you can see that there are no keys such as teams or playedgames. This is because you used fetch_row() in the PHP. Change that to fetch_assoc():
while ($row = $result->fetch_assoc())
This will give you $row with the field names as keys instead of using numerical keys that fetch_row() provides.
You can turn the php json into javascript object
obj = JSON.parse(json);
es:
var json='{"ex1":"test","ex2":[{"sub1":"test"},{"sub2":""s2test}],"ex3":true}';
var obj = JSON.parse(json);
after you can acces to data with :
obj.ex1 // test
obj.ex2[0].sub2 //s2test
I am trying to bring mysql data into jquery by using php, I get the data into a JSON format like this.
{"uid":"33","title":"Apple, Peach, Grapefruit","ing1":"apple","qty1":"1","meas1":"whole","ing2":"peaches \/ halved and","qty2":"2","meas2":"each","ing3":"grapefruit \/ peeled","qty3":"2","meas3":"each","ing4":"","qty4":"0","meas4":"each","ing5":"","qty5":"0","meas5":"each","ing6":"","qty6":"0","meas6":"each","ing7":"","qty7":"0","meas7":"each","ing8":"","qty8":"0","meas8":"each","ing9":"","qty9":"0","meas9":"each","ing10":"","qty10":"0","meas10":"each","servings":"2","benefits":""}
using this following code:
require_once'connect.php';
$uid = $_GET['uid'];
$sql = "SELECT * FROM recipes WHERE uid = '$uid'";
$result = mysqli_query($conn, $sql);
$num_rows = mysqli_affected_rows($conn);
while($row = mysqli_fetch_assoc($result)) {
$data = json_encode($row);
echo $data;
}
I am using jquery .get to pull it into the web page with this code.
$(document).ready(function(e) {
var id = location.search;
uid=id.substring(4);
$.get('../jqm_juicing/data/get_json.php?uid=' + uid,function(data, status){
$("#display").append(data);
});
});
It displays the json data as above. I would like to be able to access the different elements individually, how do I do that?
If you wrap it with <script> tags, and declare it as a variable, you will have it.
require_once'connect.php';
$uid = $_GET['uid'];
$sql = "SELECT * FROM recipes WHERE uid = '$uid'";
$result = mysqli_query($conn, $sql);
$num_rows = mysqli_affected_rows($conn);
echo "<script>";
while($row = mysqli_fetch_assoc($result)) {
$data = json_encode($row);
echo "var myJson=" . $data;
}
echo "</script>";
Now in your main page scripts, you can access this JSON like any other normal JSON.
Here is an interval that you can place anywhere in your main page scripts:
It is just to test this ;)
var checkJson = setInterval(function(){
if(typeof(myJson.uid)!="undefined"){
clearInterval(checkJson);
console.log("myJson uid: " + myJson.uid);
console.log("myJson title: " + myJson.title);
// etc...
}else{
console.log("JSON not loaded yet.");
}
},500);
Retrieve the json data to use json response jquery parse function. json data using this function
jQuery.parseJSON()
http://api.jquery.com/jquery.parsejson/
In your jQuery, add JSON.parse() before you append (data).
$(document).ready(function(e) {
var id = location.search;
uid=id.substring(4);
$.get('../jqm_juicing/data/get_json.php?uid=' + uid,function(data, status){
$("#display").append(JSON.parse(data));
});
});
I just changed this line:
$("#display").append(JSON.parse(data));
Hope this helps!
I'd like to find a way of having a single page in the root of each of my web sections to hold all of the databae queries I'm calling.
I'm using a little script .....
<script type="text/javascript">
$(function() {
var availableTags = <?php include('fn-search-em.php'); ?>;
$("#quick-add").autocomplete({
source: availableTags,
autoFocus:true
});
});
</script>
.... to do SQL searches that appear as the user is typing. Similar to this ....
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
$result = mysqli_query($conn, $sql);
$results_list = array();
while($row = mysqli_fetch_array($result))
{
$colour_id = $row['id'];
$range_name = $row['range_name'];
$range_colour = $row['colour'];
$colour_code = $row['code'];
$p1 = $row['piece_size_1'];
$p2 = $row['piece_size_2'];
if($p1 > 1){
$p_mark = 'x';
}
else {
$p_mark = '';
}
$results_list[] = $range_name.' ('.$range_colour.' '.$colour_code.' '.$p1.$p_mark.$p2.') ID:'.$colour_id;
}
echo json_encode($results_list);
Echos a list in the form of a JSON array back to the text box and voila, a list. However, the site I'm working on at the moment has about 20 search boxes for various reasons scattered around (user request), does this mean I have to have 20 separate php function pages, each with their own query on, or can a single page be used?
I suspect the java needs modifying a little to call a specific function on a page of multiple queries, but I'm not good with Java, so some help would be greatly appreciated.
I did initially try adding ?action= to the end of the PHP address in the Java script, hoping a GET on the other end would be able to separate the PHP end into sections, but had no luck.
You need to change <?php include('fn-search-em.php'); ?>; to <?php $action = 'mode1'; include('fn-search-em.php'); ?>;.
Then in your fn-search-em.php file, use the $action variable to determine what kind of MySQL query you make.
For example:
if ($action == 'mode1')
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
else
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'mode1' AND deleted = 'no'";
You can do this with by creating a php file with a switch statement to control what code is executed during your Ajax call:
JS:
$.ajax({url: 'ajax.php', method: 'POST', async:true, data: 'ari=1&'+formData,complete: function(xhr){ var availableTags = JSON.parse(xhr.responseText);}});
PHP:
<?php
switch($_REQUEST['ari']){
case 1:
$sql = "SELECT * FROM stock_c_colours WHERE current_c_status = 'current' AND deleted = 'no'";
$result = mysqli_query($conn, $sql);
$results_list = array();
while($row = mysqli_fetch_array($result)){
$colour_id = $row['id'];
$range_name = $row['range_name'];
$range_colour = $row['colour'];
$colour_code = $row['code'];
$p1 = $row['piece_size_1'];
$p2 = $row['piece_size_2'];
if($p1 > 1){$p_mark = 'x';}
else { $p_mark = ''; }
$results_list[] = $range_name.' ('.$range_colour.' '.$colour_code.' '.$p1.$p_mark.$p2.') ID:'.$colour_id;
}
echo json_encode($results_list);
break;
case 2:
// another SQL Query can go here and will only get run if ARI == 2
break;
}
?>
This allows you to keep multiple AJAX handlers in the same file, you just need to pass the index for the desired handler when you make calls to the PHP file or nothing will happen.
Form a php page I am sending some value using json.
$result = mysql_query("SELECT * FROM user_info");
$i=1;
while($row = mysql_fetch_array($result, MYSQL_NUM)) {
if(is_array($row) && count($row)>0)
{
$res['user_name'.$i] = $row[1];
$res['user_email'.$i] = $row[2];
$res['gender'.$i] = $row[4];
$res['i'] = $i;
$i++;
}
}
echo json_encode($res);
I have no problem with this code.But in another page I want to get that data code follows
$.post(urlName, function(data) {
var obj = jQuery.parseJSON ( data );
$noOfUser = obj.i;
alert("No of user- "+$noOfUser);
for($i=0;$i<=$noOfUser;$i++)
{
$user_name = obj.user_name+$i;
$user_emai = obj.user_email+$i;
$gender = obj.gender+$i;
alert("User Name- "+$user_name);
alert("User Email- "+$user_emai);
alert("User Gender- "+$gender);
}
});
But the problem is when I am adding this obj.user_name+$i instead of simple obj.user_name it can't retrieve the data properly but I need to get those value how to do that?
What you are trying to do attempts to get the user_name member of obj and appending the value of $i. Since user_name is not defined, the script fails.
This is because in javascript to access a member of an object using a dynamically generated key you must use the [] accessor, so in your case, the following example should work.
$user_name = obj['user_name' + $i];