Don't show data when i click select form = "id=undefined" - javascript

Help me please.. it show "select_modelcar.php?brandid=undefined" when i choose select form but i try to paste this code in url and define id "select_modelcar.php?brandid=40", have the results. i want to choose same categories in select form such as when i choose brand "Toyota", it'll show all car model in Toyota brand (Camry, Yaris, etc.).
when i click select form >>
past in url and define id >>
select_brandcar.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
</head>
<?php $servername = "localhost";
$username = "root";
$password = "usbw";
mysql_connect($servername,$username,$password);
mysql_select_db("carspecth");
?>
<body>
<script>
function ValueID(){
document.getElementById("getval").innerHTML = ('select_modelcar.php?brandid='+this.value);;
};
</script>
<select name="select_brandcar" id="select_brandcar" onclick="ValueID();" >
<option>Press Choose</option>
<?php
$sql = sprintf ("SELECT * FROM brand" );
$res = mysql_query ($sql);
while ($arr = mysql_fetch_array($res)){
printf ("<option value='%s'>%s</option>" ,$arr['brandid'], $arr['brandname']);
}
?>
<span id="getval"></span>
</body>
</html>
select_modelcar.php
<?php
mysql_query("SET NAMES UTF8");
include 'include_connectdb.php';
#$varbrandid = $_GET['brandid'];
#$sql = sprintf("SELECT * FROM maingeneration WHERE brandfk = %s", $varbrandid);
/*id ของตาราง catagory*/
#$res = mysql_query($sql);
printf("<select name='select' id='select'>");
while ($arr = mysql_fetch_array($res)) {
printf("<option value='%s'>%s</option>", $arr['maingenerationid'], $arr['maingenerationname']);
}
printf("</select>");
?>

Here are some suggestions:
Replace onclick with onchange
Pass the value of the select like this: onchange='ValueID(this.value);'
Then change the function to get that value:
function ValueID(brandid){
document.getElementById("getval").innerHTML = ('select_modelcar.php?brandid='+brandid);;
};

Related

PHP SQL JAVASCRIPT SEARCH NOT WORKING

I am working on a company website where a search bar is used to search the database of customers and employees by there name.
I have the output of the below code (output 1)
but it only searches the firstname and last name individually like this in the output (output 4)i want to make it join together for searching both firstname and lastname.
I want to make a search like this (output 3)
I have this code so far...
index.php
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>INDEX PAGE</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container all">
<br />
<h2 align="center">COMPANY NAME</h2><br />
<div class="form-group">
<div class="input-group">
<input type="text" name="search_text" id="search_text" placeholder="Search by Customer Details" class="form-control" />
</div>
</div>
<div id="result"></div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search.length>=2){
if(search != '')
{
load_data(search);
}
}
else
{
load_data();
}
});
});
</script>
and 2nd file..
fetch.php
<?php
$connect = mysqli_connect("localhost", "root", "root", "users_db")or die("ERROR");
$output = '';
if(isset($_POST["query"]))
{
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM users_users
WHERE firstname LIKE '%".$search."%'
OR lastname LIKE '%".$search."%'
AND lastname LIKE '%".$search."%'
OR link LIKE '%".$search."%'
";
}
else
{
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) > 0)
{
$output .= '
<div class="otp">
</div>
';
while($row = mysqli_fetch_array($result))
{
$output .= '
<div class="oup">
<a href="
'.$row["link"].'
">
'.$row["firstname"].'
'.$row["lastname"].'
</a>
</div>
';
}
echo $output;
}
else
{
echo '';
}
?>
the above code has this output...(output 1)
output 1
and after typing the firstname when i press spacebar it blanksout like in (output 2)
output 2
i want to make the search continue after typing the firstname with spacebar in between..
something like this.. in the (output 3)
output 3
i am new at php javascript and sql so try to break it down for me.
thank you in advance.
can you guys give me some more tricks how to optimise more of this code.
Before i give my answer, I should say your code is open to SQL Injection. You should learn about Prepared Statements to solve this security issue.
Now to answer your question. For searching both firstname and lastname you should separate search term before searching. Something like this:
// --- Separate the search items
if ( !empty($search) ){
$searchWords = explode(' ', $search);
$searchTerms = array();
foreach ($searchWords as $word) {
$word = trim($word);
if (!empty($word)) {
$searchTerms[] = "(firstname LIKE '%$word%' OR lastname LIKE '%$word%')";
}
}
}
// --- Search each search items
$query = "SELECT * FROM users_users WHERE".implode(' AND ', $searchTerms);
Try this:
ALTER TABLE users_users ADD FULLTEXT(firstname, lastname, link);
$searchTerm = '+'.str_replace(' ','+',$search).'*';
$query = "SELECT * FROM users where MATCH(`firstname`,`lastname`,`link`) AGAINST (".searchTerm." IN BOOLEAN MODE)";

