Good morning all,
I am using materialize.css in a PHP app
I will want to initialize the auto-complete data with an API call.
The .autocomplete () initializes the data with a JSON array " data ":,
which I get with the .ajax ({..., url: '/search.php', ... datas}).
but I can't inject the datas into the.autocomplete (),
how can I do it?
Here is the source code:
<body>
<form action="">
<div class="row">
<div class="col s12">
<div class="row">
<div class="input-field col s6">
<i class="material-icons prefix">title</i>
<input id="searchOnAPI" name="name" type="text" class="autocomplete" value="{{ item.name }} ">
<label for="searchOnAPI">{{ siteData('admin.titre') }}</label>
<ul id="autocomplete-content" class="autocomplete-content"><li><a></a></li></ul>
</div>
</div>
</div>
</div>
</form>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>
<script>
$(document).ready(function () {
$('#searchOnAPI').keyup(function () {
$('#autocomplete-content').html('');
let search = $(this).val();
if (search !== "") {
$.ajax({
type: 'GET',
url: '/search.php',
data: 'search=' + encodeURIComponent(search),
success: function (datas) {
if (datas !== "") {
$('#searchOnAPI').autocomplete(datas);
} else {
document.getElementById('autocomplete-content').innerHTML = '<ul class="autocomplete-content dropdown-content"><li><a class="black-text">{{ siteData('site.search.nodata') }}</a></li></ul>';
}
}
});
}
});
});
</script>
I think the problem comes from here:
The variable datas ...
but I don't understand the error anymore.
success: function (datas) {
if (datas !== "") {
$('#searchOnAPI').autocomplete(datas);
}
the code of the search page:
and call API
<?php
if (isset($_GET['search']) && !empty($_GET['search'])) {
$search = trim(htmlspecialchars($_GET['search']));
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.themoviedb.org/3/search/multi?api_key=". API_KEY ."&language=fr-FR&query=$search",
CURLOPT_CAINFO => dirname(__DIR__) . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR ."cert.tmdb.cer", //api.themoviedb.org
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 10,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET"
]);
$response = curl_exec($curl);
$err = curl_error($curl);
$response = json_decode($response, true);
$err = json_decode($err, true);
$datas = [];
if (!is_null($err) || $response === null || !isset($response['results'])) {
$datas[] = ['No Data' => null];
} else {
$response = $response['results'];
for ($i = 0; $i <= 5; $i++) {
if (isset($response[$i]['title'])) {
$datas[] = $response[$i]['title'] ;
} elseif (isset($response[$i]['name'])) {
$datas[] = $response[$i]['name'];
}
}
echo json_encode(array_fill_keys(['data'], array_fill_keys($datas, null)), true);
}
}
and here is the api return in json of the search page
{
"data": {
"O Amor Acontece": null,
"Quem Quer Namorar Com o Agricultor?": null,
"O'": null,
"O Clone": null,
"Hawaï police d'État": null,
"O Matador": null
}
}
Any advice is welcome!
.EDD
Your PHP code is returning a json object with a 'data' parameter, maybe you could try
if (datas !== "") {
$('#searchOnAPI').autocomplete(datas.data);
}
I found the error:
$.ajax({
type: 'GET',
url: '/search.php',
data: 'search=' + encodeURIComponent(search),
success: function (datas) {
I did not set the dataType ...
dataType:"json",
like this
$.ajax({
type: 'GET',
dataType:"json",
url: '/search.php',
data: 'search=' + encodeURIComponent(search),
success: function (datas) {
But with everything works.
find on [Jquery autocomplete _renderItem is not working][1]
Related
I have below code which is reloading new records if inserted.
On page load it works fine But after reloading div when get new data, it is keep reloading again and again and also not including a file which is included in order_new_orders.php.
I want only reload the div if new record inserted and then keep close.
order_new_orders.php
**EXAMPLE:**
$sqla = "select order_id from orders where status = 0
and store_id = '".$_SESSION['ses_user_idx']."'";
$sqlb = $dba2->query($sqla);
while ($sqlc = $sqlb->fetch_assoc()){
include ('inc/afile.php');
echo $sqlc['name'];
}
Code:
var currentNewOrders = "";
function auto_loadNewOrders(){
$.ajax({
type: 'POST',
url: 'order_new_orders.php',
success: function(data){
if(currentNewOrders !== data) {
$("#newOrderRefresh").html(data);
currentNewOrders = data;
}
}
});
}
auto_loadNewOrders();
setInterval(auto_loadNewOrders,1000);
PHP
order_new_orders.php
<?php
//Dummy Data
$datas = array(
array('id' => 1, 'name' => 'Dummy Name1', 'age' => 25),
array('id' => 2, 'name' => 'Dummy Name2', 'age' => 28),
array('id' => 3, 'name' => 'Dummy Name2', 'age' => 28),
);
if (isset($_GET['checkNew']) && isset($_GET['lastDataID'])) {
if (count($datas) > $_GET['lastDataID']) {
echo 1;
} else {
echo 'No new Data';
}
exit;
}
//Data Output structure
$htm = "<table border='1'>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
";
foreach ($datas as $row) {
$htm.="<tr class='data-row' data-row-id='$row[id]'>
<td>$row[name]</td>
<td>$row[age]</td>
</tr>";
}
$htm.="</table>";
echo $htm;
exit;
HTML & jQuery
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="newOrderRefresh"></div>
<script>
$(document).ready(function() {
auto_loadNewOrders();
setInterval(checkForNew, 1000);
});
function auto_loadNewOrders() {
$.ajax({
type: 'POST',
url: 'order_new_orders.php',
success: function(data) {
$("#newOrderRefresh").html(data);
}
});
}
function checkForNew() {
var lastData = $('.data-row').last().attr('data-row-id');
$.ajax({
type: 'POST',
url: 'order_new_orders.php?checkNew&lastDataID=' + lastData,
success: function(data) {
if (data == 1) {
auto_loadNewOrders();
}
}
});
}
</script>
I've seen and tried a few answers that are similar to this question, but it still displays the same error.
The console is also giving the error: Uncaught TypeError: Cannot read property 'length' of undefined at Function.each (jquery-1.10.2.js:631)
My view:
<form action="https://dev.vmc.w3.uvm.edu/xana/sensors/deployments" class="basicForm aboutForm form-horizontal" id="deploymentForm" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div class="form-group">
<label for="fldFileName" class="col-sm-4 control-label">Image</label>
<div class="col-sm-8">
<input type="file" name="fldFileName" value="" class="form-control" id="fldFileName" />
</div>
</div>
<button type="button" class="btn btn-primary" id="newSensorSubmit">Save</button>
</form>
javascript to submit form:
$(document).on("click", "#newSensorSubmit", function(event){
var posturl="<?php echo site_url("sensors/add_deployment");?>";
var formData = new FormData();
var fldFileName = $('#fldFileName').val();
formData.append('fldFileName', fldFileName);
jQuery.ajax({
url: posturl,
data: formData,
cache: false,
mimeType: "multipart/form-data",
dataType: 'json',
contentType: false,
processData: false,
type: 'POST',
success: function(data){
if(data.status === 'success') {
//handle success
}
else {
//handle fail
}
},
error: (error) => {
$('#articleErrorText').html(JSON.stringify(error));
}
});
});
controller:
public function add_deployment(){
$this->load->helper(array('form', 'url'));
$this->load->library('upload');
$config = array(
'upload_path' => site_url("attachments/project/999/metstations"),
'allowed_types' => "gif|jpg|png|jpeg",
'overwrite' => TRUE,
'max_size' => "16000000"
);
$this->load->library('upload', $config);
if($this->upload->do_upload('fldFileName'))
{
$data['image_metadata'] = array('image_metadata' => $this->upload->data());
}
else
{
$error = $this->upload->display_errors();
$data['errors']='<p class="error-message">'.$error.'</p>';
$data['status']='failure';
}
}
Try This.
To get all your form inputs, including the type="file" you need to use FormData object.
To append param just use append() method:
formData.append("param", "value");
And in the php-side I catch it:
echo $file_name = ($_FILES['file']['name']);
View Code:-
<body>
<p id="msg"></p>
<input type="file" id="file" name="file" />
<button id="upload">Upload</button>
</body>
jQuery / Ajax Code:-
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e){
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'ControllerName/upload_file', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
</script>
Controller Code:-
class ControllerName extends CI_Controller {
function __construct() {
parent::__construct();
}
function upload_file() {
//upload file
$config['upload_path'] = 'uploads/';
$config['allowed_types'] = '*';
$config['max_filename'] = '255';
$config['encrypt_name'] = TRUE; // remove it for actual file name.
$config['max_size'] = '1024'; //1 MB
if (isset($_FILES['file']['name'])) {
if (0 < $_FILES['file']['error']) {
echo 'Error during file upload' . $_FILES['file']['error'];
} else {
if (file_exists('uploads/' . $_FILES['file']['name'])) {
echo 'File already exists : uploads/' . $_FILES['file']['name'];
} else {
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
echo $this->upload->display_errors();
} else {
echo 'File successfully uploaded : uploads/' . $_FILES['file']['name'];
}
}
}
} else {
echo 'Please choose a file';
}
}
}
Note:- For more reference regarding this check this
https://developer.mozilla.org/en-US/docs/Web/API/FormData/append
php isn't passing $id to query
I am trying to execute an inline edit script using data pulled from a mysqli query that pulls specific data based on url ?id= using if isset $_GET $id, the page is getting and echoing the id correctly, however, the query isn't getting the $id variable.
I have tested the query by replacing the $id var with a number relative to the data and it works without issue.
I have tried adding the $id into the $_SESSION and retrieving it from there but still no luck.
The main page is an index.php (which has url of index.php?id=2019018) which fetches data and displays it as a datagrid with inline edit capability through js (fetch_data.php).
you may notice tests etc that have been commented out
both scripts are below, any help appreciated
index.php
<html>
<head>
<title>Inline Table Insert Update Delete in PHP using jsGrid</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" />
<link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.js"></script>
<style>
.hide
{
display:none;
}
</style>
</head>
<body>
<div class="container">
<br />
<div class="table-responsive">
<h3 align="center">Inline Table Insert Update Delete in PHP using jsGrid</h3><br />
<div id="grid_table"></div>
</div>
</div>
<?php
if (isset($_GET['id'])) {
$id = $_GET['id'];
}
//session_start();
//$_SESSION['id_sess'] = $id;
?>
<?php
// echo $_SESSION['id_sess'];
echo $id;
?>
</body>
</html>
<script>
$('#grid_table').jsGrid({
width: "100%",
height: "600px",
filtering: true,
inserting: true,
editing: true,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
pageButtonCount: 5,
deleteConfirm: "Do you really want to delete data?",
controller: {
loadData: function (filter) {
return $.ajax({
type: "GET",
url: "fetch_data.php",
data: filter
});
},
insertItem: function (item) {
return $.ajax({
type: "POST",
url: "fetch_data.php",
data: item
});
},
updateItem: function (item) {
return $.ajax({
type: "PUT",
url: "fetch_data.php",
data: item
});
},
deleteItem: function (item) {
return $.ajax({
type: "DELETE",
url: "fetch_data.php",
data: item
});
},
},
fields: [
{
name: "job_id",
type: "text",
//css: 'hide'
},
{
name: "part_id",
type: "text",
//css: 'hide'
},
{
name: "part_name",
type: "text",
width: 150,
validate: "required"
},
{
name: "part_cost",
type: "text",
width: 150,
validate: "required"
},
{
name: "part_rrp",
type: "text",
width: 50,
validate: "required"
},
{
name: "quantity",
type: "text",
width: 50,
validate: "required"
},
{
type: "control"
}
]
});
</script>
fetch_data.php
<?php
//$id = $_GET['id'];
//$id = $_SESSION['id_sess'];
$connect = new PDO("mysql:host=localhost;dbname=****", "****", "****");
$method = $_SERVER['REQUEST_METHOD'];
/* if(!isset($_GET['id'])) // if it doesnt get id?
{
echo "IT WORKS";
//$id = $_GET['id'];
}else{
$id = $_GET['id'];
} */
if ($method == 'GET') {
$data = array(
':part_name' => "%" . $_GET['part_name'] . "%",
':part_cost' => "%" . $_GET['part_cost'] . "%",
':part_rrp' => "%" . $_GET['part_rrp'] . "%",
':quantity' => "%" . $_GET['quantity'] . "%"
);
//$query = "SELECT job_id, part_id, part_name, part_cost, part_rrp, quantity FROM jobs INNER JOIN job_parts USING (job_id) INNER JOIN parts USING (part_id) Where job_id = 2019018";
$query = "SELECT job_id, part_id, part_name, part_cost, part_rrp, quantity FROM jobs INNER JOIN job_parts USING (job_id) INNER JOIN parts USING (part_id) Where job_id = '$job_id'";
$statement = $connect->prepare($query);
$statement->execute($data);
$result = $statement->fetchAll();
foreach ($result as $row) {
$output[] = array(
'part_id' => $row['part_id'],
'part_name' => $row['part_name'],
'part_cost' => $row['part_cost'],
'part_rrp' => $row['part_rrp'],
'quantity' => $row['quantity']
);
}
header("Content-Type: application/json");
echo json_encode($output);
}
if ($method == "POST") {
$data = array(
':part_name' => $_POST['part_name'],
':part_cost' => $_POST["part_cost"],
':part_rrp' => $_POST["part_rrp"]
);
$query = "INSERT INTO parts (part_name, part_cost, part_rrp) VALUES (:part_name, :part_cost, :part_rrp)";
$statement = $connect->prepare($query);
$statement->execute($data);
}
if ($method == 'PUT') {
parse_str(file_get_contents("php://input"), $_PUT);
$data = array(
':part_id' => $_PUT['part_id'],
':part_name' => $_PUT['part_name'],
':part_cost' => $_PUT['part_cost'],
':part_rrp' => $_PUT['part_rrp']
);
$query = "
UPDATE parts
SET part_name = :part_name,
part_cost = :part_cost,
part_rrp = :part_rrp
WHERE part_id = :part_id
";
$statement = $connect->prepare($query);
$statement->execute($data);
}
if ($method == "DELETE") {
parse_str(file_get_contents("php://input"), $_DELETE);
$query = "DELETE FROM parts WHERE part_id = '" . $_DELETE["part_id"] . "'";
$statement = $connect->prepare($query);
$statement->execute();
}
?>
You need to pass the id to your AJAX request too since it is considered a totally separate request.
e.g.
insertItem: function (item) {
return $.ajax({
type: "POST",
url: "fetch_data.php?id="<?php echo $id; ?>,
data: item
});
},
The jQuery autocomplete function brings the item from the database based on my typing word but result shows as just horizontal line of list. Attached image is showing how the result looks like.
HTML:
<form class="navbar-seach pull-center">
<div>
<input type="text" placeholder="Search Productstyle="width:550px; height:40px;padding-left: 10px;margin-top: 20px;" id="searchBox" onkeyup="if (event.keyCode === 13) {searchResults(this.value); this.value = '';}">
</div>
</form>
PHP:
include 'searchbox.php';
$switch_id = filter_input(INPUT_POST, 'switch_id', FILTER_SANITIZE_SPECIAL_CHARS);
if (isset($_POST['name_startsWith']))
$searchWordResults = $_POST['name_startsWith'];
else
$searchWordResults = null;
switch($switch_id){
case 1:
$userObj = new searchBox();
echo $userObj->autoComplete($searchWordResults);
break;
}
jQuery:
$("#searchBox").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "class/searchbox_switch.php",
dataType: "json",
data: { name_startsWith: request.term, switch_id: 1 },
success: function(data) {
response($.map(data, function(item){
return {
label: item.label,
value: item.value
};
}));
},
error: function(response) {
console.log(response.responseText);
}
});
},
autoFocus: true,
minLength: 1,
select: function( event, ui ) {
searchResults(ui.item.label);
}
});
PHP (searchbox.php):
include '../dbConnect.php';
class searchBox {
public function autoComplete($name_startsWith) {
$letterSearch = $name_startsWith . "%";
$connectObj = new db_connect();
$dbh = $connectObj->connect();
$stmt = $dbh->prepare("SELECT product_name FROM products WHERE product_name LIKE :start");
$stnd = array();
$stmt->bindParam(':start', $letterSearch, PDO::PARAM_STR);
$stmt->execute();
$stnd = $stmt->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($stnd);
return $json;
}
}
OK got it. You are passing wrong key in your result. Your result data key is "product_name" And You are trying to access "label ". Try This solution:
success: function( data ) {
response( $.map( data, function(item) {
return {
label: item.product_name,
}
}));
},
I have a form, whose values I am trying to post after serializing to a controller via ajax. Below is the form:
Form
<form method="post" id="frm_reg_student" class="stop-propagation registration-form">
<input type="hidden" name="register[user_type]" value="2">
<input type="hidden" name="register[status_id]" value="1">
<div class="stud_register_error"></div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label for="input" class="control-label font-12 font-blue">First Name <span>*</span></label>
<input type="text" class="form-control" required="required" placeholder="Your First Name" name="register[first_name]">
</div>
</div>
<div class="col-xs-6 col-sm-6 col-md-6">
<div class="form-group">
<label for="input" class="control-label font-12 font-blue">Last Name <span class="req">*</span></label>
<input type="text" class="form-control" required="required" placeholder="Your Last Name" name="register[last_name]">
</div>
</div>
</div>
</form>
js
$(".js-btn_reg_student").click(function(e){
e.preventDefault();
var serialData= $( "#frm_reg_student" ).serialize();
alert(serialData);
$.ajax ({
type: "POST",
url: '<?=base_url()?>index.php/register/signup/',
data: serialData,
success: function(result) {
alert(result);
output = JSON.parse(result);
if(result) {
if( 'success' == output.type ) {
location.href = output.location;
} else {
$('.stud_register_error').html(output.message);
}
}
}
});
});
Controller
public function signup(){
if($_SERVER["REQUEST_METHOD"]=="POST"){
print_r($_POST);
}
}
Here, $_POST comes out to be empty, it never goes inside the loop. If you see in the JS, I have included an alert with the serialized data, which even shows me the proper serialized data. I believe it is something wrong with the way I am posting it.
Any help!
Try on ajax
$(".js-btn_reg_student").click(function(e){
var formdata = $( "#frm_reg_student" ).serialize();
$.ajax({
type: "post",
url: "<?php echo base_url('register/signup');?>",
data: formdata,
dataType: 'json',
success: function(json) {
if (json[success]) {
alert(json['post']);
} else {
}
}
});
e.preventDefault();
});
And controller
public function signup() {
$data = array(
'success' => false,
'post' => ''
);
if ($this->input->server("REQUEST_METHOD") == 'POST')
{
$data['success'] = true;
$data['post'] = $_POST;
}
echo json_encode($data);
}
Try
$('#js-btn_reg_student').click(function () {
$.ajax ({
type: 'post',
url: '<?php echo base_url(); ?>index.php/test/signup/',
data: $('#frm_reg_student').serialize(),
dataType: 'json',
success: function(result) {
if(result.status == 'success')
{
alert(result.name);
}
else
{
alert(result.status);
}
}
});
});
And in Controller
public function signup ()
{
if($this->input->post())
{
$data = array('status' => 'success');
$data['name'] = $this->input->post('register[first_name]');
}
else
{
$data = array('status' => 'failed');
}
echo json_encode($data);
}
Try it and let me know if it works or not :)
Try to use below code.
$(".js-btn_reg_student").click(function(e){
e.preventDefault();
var serialData= $( "#frm_reg_student" ).serialize();
alert(serialData);
$.ajax ({
url: '<?=base_url()?>index.php/register/signup/',
method : 'POST',
data: serialData,
success: function(result) {
if(result) {
if( 'success' == output.type ) {
location.href = output.location;
} else {
$('.stud_register_error').html(output.message);
}
}
}
});
});
I think all the answers were correct in their own way. I figured out that it might be possible that it is not getting the DOM upon submit so I simply put it in document.ready and it worked!
Thanks