Jquery mobile autocomplete with php - php

I'm trying to get the Jquery mobile autocomplete demo on the jquery mobile website (http://view.jquerymobile.com/1.3.2/dist/demos/widgets/autocomplete/autocomplete-remote.html) work with a php file, if i tested in firebug, I have the callback response working in this format: [{"label":"278","value":"ANGELIC HOLISTIC HEALING"}]
But I don't know why is not showing any results on my html, here's the code:
<script type="text/javascript">
$( document ).on( "pageinit", "#searchPage", function() {
$( "#autocomplete" ).on( "listviewbeforefilter", function ( e, data ) {
var $ul = $( this ),
$input = $( data.input ),
value = $input.val(),
html = "";
$ul.html( "" );
if ( value && value.length > 2 ) {
$ul.html( "<li><div class='ui-loader'><span class='ui-icon ui-icon-loading'></span></div></li>" );
$ul.listview( "refresh" );
$.ajax({
url: "services/search2.php",
dataType: "jsonp",
crossDomain: true,
data: {
term: $input.val()
},
})
.then( function ( response ) {
$.each( response, function ( i, val ) {
html += "<li>" + val.value + "</li>";
});
$ul.html( html );
$ul.listview( "refresh" );
$ul.trigger( "updatelayout");
});
}
});
});
the php:
(database connection)
$q = strtolower($_GET["term"]);
$return = array();
$query = mysql_query("select * from directory2 where business like '%$q%'");
while($row = mysql_fetch_assoc($query))
{
array_push($return, array(
'label' => $row['ID'],
'value' => html_entity_decode($row['business'], ENT_QUOTES, 'UTF-8') )
);
}
echo(json_encode($return));
the html
<div data-role="content">
<h3>Cities worldwide</h3>
After you enter at least three characters the autocomplete function will show all possible matches.
<<ul id="autocomplete" data-role="listview" data-inset="true" data-filter="true" data-filter-placeholder="Find a business..." data-filter-theme="d"></ul>
</div>
Please any help will be soo much appreciated, I've been searching for this a lot everywhere and no luck!

Related

How to add a member and task allocated if not found in dynamically populated dropdownlst

I have reviewed suggested solutions but did not find any matching my issue.
We have a SELECT list that is dynamically populated from the database.
Each time a staff wishes to create a task and allocate time to complete the task, s/he selects the member who would handle that task and then allocates time to complete the task. This works fine.
//JS
function populateMember() {
$.ajax({
type: 'GET', // define the type of HTTP verb we want to use (POST for our form)
url: 'php/getMember.php?mode=edited&rowId=' + $.urlParam('id'), // the url where we want to POST
dataType: 'html', // what type of data do we expect back from the server
encode: true
})
.done(function (data) {
var returnedData = JSON.parse(data);
var newRows = (returnedData.length - 3);
if (returnedData.length > 3){
var x = 0;
for (x=0; x < newRows; x++){
$( "#newMember" ).trigger( "click" );
}
}
var i=0;
for (i in returnedData){
$('#member' + i).val(returnedData[i][0]);
$('#task_time_alocatted' + i).val(returnedData[i][1]);
}
})
.error(function () {});
}
//PHP
<?php
//Connect to server
///Connection info goes here
}
//These are parameters from the POST request
$mode = $_GET[ 'mode' ];
$rowId = (int) $_GET[ 'rowId' ];
$sql = "SELECT member, task_time_allocated FROM TaskAllocations WHERE parent_task_id = $rowId;";
$stmt = sqlsrv_query( $conn, $sql );
if ( $stmt === false ) {
$theErrors = sqlsrv_errors();
array_push($messages, 0, $sql, $theErrors);
echo json_encode($messages);
die();
} else {
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_BOTH) ) {
array_push($messages, [$row['member'], $row['task_time_allocated']]);
}
echo json_encode($messages);
}
?>
However, if the member that a staff is trying to select from the SELECT list is not on that list, we would like two text boxes, one for the member and one for task to be allocated to that member.
How do we handle this?
We have created this on the HTML form:
//JS
<script type="text/javascript">
$(function () {
$("#btnstaff").click(function () {
if ($(this).val().toLowerCase() == "amend") {
$.each($('.dvstaff'), function(i, item){
$(this).show();
});
$(this).val("Cancel");
} else {
$.each($('.dvstaff'), function(i, item){
$(this).hide();
});
$(this).val("Amend");
}
});
});
</script>
//HTML
<input id="btnstaff" type="button" value="Amend" name="btnstaff" />
<tr>
<td></td>
<td><div class="dvstaff" style="display: none"><input id="amendmember" class="shortText" style="width:242px;" name="amendmember"></div></td>
<td>
<div class="dvstaff" style="display: none"><input id="amendtime" class="shortText" placeholder="0" name="amendtime"> %</div></td>
</tr>
You click Amend and it creates two blank textboxes, one for new member and the other for task_time_allocated.
We would prefer to handle this Amend bit on the JS that invokes the getMember method since the HTML is generated from the JS.
Is this possible?