How to tell ajax to get the selected data and retrive a data from the database acquired to the selected data

I have 2 select boxes. the first one is to select the brand, the second one to select the product. what I want is that the second select box gets the data from the database which have the same brand_name as the first select box. I don't have any clue about AJAX. I've got this script from a friend but it's not working...
that what is my database look like:
The "brands" database:
brand_id | brand_name
1 | ADIDAS
2 | NIKE
and here is my "product" database:
product_id | brand_name | product_name | product_image | amount | sell | buy
1 | ADIDAS | T-Shirt | none | 50 | 30 | 28
2 | NIKE | Shoes | none | 20 | 130 | 120
and here is my code:
<!DOCTYPE html>
<html>
<head>
<title>TEST | INDEX</title>
<meta charset="utf-8" lang="en">
<script src="ajax.js"></script>
</head>
<body>
<select required="required" name="brand_name">
<option disabled selected>----SELECT----</option>
<?php
require_once 'connections/dbc.php';
$query = "SELECT `brand_name` FROM `brands`";
$response = #mysqli_query($conn, $query);
if (!$response) {
$_SESSION['errortitle'] ='Error loading the brands';
$_SESSION['errormessage'] = 'Something wrong happend while loading the brands.<br/>Please contact The developer';
header("location: error.php");
exit();
} else {
while($row = mysqli_fetch_array($response)){
echo '<option value='.$row['brand_name'].'>'.$row['brand_name'].'</option>';
}
}
?>
</select>
<select required="required" name="product_name" disabled>
<option disabled selected >SELECT</option>
<?php
?>
</select>
<script>
$('[name = "brand_name"]').change(function(event){
var brand_name = $(this).val();
$.get(
"action/ajax.php",
{ brand_name: brand_name },
function(data) {
var opts = $.parseJSON(data);
$.each(opts, function(i, d) {
$('[name="product_name"]').append($('<option>', {
value: d.product_name,
text : d.product_name
}));
});
//Enable the product_name select box
$('[name="product_name"]').prop('disabled', false);
//Refresh the product_name select box
$('[name="product_name"]').selectpicker('refresh');
}
);
});
</script>
</body>
</html>
and here is the ajax.php code:
<?php
require_once '../connections/dbc.php';
$getBrandName = $_REQUEST['brand_name']; // This is the id of the selected brand name
$query = "SELECT 'product_name' FROM `product` WHERE brand_name = '$getBrandName' ";
$response = #mysqli_query($conn, $query);
if (!$response) {
echo "Error loading the prouducts";
echo 'Something wrong happend while loading the proudcts.<br/>Please contact The developer';
exit();
} else {
while($row = mysqli_fetch_array($response)){
$productsArray[]['name'] = $row['product_name'];
}
echo json_encode($brandName);
}
?>
Try this:
<?php
require_once 'connections/dbc.php';
// Get our brands
$query = "SELECT `brand_name` FROM `brands`";
$response = #mysqli_query($conn, $query);
if (!$response) {
$_SESSION['errortitle'] = 'Error loading the brands';
$_SESSION['errormessage'] = 'Something wrong happend while loading the brands.<br/>Please contact The developer';
header("location: error.php");
exit();
} else {
$brands = mysqli_fetch_array($response);
}
?>
<!DOCTYPE html>
<html>
<head>
<title>TEST | INDEX</title>
<meta charset="utf-8" lang="en">
<script>
$(document).ready(function () {
$('[name = "brand_name"]').change(function (event) {
var brand_name = $(this).val();
$.get(
"action/ajax.php",
{brand_name: brand_name},
function (data) {
var opts = JSON.parse(data);
$.each(opts, function (i, d) {
$('[name="product_name"]').append('<option>', {
value: d.product_name,
text: d.product_name
});
});
//Enable the product_name select box
$('[name="product_name"]').prop('disabled', false);
//Refresh the product_name select box
$('[name="product_name"]').selectpicker('refresh');
}
);
});
});
</script>
</head>
<body>
<select required="required" name="brand_name">
<option disabled selected>----SELECT----</option>
<?php
foreach ($brands as $row) {
echo '<option value=' . $row['brand_name'] . '>' . $row['brand_name'] . '</option>';
}
?>
</select>
<select required="required" name="product_name" disabled>
<option disabled selected>SELECT</option>
</select>
</body>
</html>

