I'm trying to automate my textfield of webform with auto search from database, where I have been trying it from many days. What I see is I get all the data which I typed but not with the data in the database. Can anyone help me out of this?
<script>
$(document).ready(function(){
$('input.module_nbr').module_nbr({
name: 'module_nbr',
remote:'search.php?key=%QUERY',
limit : 3
});
});
</script>
<?php
$key=$_GET['key'];
$array = array();
$dbc = mysqli_connect('','', '', '') OR die(mysqli_connect_error());
date_default_timezone_set("Asia/Calcutta");
$query=mysqli_query("select module_nbr from module_master where module_nbr LIKE '%{$key}%'");
while($row=mysqli_fetch_assoc($query));
{
$array[] = $row['module_nbr'];
}
echo json_encode($array);
?>
This will be a piece of code where I'm going to implement it in almost all fields of my form to reduce typing to the user.
Related
I have a small problem. I would like to insert SQL table information into a predefined Javascript code. I know how it works with PHP but I have never done it with Javascript and so I need your help.
I am a total beginner.
SQL Table:
Date_begin | Date_end | Text
-----------|----------|-----
03/2002 |07/2020 |test1
05/2002 |08/2020 |test2
... |... |...
PHP SQL Query (PDO):
<?php
$Date_begin = $connection->query("SELECT Date_begin FROM `test_table`");
$Date_end = $connection->query("SELECT Date_end FROM `test_table`");
$Text = $connection->query("SELECT Text FROM `test_table`");
?>
Predefined static JavaScript Code where the Information must be put in:
<script>
['03/2002', '07/2020', 'test1'],
['05/2002', '08/2020', 'test2'],
....
</script>
My attempt to solve it to make it dynamic:
<script>
var Date_begin = <?php echo $Date_begin ?>;
var Date_end = <?php echo $Date_end ?>;
var Text = <?php echo $Text ?>;
begin loop
['XXX', 'XXX', 'XXX'], // SQL Row 1
['XXX', 'XXX', 'XXX'], // SQL Row 2
['XXX', 'XXX', 'XXX'], // SQL Row 3
... // SQL Row n
end loop
</script>
Now I need to generate the above lines dynamic and fill it with the SQL Information. I think I need a loop but I don't know the syntax. I also don't know if I passed the variables from PHP to JavaScript correctly.
Thanks for any help and answer.
At the moment, you are not fetching any data, just executing the queries. Note that you only need one query since you are fetching all the data from the same table with the same conditions (in this case, none). You can get a JavaScript array of data directly from your PHP code by using json_encode.
Your code should look something like this:
<?php
$result = $connection->query("SELECT Date_begin, Date_end, Text FROM `test_table`");
if (!$result) {
// deal with error
}
$data = $result->fetchALL(PDO::FETCH_NUM);
?>
<script>
var data = <?php echo json_encode($data, JSON_UNESCAPED_SLASHES); ?>
// process data array
</script>
I realize that there are several similar questions that have been asked, but none of those have been able to get me over the top. Maybe what I wnat to do is just not possible?
I have a page on which there is an order form. The admin can create an order for any user in the database by selecting them in the dropdown menu and then fill out the form. But each user may have a PriceLevel that will give them a discount. So I need to be able to make a database call based on the username selected in the dropdown and display their price level and be able to use the username and pricelevel variables in my PHP.
I have the an add_order.php page on which the form resides, and an ajax.php which makes a quick DB call and returns the results in a json format.
The problem I am running into is actually getting the information from jQuery into the PHP. I have tried using the isset method, but it always comes back as false.
Here's what I have:
add_order.php
<?php
// $username = $_POST['orderUser']['Username'];
$username = isset($_POST['orderUser']) ? $_POST['orderUser']['Username'] : 'not here';
echo 'hello, ' . $username;
?>
...
$('#frm_Username').change(function() {
orderUser = $(this).val();
$.post('/admin/orders/ajax.php', {
action: 'fetchUser',
orderUser: orderUser
}
).success(function(data) {
if(data == 'error') {
alert('error');
} else {
console.log(data);
}
})
})
ajax.php
<?php
$action = $_POST['action'];
if($action == "fetchUser"):
$un = $_POST['orderUser'];
/*if($un):
echo $un;
exit;
endif;*/
// SET THE REST UP WITH MYSQL
if($un):
$qid = $DB->query("SELECT u.Username, u.PriceLevel FROM users as u WHERE u.Username = '" . $un . "'");
$row = $DB->fetchObject($qid);
// $row = jason_decode($row);
echo json_encode($row);
exit;
endif;
echo "error";
endif;
?>
I am logging to the console right now and getting this:
{"Username":"dev2","PriceLevel":"Tier 2"}
Any help would be appreciated. Thanks.
After calling $.post('/admin/orders/ajax.php', ...), the PHP code which sees your POSTed variable is ajax.php.
You need to check in there (inside ajax.php), whereas currently your isset check is in add_order.php, which does not see the POST request you send.
You do seem to have some logic in ajax.php, but whatever you've got in add_order.php is not going to see the data in question.
I'm using ajax to send a search string to a php script that executes a mysql like function to find all related entries with the username like the string being sent for friend searching. I have two current entries in the database zukeru and zukeru2. when i search z i only get zukeru returned in my console output. When i search 2 i still get zukeru and im really not sure why.
Also how to i remove a specific field from a php nested tupple. I don't want to include the password field for obvious reason. Sorry im new to php learning as i go so far its not as bad as I thought it would be kinda similar to python.
returned object when searching the number 2, but i get zukeru and not zukeru2 doesn't make sense.
Object {0: "2", 1: "you wish you could see", 2: "zukeru", 3: "deleted for security", 4: "grant", id: "2", email: "deleted for security", username: "zukeru", password: "deleted for security", name: "grant"}
this is the search string i used for the above result. You can see i searched 2 and got back zukeru and not zukeru2
profile.php:92 searchstring=2
<?php
$db = new mysqli(security reasons removed.);
extract($_POST);
//I think i can remove this session start ?
session_start();
$serach_string = $_POST['searchstring'];
$fetch=$db->query("SELECT * FROM users WHERE username LIKE '%$serach_string%'");
$friends=mysqli_fetch_array($fetch);
//echo $search_string
echo json_encode($friends);
?>
Here is my jquery incase you wanted to see
function search(){
var url = "search_friends.php";
$.ajax({
type: "POST",
url: url,
data: $("#search_friends").serialize(), // serializes the form's elements.
success: function(data)
{
//console.log(data);
var returned_friends = JSON.parse(data);
var html_built = '<br>';
console.log(returned_friends);
console.log($("#search_friends").serialize());
if (returned_friends){
$.each( returned_friends, function( key, value ) {
if (key =="username"){
html_built += '<li><a href="#"><button class="btn btn-primary" style="width:100%;" id="'+value+'" onClick="add_friend(this.id)"> Send '+value+' A Friend Request</button></li>';
}
});
}
html_built += ""
document.getElementById("list_friends").innerHTML = html_built;
}
});
return false;
}
this is what im currently using and I get undefined method. It cant find fetch_all(); and im using php 5.4
here is the console error returned.
<br />
<b>Fatal error</b>: Call to undefined method mysqli_result::fetch_all() in <b>/home/gzukel/public_html/search_friends.php</b> on line <b>7</b><br />
<?php
$db = new mysqli();
extract($_POST);
session_start();
$serach_string = $_POST['searchstring'];
if($fetch=$db->query("SELECT username FROM users WHERE username LIKE '%$serach_string%'")){
$friends=$fetch->fetch_all();
echo json_encode($friends);
}else{
echo 'no results';
}
?>
so something like this?
<?php
$db = new mysqli();
extract($_POST);
session_start();
$serach_string = $_POST['searchstring'];
$fetch=$db->query("SELECT * FROM users WHERE username LIKE '%$serach_string%'");
$friends=[]
while($row = $fetch->fetch_array())
{
$rows[] = $row;
}
foreach($rows as $row)
{
array_push($friends,$row['username']);
}
//echo $search_string
echo json_encode($friends);
?>
You Could use fetch all:
if($fetch=$db->query("SELECT username FROM users WHERE username LIKE '%$serach_string%'")){
$friends= $fetch->fetch_all();
echo json_encode($friends);
}else{
echo 'no results';
}
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'm using jQuery autocomplete with PHP source file that connects to MySQL and get the info to show as autocomplete on input field. Here's my code:
Index/Input
<script>
$(function() {
$("#search").autocomplete({
source: 'http://localhost/testes/autocomplete.php',
minLength: 3
});
});
</script>
<input type="text" id="search"/>
autocomplete PHP
$req = "SELECT DISTINCT name FROM faculty WHERE name LIKE '%".$_REQUEST['term']."%'";
$query = mysql_query($req);
while($row = mysql_fetch_array($query)){
$results[] = array('label' => $row['name']);
}
echo json_encode($results);
The problem is, it returns good values and other null values. But, in the last case, the values should not be null because they are in the database.
For example, in the database I have the entries:
ISCTE - Instituto Universitário
INDEG-ISCTE Business School
Searching by 'iscte' the autocomplete gives second one but the first one appear as null.
Thank you for you time,
Regards,
Hugo
That is because the encoding. Use this:
...
while($row = mysql_fetch_array($query)){
$results[] = array('label' => utf8_encode($row['name']));
}
...
Your database should set to UTF8, but by the way, this fix it.