How to use foreach loop in php for retrieve data from data base to jquery-ui accordion

How to use foreach loop in php for retrieve data from data base to jQuery-ui accordion. I want to user jQuery accordion for fetch data from database. I tried many ways but I can't to do that because of lack of my knowledge. I used jQuery-ui for this one.
This is the code I wrote for this
<body>
<div class="container" style="width:900px;">
<div id="accordion"></div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$.ajax({
url: "fetch.php",
method:"POST",
dataType: "json",
success: function(data)
{
console.log(data);
$( function() {
$( "#accordion" ).accordion();
//console.log(data);
var device_ID;
var sensor_ID;
} );
}
});
});
</script>
This is the PHP part:
<?php
//fetch.php
$connect = mysqli_connect("localhost", "root", "", "kapra_iot");
$query = "
SELECT * FROM `view_sensor`
";
$result = mysqli_query($connect, $query);
//$output = array();
while($row = mysqli_fetch_array($result))
{
$sub_data["device_ID"] = $row["device_ID"];
$sub_data["device_Name"] = $row["device_Name"];
$sub_data["sensor_ID"] = $row["sensor_ID"];
$sub_data["sensor_Name"] = $row["sensor_Name"];
$sub_data["lower_Value"] = $row["lower_Value"];
$sub_data["mid_Value"] = $row["mid_Value"];
$sub_data["upper_Value"] = $row["upper_Value"];
$data[] = $sub_data;
}
foreach($data as $key => &$value)
{
$output[$value["device_ID"]] = &$value;
}
foreach($data as $key => &$value)
{
if($value["sensor_ID"] && isset($output[$value["sensor_ID"]]))
{
$output[$value["sensor_ID"]]["nodes"][] = &$value;
}
}
foreach($data as $key => &$value)
{
if($value["sensor_ID"] && isset($output[$value["sensor_ID"]]))
{
unset($data[$key]);
}
}
echo json_encode($data);
//echo '<pre>';
//print_r($data);
//echo '</pre>';
?>
I'd point you to the docs just as Kumar Praveen did. The Accordion will display the different sections titles using the h3 tag and the inner section of each one inside div tags.
Loop trough the result and add it to your accordion div following the syntax described before.
$(document).ready(function () {
$.ajax({
url: "fetch.php",
method: "POST",
dataType: "json",
success: function (data) {
for (device in data)
{
$("#accordion").append("<h3>"+device['device_id']+" " + device['device_Name'] + "</h3>");
$("#accordion").append("<div><p> Insert here all the relevant data of your device including all the other variables</p></div>");
}
$("#accordion").accordion();
}
});
});
Using the Widget Factory, you can extend accordion to a remote source.
$(function() {
var testData = [{
"device_ID": 1001,
"device_Name": "Device 1",
"sensor_ID": 597,
"sensor_Name": "Sensor 1",
"lower_Value": 0,
"mid_Value": 50,
"upper_Value": 100
}, {
"device_ID": 1002,
"device_Name": "Device 2",
"sensor_ID": 598,
"sensor_Name": "Sensor 1",
"lower_Value": 0,
"mid_Value": 500,
"upper_Value": 1000
}, {
"device_ID": 1003,
"device_Name": "Device 3",
"sensor_ID": 599,
"sensor_Name": "Sensor 1",
"lower_Value": 0,
"mid_Value": 0.05,
"upper_Value": 0.1
}];
$.widget("custom.buildList", $.ui.accordion, {
options: $.extend(this.options, {
source: "",
data: []
}),
_create: function() {
console.log("Init");
this.element.addClass("custom-list");
var action;
if (this.options.source == "") {
action = "html";
} else if (typeof this.options.source == "string") {
action = "ajax";
} else {
action = "array";
}
console.log("Action", action);
if (action !== "html") {
if (action === "ajax") {
this.options.data = this._getData(this.options.source);
}
this._makeList(this.element);
}
console.log("Return to _create");
return this._super();
},
_getData: function(url) {
console.log("Getting Data", url);
$.getJSON(url, function(resp) {
this.options.data = resp;
});
},
_makeList: function(tObj) {
console.log("Making List");
var myData;
if (this.options.data.length == 0) {
myData = this.options.source;
} else {
myData = this.options.data;
}
console.log("List Data", myData);
$.each(myData, function(i, d) {
var hd = $("<h3>").html(d.device_Name);
var bd = $("<div>");
var ls = $("<ul>").appendTo(bd);
$.each(d, function(k, v) {
$("<li>").html(k + ": " + v).appendTo(ls);
});
tObj.append(hd, bd);
});
}
});
$("#accordion").buildList({
source: testData
});
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="container" style="width:900px;">
<div id="accordion"></div>
</div>
This extension allows a URL or Array to be passed in as a Source option. So if you wanted to use it to get data from a PHP Script, you could do:
$("#accordion").buildList({
source: "fetch.php"
});
The extended widget will collect the data from the URL or Array and build the needed HTML before calling on the rest of the widget. I had to test with an array. You will also need to modify _makeList() function to meet you various needs.
It is also built to default back to HTML if you so choose. Also you have all the same options as you would with a standard Accordion widget.

Trying to get PHP responce on ajax

Here I am trying to update the MSQL table using jQuery, both PHP code and jQuery script is written on the same page, the code working fine to update my tables but the response msg is not getting by the AJAX so it always shows me the default message "Some problem occurred, please try again.".
HTML
<!-- HTML code to display msg -->
<p class="statusMsg_post"></p>
jQuery
<script>
$(document).ready(function(){
$('#btn_publish').click( function() {
var obj_post_postID="<?php echo $post_id; ?>";
var publish_post="publish";
$.ajax({
type:'POST',
// url:'post_view.php',
data:{
"post_status_update": publish_post,
"obj_post_status": obj_post_postID,
},
success:function(res) {
if (res=='ok') {
$('.statusMsg_post').html('<span style="color:green;">Post has been '+publish_post+' sucessfully</span>');
}
else {
$('.statusMsg_post').html('<span style="color:red;">Some problem occurred, please try again.</span>');
}
}
});
});
});
</script>
PHP
// my PHP code to update my table
<?php
// require_once('../../inc/db-connect.php');
if (isset($_POST['post_status_update'])) {
$temp_publish_post = $_POST['post_status_update'];
echo $bj_post_postID = $_POST['obj_post_status'];
$obj_post_status_query = "UPDATE `objection_report` SET `obj_status` = '$temp_publish_post' WHERE `objection_report`.`obj_post_id` = $bj_post_postID;";
$obj_post_status_query .= "UPDATE `post` SET `status` = '$temp_publish_post' WHERE `post`.`post_id` = $bj_post_postID ;";
if (mysqli_multi_query($con, $obj_post_status_query)) {
echo "ok";
die;
}
}
?>
all the above codes are on the same page
The script is returning the HTML and JS on the ajax call. If you put checks around the HTML it will not:
<?php if ( ! isset( $_POST['post_status_update'] ) ): ?>
<p class="statusMsg_post"></p>
<script>
$( document ).ready( function () {
$( '#btn_publish' ).click( function () {
var obj_post_postID = "<?php echo $post_id; ?>";
var publish_post = "publish";
$.ajax( {
type: 'POST',
// url:'post_view.php',
data: {
"post_status_update": publish_post,
"obj_post_status": obj_post_postID,
},
success: function ( res ) {
if ( res === 'ok' ) {
$( '.statusMsg_post' ).html( '<span style="color:green;">Post has been ' + publish_post + ' sucessfully</span>' );
} else {
$( '.statusMsg_post' ).html( '<span style="color:red;">Some problem occurred, please try again.</span>' );
}
}
} );
} );
} );
</script>
<?php endif; ?>

jQuery autocomplete text seperated with comma not working in CodeIgniter

code: search_json.php
<?php
function get_data()
{
$ci =& get_instance();
$ci->db->select('*');
$ci->db->from('top_menu');
$ci->db->order_by('menu_name');
$query = $ci->db->get();
$result = $query->result_array();
foreach($result as $row)
{
$menu[] = array(
'id' => $row["id"],
'label' => $row["menu_name"]
);
}
return json_encode($menu);
}
echo "<pre>";
print_r(get_data());
echo "</pre>";
?>
index.php
<script>
$(function(){
function split( val )
{
return val.split( /,\s*/ );
}
function extractLast( term )
{
return split( term ).pop();
}
$( "#tags" )
.on( "keydown", function( event ) {
if ( event.keyCode === $.ui.keyCode.TAB &&
$( this ).autocomplete( "instance" ).menu.active ) {
event.preventDefault();
}
})
.autocomplete({
source: function( request, response ) {
$.getJSON( "<?php echo base_url(); ?>user/search", {
term: extractLast( request.term )
}, response );
},
search: function() {
var term = extractLast( this.value );
if ( term.length < 1 ) {
return false;
}
},
focus: function() {
return false;
},
select: function( event, ui ) {
var terms = split( this.value );
terms.pop();
terms.push( ui.item.value );
terms.push( "" );
this.value = terms.join( ", " );
return false;
}
});
});
</script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
<label for="tags">Tags</label>
<input type="text" class="form-control1" id="tags" name="tags"/>
</div>
controller: user.php
public function search()
{
$this->load->view('user/search_json');
}
In this code, I have created a json format file (i.e. search_json.php) and I want to implement it inside index.php. search_json.php file works perfectly, data is in proper format, but when I write something inside the tags input field it shows nothing. So, how can I fix this issue?
Thank you!
First of all, <?php echo base_url(); ?>user/search can, and should be used like <?php echo base_url('user/search'); ?>. (I mostly do <?= base_url().'user/search'; ?> though :) Funny to see I'm not the only one using it 'wrong'...
If I have ajax controllers I tend to set the output like this:
$this
->output
->set_content_type('application/json')
->set_output(json_encode($return)); // Where $return is an array
So in your case I guess you should load the json php file as a partial and set the output to the partial contents:
public function search() {
$return = $this->load->view('user/search_json', '', true);
$this
->output
->set_content_type('application/json')
->set_output($return);
}

JQuery GET works only first time, second time I just get server response... why?

I have some JQuery where when you click on a "Add to Basket" button (it's really a link), the first time everything works as expected however click the button a second time, although the product is added to basket (database row has increased quantity), the response sent by server is outputted rather than "captured" by JQuery in the SUCCESS function.
I don't understand why this would happen, any thoughts on this?
JQuery
$(function() {
$( '.button' ).click(function( e ) {
e.preventDefault();
var url = $( this ).children( 'a' ).attr( 'href' );
var elem = $( this );
var parent = $( this ).parent().parent();
var html = parent.html(); alert( html );
$.ajax({
type: 'get',
url: url,
data: '',
cache: false,
dataType: 'text',
beforeSend: function( rs ) {
parent.html( '<div class="basket-item item-border" style="width:896px;text-align:center;"><p class="para"><img src="/media/images/spinner.gif" />Please wait...</p></div>' );
},
success: function( rs ) {
parent.html( html );
if( rs = 'YES' ) {
alert( 'Okay' );
} else {
alert( 'Something went wrong' );
}
},
error: function( rs, err ) {
if( rs.status == 0 ) {
alert( '--- Offline' );
} else if( rs.status == 404 ) {
alert( '404 Not Found' );
} else if( rs.status == 501 ) {
alert( '501 Internal Error' );
} else if( err == 'timeout' ) {
alert( '--- Timeout' );
} else {
alert( '--- Unknown' );
}
}
});
});
});
And here is a section of the HTML the JQuery works on
<div>
<div class="basket-item item-border" style="width:512px;text-align:left;">
<p class="para">
<img
width="48"
height="48"
alt="Sample Soap Pack (£3.99)"
src="http://www.mj.local/media/images/products/generic/0929005236213037.jpg" />
Sample Soap Pack</p>
</div>
<div class="basket-item item-border"><p>3.99</p></div>
<div class="basket-item item-border" style="width:256px;text-align:center;">
<p class="button"><a href="http://www.mj.local/shop/add/sample-soap-pack/">
<span class="add">Add to Basket</span>
</a></p>
</div>
</div>
The contents of the parent DIV are replaced with a "Please wait.." message and then restored, as expected so would this alter any way JQuery works? I have another JQuery working okay when swapping HTML so why now with this?
Thanks.
it's because on success you are replacing the html of the parent, your .button will be replaced, and the new .button won't have the click event binded anymore.
You could fix it by using live jQuery <1.7:
$(function() {
$('.button').live('click', function() {
//your function here
});
});
or on for jquery >1.7:
$(function() {
$(document).on("click", ".button", function(){ });
});
You are replacing your .button element inside the callback function for the AJAX request that clicking on the .button element makes and when you remove the .button element the click event handler for that element is also removed. I would use event delegation so the event handler will affect all the elements currently in the DOM and ones added later (for example by an AJAX call):
Just change:
$( '.button' ).click(function( e ) {
To:
$(document).delegate('.button', 'click', function( e ) {
Here are docs for .delegate(): http://api.jquery.com/delegate

Categories