i am trying to make an search box which search the name from elastic search database, but when i run the it always give me an error that ----
Notice: Undefined index: value in the line --> $query = $_GET['search_keyword'];
but from my script i believe it should get the "search_keyword".
Search box --
<form method="GET" action="/latest/helloTestData">
<input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">
</form>
Script --
<script>
$(function () {
var minlength = 3;
$("#sample_search").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
$.ajax({
type: "GET",
url: "/latest/helloTestData", // address to the php function
data: {
'search_keyword' : value
},
dataType: "text",
success: function(msg){
//we need to check if the value is the same
if (value==$(that).val()) {
//Receiving the result of search here
}
}
});
}
});
});
</script>
PHP ---
public function helloTestDataAction() {
$paramss = array('hosts' => array('localhost:9200'));
$client = new Elasticsearch\Client($paramss);
$query = $_GET['search_keyword'];
if ($query != "") {
$params = array();
$params['size'] = 1000000000;
$params['index'] = 'myindex';
$params['type'] = 'mytype';
$params['body']['query']['bool']['must'] = array(
array('match' => array('name' => $query)), // search data by input data
);
$esresult = $client->search($params);
if ($esresult < 1) {
echo "Your search did not match any documents. Please try different keywords.";
} else {
echo $esresult; //results found here and display them
}
}
return new Response('ok');
}
Can anyone knows how to fix this problem. Thanks a lot in advanced.
Modifiy $_GET['value'] into $_GET['search_keyword']
So
public function helloTestDataAction() {
[...]
$_GET['search_keyword'];
[...]
}
You're searching for a key that will not be into $_GET array, as, into your ajax request, you're passing a key named search_keyword and so this is the error
Simply replace
$_GET['value'] to $_GET['search_keyword']
Quick and simple! The front-end pass the typed text via GET by url.
In this test I put the 2 files in the same folder. Change as you need.
Front-end:
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.js"></script>
<div id="my_header" style="background-color:lightblue">
</div>
<input type="text" id="foo" value="bar" onkeyup="loadlink(this)" />
<script>
function loadlink(e){
$('#my_header').load('back.php?var='+e.value,function () {
$(this).unwrap();
});
}
</script>
Back-end (back.php):
<?php
echo "received: " . $_GET["var"] . ' <br>at ' . gmdate('Y-m-d h:i:s \G\M\T', time());
?>
Related
In my web application just I trying to returning JSON data from MySQL database using PHP and AJAX query. This is where I follow a tutorial on internet. In case in my application it shows and error like;
data = "↵↵↵↵Notice: Undefined index: lymph in
C:\xampp\htdocs\Hospital\hospitalwebsite\test_query\fetch_count.php
on line 29
Here is my AJAX Code :-
<script>
$(document).ready(function () {
$('select').material_select();
$('#search').click(function () {
var id = $('#test_list').val();
if (id != '') {
$.ajax({
url: 'test_query/fetch_count.php', // Url to which the request is send
method: 'POST', // Type of request to be send, called as method
data: { id: id },
//dataType:"JSON",
success: function (data) {
$('#success_mes').fadeIn().html(data);
$('#test_info').css('display', 'block');
$('#1').text(data.WBC);
$('#2').text(data.lymph);
$('#3').text(data.Mid);
}
});
} else {
alert('sdsd');
$('#test_info').css('display', 'none');
}
});
});
</script>
Below is the PHP Code :-
<?php
session_start();
require_once "../phpquery/dbconnection.php";
if (isset($_POST['id'])) {
//$id = $_POST['id'];
$stmt = $con->prepare("SELECT * FROM testing_report WHERE testing_report_id = ? AND test_id='7' ");
$stmt->bind_param("s", $_POST['id']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0);
while ($row = $result->fetch_assoc()) {
$medRecords = json_decode($row['testing_results'], true);
if (is_array($medRecords) || is_object($medRecords)) {
foreach ($medRecords as $key => $object) {
$data["WBC"] = $object['WBC'];
$data["lymph"] = $object['lymph'];
$data["Mid"] = $object['Mid'];
}
}
}
echo json_encode($data);
}
?>
SQL schema
Really I am appreciating if someone can help me. Thank you
The issue is that your data structure is split over several array elements, something like...
[
{
"WBC": "1"
},
{
"lymph": "5"
}
]
so each loop round the array only has 1 piece of information. This code combines all of that data into 1 set of information using array_merge() and then extracts the data from the result.
I've also added ?? 0 to default the values to 0 if not present, there may be a better default value.
$data = [];
$medRecords = json_decode($row['testing_results'], true);
if (is_array($medRecords) || is_object($medRecords)) {
$medRecords = array_merge(...$medRecords);
$data["WBC"] = $medRecords['WBC'] ?? 0;
$data["lymph"] = $medRecords['lymph'] ?? 0;
$data["Mid"] = $medRecords['Mid'] ?? 0;
}
JQuery work file if the result be json:
$(document).ready(function(){
$('#search').click( function () {
$.ajax({
url: "https://reqres.in/api/users?page=2",
method: "GET",
success:function(data)
{
console.log("page:", data.page);
console.log(data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="search">Search</button>
i think you have to add correct header to your result:
<?php
header('Content-Type: application/json');
add this code into first line of your php page. then jQuery know result is json.
I am building now a Queuing system for my helpdesk system. i have problem in detecting the changes of input value. I want to play the play_sound() function sound when the value of input is incremented. the curent value of input is coming from the rowCount in my SQL Query stored in variable.
screenshot picture link
Input
<input disabled type="text" id="needapproval" id="approval" value="0" class="center" />
My Script
<script type="text/javascript">
function play_sound() {
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', 'Kalimba.mp3');
audioElement.setAttribute('autoplay', 'autoplay');
audioElement.load();
audioElement.play();
}
activateMagic();
function activateMagic() {
setInterval(realTimeData, 1000);
function realTimeData() {
$.ajax({
url: './includes/needapproval.php',
method: 'GET',
dataType: "json",
success: function(res) {
$("#needapproval").val(res.data_count);
},
error: function(err) {
console.log(err);
}
});
}
}
</script>
PHP
require_once "connection.php";
class NeedApprovalStatus extends Connection{
public function needApproval() {
$count_approval = "SELECT * FROM job_request WHERE approval_status LIKE '%Need Approval%' ";
$stmt_count_approval = $this->db->prepare($count_approval);
$stmt_count_approval->execute();
$count = $stmt_count_approval->rowCount();
$data_count = [];
if ($count == 0) {
$data_count = [
'data_count' => 0
];
} else {
$data_count = [
'data_count' => $count
];
}
echo json_encode($data_count);
}
}
$need_approval = new NeedApprovalStatus;
$need_approval->needApproval();
I tried to use onchange event in jquery but it doesn't work. because i think onchange only trigger when you change value on input manually. Any ideas guys?
It would be easier to check the value inside the success function and call play_sound() from there.
function activateMagic() {
var value = 0;
setInterval(realTimeData, 1000);
function realTimeData() {
$.ajax({
url: './includes/needapproval.php',
method: 'GET',
dataType: "json",
success: function(res) {
var newValue = res.data_count;
if(newValue != value) {
play_sound()
$("#needapproval").val(value);
value = newValue;
}
}
...
PHP function
function getSerialNumber(){
$upload_dir = wp_upload_dir();
$csvFile = $upload_dir['baseurl'].'/sample.csv';
$csv = $this->csv_to_array($csvFile); //read csv
foreach ($csv as $serialnum){
$serial_num_array[] = $serialnum['product_serial'];
}
$json_array = json_encode($serial_num_array);
return $json_array;
}
Return Value
["123456","789012"]
User input
<input name="product_serial" type="text" class="form-control login-field"
value="<?php echo(isset($_POST['reg_product_serial']) ? $_POST['reg_product_serial'] : null); ?>"
placeholder="Product serial number *" id="reg-product-serial" required/>
JS Code:
<script>
jQuery(document).ready(function($){
$.ajax({
url: "registration-form.php&f=getSerialNumber",
type: "GET"
success: function(data){
console.log('eureka');
}
});
$('input#reg-product-serial').on('blur', function() {
alert($(this).val()); //alerts user input
});
});
</script>
I am unable to call PHP function and pass json values in JS code to compare user input value for reg_product_serial.
How to fetch user input entered for product_serial and validate it
with php array returned ?
If that user input does not exists in array validate user by alert
message.
I didn't quite understand why do you have an ajax request to the form and why it's on the document ready event.
As far as I understood, the following is the code I came up with.
I haven't tested it but it should be enough for understanding the direction and main idea.
If you'd need further help add a comment.
validSerials.php
function compareSerialNumber($userSerial){
$validSerial = 0;
#Consider sanitizing the $userSerial variable (!!)
$upload_dir = wp_upload_dir();
$csvFile = $upload_dir['baseurl'].'/sample.csv';
$csv = $this->csv_to_array($csvFile); //read csv
foreach ($csv as $serialnum){
if($userSerial == $serialnum['product_serial'])
$validSerial = 1;
}
echo $validSerial;
}
echo compareSerialNumber($_GET['userSerial']);
die();
JS
<script>
jQuery(document).ready(function($){
$('input#reg-product-serial').on('blur', function() {
$.ajax({
url: "validSerials.php",
data: {userSerial: $(this).val() },
type: "GET"
success: function(res){
if(res == 1)
alert('Valid Serial');
else
alert('Invalid Serial');
}
});
});
});
</script>
I am trying to set up search for a table within database in mine within the Laravel 4 PHP Framework. I am using jquery to accomplish this. I have a table "artists", that I am trying to allow a user to search through. I have a model "Artist.php", and a controller "SearchController.php" that I am using to control the logic. Finally, I have a view "search.blade.php" that I am using as the user facing file. Here is the relevant code:
SearchController.php:
public function show_search() {
$limit = 10;
if(isset($_GET['mode']) && !empty($_GET['mode'])) {
switch($_GET['mode']) {
case 'autocomplete':
if(isset($_GET['keywords']) && !empty($_GET['keywords'])) {
$query = htmlspecialchars($_GET['keywords']);
$query = mysql_real_escape_string($query);
$results = Artist::search_artists($query);
$data = array();
$i = 0;
if(isset($results) && !empty($results)) {
foreach($results as $result) {
if (strlen(strstr($result->stage_name, 'artists')) == 0) {
if($i < $limit) {
$data[$i] = $result;
$i++;
}
}
}
}
exit;
}
break;
}
}
return View::make('search.search');
}
Artist.php:
public static function search_artists($query) {
$search_artists = DB::table('artists')
->where('artists.stage_name', 'LIKE', $query)
->orderBy('created_at', 'DESC')
->get();
return $search_artists;
}
search.blade.php:
<input type="text" class="search" id="inputSearch" /><br />
<div id="divResult"></div>
<script type="text/javascript">
$(function(){
$(".search").keyup(function() {
var inputSearch = $(this).val();
var data = {mode : 'autocomplete', keywords : inputSearch};
if(inputSearch!='') {
$.ajax({
type: "GET",
url: "/search/search",
data: data,
cache: false,
success: function(html) {
console.log(html);
$("#divResult").html(html).show();
}
});
}
return false;
});
});
</script>
I call all of this with the route:
Route::get('/search/search', array('uses' => 'SearchController#show_search'));
When I run this and I type things into the search box, I see in the javascript console it reads:
event.returnValue is deprecated. Please use the standard event.preventDefault() instead.
and the results don't display under the search box. Any idea what could be going wrong? Thank you for your help.
The javascript warning is caused by your return false;. If you need it (doesn't seem necessary for the keyup event unless you want to catch the enter key), you should do something like:
$(".search").keyup(function(e) {
e.preventDefault(); // prevent the default action of the event
I am not familiar with Laravel, but it seems to me that you are not getting any results because you are not doing anything with the $data variable in your controller.
I would guess you need something similar to:
return View::make('search.search', $data);
to pass the variable to your view.
I have done to make control autocomplete, but I have a problem to post data with jquery.
<input type="text" id="matakuliah" class="med" name="matakuliah">
<script type="text/javascript">
$(this).ready( function() {
$("#matakuliah").autocomplete({
minLength: 1,
source:
function(req, add){
$.ajax({
url: "<?php echo site_url('bahanAjar/lookup'); ?>",
dataType: 'json',
type: 'POST',
data:req,
success:
function(data){
if(data.response =="true"){
add(data.message);
}
},
});
},
});
});
</script>
on my controller
function lookup(){
// process posted form data (the requested items like province)
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->matakuliah_model->lookup($keyword); //Search DB
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id_matakuliah'=>$row->id,
'value' => $row->matakuliah,
''
); //Add a row to array
}
}
if('IS_AJAX')
{
echo json_encode($data); //echo json string if ajax request
}
else
{
$this->load->view('admin/bahan_ajar/form_manage_file_view', $data); //Load html view of search results
}
}
The code work it well, but I want to add parameter to call database.
$query = $this->matakuliah_model->lookup($keyword, $id_matakuliah);
like this. how I can get
$this->input-<post('id_matakuliah')
from jquery before.;
and I have another textbox for fill value of autocomplete from textbox matakuliah.
`<input type="hidden" id="matakuliah_post" class="med" name="matakuliah_post">`
When I'm use autocomplete textbox automatic fill another textbox, please help me.
In this case req will contain {term:"your search term"}. Your can extend this javascript object to pass extra data. If you want to post id_matakuliah, you can assign its value like following before $.ajax call:
req.id_matakuliah = "Whatever you want to send";