My problem is that I need to be able to use random values from index.php´ in ajquery`function. I'm kind of stuck in the process.
I have an sql table that contains two columns country and dish.
In my index.php I call the data-base and import the value to an array witch gives my random selection from the database. I store that in two variables $country and $dish
<?php
$sql = 'SELECT country, dish FROM countries_dishes ORDER BY id';
$result = mysqli_query($conn, $sql);
$dishes = mysqli_fetch_all($result, MYSQLI_ASSOC);
$random_countries = $dishes[array_rand($dishes)];
$country = $random_countries['country'];
$dish = $random_countries['dish'];
?>
Then I load the php variables in my script.js like so:
var randCountries = <?php echo json_encode($country); ?>;
var randDish = <?php echo json_encode($dish); ?>;
console.log(randCountries);
console.log(randDish);
$(document).ready(function(){
$('#btn-select').click(function(){
var country = randCountries;
var dish = randDish;
console.log(country);
});
});
when I refresh the page I can see random values from console.log(randCountries); and console.log(randDish);
but the console.log(country); is always showing Antartica when the #btn-select button is clicked.
The thing is that I don't want to refresh the page each time to get random values. I need to be able to get the random values from var randCountries and var randDish to the jquery function in some way or another.
Can someone help me out here?
Related
i have a table 'class' with thier fee structure. i want to show fee amount if a particular class is selected by user.
i'm able to fetch only one value from database want ot show multiple value..
here is my db table:
here are my codes:-
fetch.js
$('#class').click(function(){
$.getJSON(
'fetch2.php',
'class=' + $('#class').val(),
function(result){
$('#tution_fee').empty();
$.each(result.result, function(){
$('#tution_fee').append('<option>'+this['tution_fee']+'</option>');
});
}
);
});
fetch.php
<?php
define('HOST','localhost');
define('USERNAME', 'root');
define('PASSWORD','');
define('DB','bethel');
$con = mysqli_connect(HOST,USERNAME,PASSWORD,DB);
$class = $_GET['class'];
$sql = "SELECT tution_fee FROM class WHERE class='$class'";
$res = mysqli_query($con,$sql);
$result = array();
while ($row = mysqli_fetch_array($res)) {
array_push($result,
array('tution_fee'=>$row[0])
);
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
first one is fetch.js and second fetch.php
here you can see the JS code that one value can be fetched from database but i want to fetch multiple value.
please help
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.
I'm sending array from Php to Javascript, then I try to generate a div for each value of that array to display them in html, but instead of making a div for each independent value it stacks them all on a single one. It seems the array I'm making in php arranges all the values from my database into single string.
How can I separate them?
Here's how the error looks upfront
Here's part of my code:
Php:
$query= "SELECT titulo FROM notas WHERE usuario_idusuario = '".$ide."'";
//Runs the search
$resultado = $conn->query($query);
if($resultado->num_rows>0){
while($row = $resultado->fetch_assoc()){
//inserts result in an array
$contenido= array('titulo'=> $row['titulo']);
//json_encode
$objJson = json_encode($contenido["titulo"]);
//sends the array to javascript
echo "$objJson\n";
}
}else{
echo "Error";
}
$conn->close();
?>
javascript:
//response receives the array
success: function(response){
console.log(response);
console.log(response.length);
var contenidoInt = new Array();
contenidoInt = [{
"titulo":response
}];
console.log(contenidoInt);
console.log(contenidoInt[0].titulo);
}
I hope someone can help me, thanks.
In changename.php I have this DIV:
<div id="resultDiv"></div>
In the same file I have the PHP code:
<?php
include_once ('connect.php');
if(isset($_POST['name']))
{
$postedname = $_POST['name'];
$safename = mysqli_real_escape_string($con, $postedname);
$checkname = "SELECT * from accounts where name='$safename' LIMIT 1";
$query = mysqli_query($con, $checkname);
$row = mysqli_num_rows($query);
if($row) {
echo 'Name is already taken!';
} else {
$changename = "UPDATE accounts SET name='$safename' WHERE Name='$_SESSION[username]'";
$query = mysqli_query($con, $changename);
if($query)
{
echo 'Name is changed!';
$_SESSION['username'] = $safename;
}
}
}
?>
And this is my Jquery script (in a seperate file):
$(function(){
$("form").submit(function() {
event.preventDefault();
var name = $('#inputName').val();
$.post("changename.php",
{
name: name
},
function(data)
{
$("#resultDiv").text(data);
});
});
});
The code is just working fine, it successfully changes my name. If I want my name to be 'John', it successfully changes it in the DB.
The problem is, it's supposed to change the div with ID resultDiv to Name is already taken!. Instead of that, it takes the whole changename.php HTML code and puts it into that DIV. So instead of 1 line, I have 100+ lines of my page in there. So it looks like this:
https://gyazo.com/9320a5f15ed67a8ad9298d6172ab6909
Any idea why it's not just the message I want?
Ajax will fetch all data from file given as url for it.
If you want to avoid that, you have 2 options.
Write condition in changename.php in such a way that only update to db part will be executed.
On changename.php keep only required code to update to db.
I am trying to create a D3 line graph that will display a graph specific to the item that is selected in the drop-down menu. I have one script that queries my MySQL database and fills a drop-down menu with all of the correct options. From there, I want to click on an option and go to another page that creates a line graph based off of that selection. When I click on an option, I use json_encode to create a JSON object that should be compatible with D3.
I have another script that deals completely with drawing the graph and try to use d3.json to get the JSON object that is created when the specific selection is clicked. Whenever I try to load the graph page, it is completely blank. I am not sure if what I am trying to do is even possible. I have not tried including the drop-down in the same script as the one that creates the graph but do not think that I will be able to get the information from the database the same way.
Any guidance or suggestions would be greatly appreciated. I can post the code later if it is determined what I am trying to do is possible. Thanks!
EDIT:
This is the script that queries my database for the users that are put in the drop-down menu and then queries the database again for that selection's data. The drop-down menu has the desired result and the data is correctly echoed as well.
<?php
if (isset($_POST['name']))
{
$out = $_POST['name'];
$temp = explode(",", $out);
$populate_selection = "SELECT id, lastname, firstname FROM users WHERE id != '$temp[0]' ORDER BY lastname";
$out = $temp[1] . ', ' . $temp[2];
$student_hours = "SELECT ai_averages.user_id, ai_averages.title, ai_averages.hours FROM ai_averages INNER JOIN users ON ai_averages.user_id = users.id WHERE $temp[0] = ai_averages.user_id";
}
else
{
$temp[0] = " ";
$populate_selection = "SELECT id, lastname, firstname FROM users ORDER BY lastname";
$student_hours = "SELECT ai_averages.user_id, ai_averages.title, ai_averages.hours FROM ai_averages INNER JOIN users ON ai_averages.user_id = users.id WHERE $temp[0] = ai_averages.user_id";
$out = " ";
}
$result = $mysqli->query($populate_selection);
$option = "<option value= '{$temp[0]}'>$out</option>";
while($row = mysqli_fetch_assoc($result)) {
$option .= "<option value = '{$row['id']}, {$row['lastname']}, {$row['firstname']}'>{$row['lastname']}, {$row['firstname']} </option>";
}
if($student_results = $mysqli->query($student_hours))
{
$data = array();
for ($x = 0; $x < mysqli_num_rows($student_results); $x++)
{
//this array contains the data that I want in my graph
//the correct data is echoed every time that I click on the different choices
$data[] = mysqli_fetch_assoc($student_results);
}
echo json_encode($data, JSON_PRETTY_PRINT);
}
?>
<form id = "hello" method = "POST" >
<select name = "name" onchange = 'this.form.submit()'> <?php echo $option; ?> </select>
</form>
I then try and use d3.json("filename.php", etc) to get the information from the $data array but this has not worked.