Identify AJAX errors

I have a php file which has svg embedded in php variable. Using an onclick event on the svg elements displayed (lines with ID's) I want to change the colour of the SVG element and then send a parameter to a mysql table to return the x and y coords etc of other lines which join my selected line.
This part unto sending the parameter to mysql table works fine using ajax in my javascript function:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="application/json" />
<title>Enter Exercises</title>
</head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> </script>
<script type="text/javascript">
function GetPathways(elt)
{
document.getElementById(elt.id).style.stroke = "blue";
var test=elt.id;
var test = document.getElementById(elt.id);
test.setAttribute("x2", "550");
test.setAttribute("y2", "450");
document.getElementById(elt.id).style.visibility = "visible";
var exid = parseInt(elt.id);
$.ajax(
{
type: "POST",
url: 'GetPathways.php',
data: {id: exid},
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(message)
{
alert (message);
},
error: function(xhr, ajaxOptions, thrownError)
{
alert("Error code is....:"+xhr.status);
}
});
};
</script>
Ajax calls php file which executes the sql required to return the table rows (multiple). I have tested the query in my phpAdmin and it works fine retrieving some appropriate rows of data.
Ajax script however only executes error function and not the success function.
The success function will eventually use the ID of the returned svg element to be displayed ie update the webpage based on the onclick event. Seems like a good use of ajax to refresh page without reloading.
GetPathways.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="application/json" />
<title>Get Pathways</title>
</head>
<body>
<?php
//echo "Hello from processing file GetPathways.php"."<br>";
header("Content-Type: application/json");
$dbname = 'TTexercises';
$dbuser = 'dummy entry';
$dbpass = 'dummy entry';
$dbhost = 'localhost:3036';
# set the database connection to be used using php function
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to
Connect to '$dbhost'");
# select the database to be used using php function
mysql_select_db($dbname) or die("Could not open the db '$dbname'");
$id = $_POST['id'];
$query = "SELECT * FROM `PathwayTable` WHERE `EndPathwayID`= $id";
mysql_query($query);
mysql_close($conn);
?>
</body>
</html>
Error code is 200
You have to echo the data inorder to get response from ajax call and also you did not execute the query. change the GetPathways.php as follows
<?
header("Content-Type: application/json");
$dbname = 'TTexercises';
$dbuser = 'dummy entry';
$dbpass = 'dummy entry';
$dbhost = 'localhost:3036';
# set the database connection to be used using php function
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die("Unable to
Connect to '$dbhost'");
# select the database to be used using php function
mysql_select_db($dbname) or die("Could not open the db '$dbname'");
$id = $_POST['id'];
$query = "SELECT * FROM `PathwayTable` WHERE `EndPathwayID`= $id LIMIT 1";
$result = mysql_query($sql);
$value = mysql_fetch_object($result);
mysql_close($conn);
print_r($value);
?>

Display content dynamically with Dropdown (with connection to DB)

im pretty new into this stuff and I just tried to do an AJAX request with Javascript and PDO and PHP to create a dropdown function that reacts dynamically in order to display new content.. Since my knowledge is quite limited here I created it by combining snippets of code I got from various pages and videos. The error is:
Parse error: syntax error, unexpected 'endforeach' (T_ENDFOREACH) in /var/www/xxx/html/listing.php on line 22
This is my listing.php page where the dropdown and the new content should be displayed:
<!DOCTYPE html>
<html>
<head>
<title>listing</title>
<meta charset="UTF-8">
<meta name="description" content="">
<meta name="author" content="">
<meta name="keywords" content="">
<link href=".css" type="text/css" rel="stylesheet">
<link href="favicon.ico" type="image/x-icon" rel="shortcut icon">
</head>
<body>
<select name="user" id="user-select">
<option value="">Choose a user</option>
<?php foreach ($subjects->fetchAll() as $user); ?>
<option value="<?php echo $user['subject_id']; ?>"><?php echo $user['subject']; ?></option>
<?php endforeach; ?>
</select>
<div id="user-profile"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="js/global.js"></script>
This is the global.js file:
$('#user-select').on('change', function() {
var self = $(this);
$.ajax({
url: 'https://www.xxx.de/partials/user.php',
type: 'GET',
data: { user: self.val() },
success: function(data){
$('#user-profile').html(data);
}
});
});
And the partials/user.php, which contains the connection to the database:
<?php
$dsn = "xxx";
$user = "xxx";
$pw = "xxx";
try {
$pdo = new PDO($dsn, $user, $pw);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
if (isset($_GET['user'])) {
$userQuery = "
SELECT
subjects.subject_id,
subjects.subject,
FROM subjects
WHERE subjects.subject_id = :subject_id
";
$user = $pdo->prepare($userQuery);
$user->execute(['subject_id' => $_GET['user']]);
$selectedUser = $user->fetch(PDO::FETCH_ASSOC);
print_r($selectedUser);
}
?>
Any help is appreciated and I am thankful for any tips !
Stupid mistake.. I simply forgot to include the connection on the listing.php page to fill the foreach loop.
->
On listing.php before the !DOCTYPE html begins:
<?php
$dsn = "xxx";
$user = "xxx";
$pw = "xxx";
try {
$pdo = new PDO($dsn, $user, $pw);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$usersQuery = "SELECT fach_id, fach FROM faecher";
$users = $pdo->query($usersQuery);
?>
Try replacing ; with : in php foreach statement
<?php foreach ($subjects->fetchAll() as $user): ?>

PHP echo, outputting full html code (undesired) before object (desired)

When I echo $jsonstring, seemingly a whole blank html page is sent over (from PHP to Javascript) with the object I requested. Super new all around here, so I don't get why.
my php code:
<?php
//ini_set('display_errors', '1');
//ini_set('error_reporting', E_ALL);
require "localdbcxn.php";
$encoded = file_get_contents('php://input');
$decoded = json_decode($encoded, true);
$email = $decoded['email'];
$password = $decoded['password'];
$identify = mysql_query("SELECT UserId FROM users WHERE UserEmail='$email' AND UserPassword='$password'");
$numrows = mysql_num_rows($identify);
$row = mysql_fetch_assoc($identify);
$userid = $row['UserId'];
$sessionid = mt_rand(1111111111111111,9999999999999999);
$sessionkey = mt_rand(1111111111111111,9999999999999999);
$logindate = date("Y-m-d H:i:s");
$login = "INSERT INTO mobileSession (UserId, SessionId, SessionKey, BeginDate) VALUES('$userid','$sessionid','$sessionkey','$logindate') ON DUPLICATE KEY UPDATE SessionId='$sessionid', SessionKey='$sessionkey', BeginDate='$logindate' ";
if ($numrows == 1) {
mysql_query($login);
$session = array('UserId'=>$userid,'SessionId'=>$sessionid);
$jsonstring = json_encode($session);
echo $jsonstring;
}
?>
Here's what the console(log) shows:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Untitled Document</title>
</head>
<body>
</body>
</html>{"UserId":"33","SessionId":8207219793564744}
From UserID til ...4744 is correct, but can anyone help me understand why the html code is being echoed? In my limited experience, I haven't seen this before, and feel that I am doing something wrong.
Thanks!
you must specify the content type before printing json data. before echo set header -
header('Content-type: application/json');

Categories

Resources