I am having problems with a jquery. The code below is not triggered when the php page loads. I attempt to check the value of a field in a database table and do a redirect if the returned value is 0. I have been struggeling with this for hours and I have really searched around to find the answer. Any help is appreciated.
<script type="text/javascript">
$jQn(document).ready(function(){
var do_checking;
var status = 1;
var ui = "";
if(status == 1){
$jQn.blockUI.defaults.overlayCSS.opacity=.3;
$jQn.blockUI({
message: ui,
css: {
border: '10px solid #888',
backgroundColor: '#000',
'-webkit-border-radius': '10px',
'-moz-border-radius': '10px',
color: '#fff',
width: '50%',
left: '25%',
cursor: 'wait',
'-ms-filter': 'progid:DXImageTransform.Microsoft.Alpha(Opacity=10)',
'filter': 'progid:DXImageTransform.Microsoft.Alpha(Opacity=10)',
'-moz-opacity':.10,
opacity:.10,
padding:'15px'
}
});
do_checking = setInterval(check_search_status, 1000);
} else {
document.location = 'https://mysite.com/result.php';
}
});
function check_search_status(){
$jQn.ajax({
type: 'POST',
url: 'https://mysite.com/checksearchstatus.php',
data: {
id: '$owner'
},
dataType: 'json',
success: function(response){
if(response.status == 0){
clearInterval(do_checking);
document.location = 'https://mysite.com/result.php';
}
}
});
}
</script>
Here is the code of the separated php file
$con = mysql_connect($db_host,$db_username,$db_password);
if (!$con)
{
die('Feil ved tilkobling av: ' . mysql_error());
}
mysql_select_db($db_name, $con);
$response = array('status' => '');
$user_id = $_POST['id'];
// Build SQL
$first_search_sql = "SELECT `firstsearch` FROM `class_users` WHERE id = '".$user_id."'";
$first_search_result = $db->query($first_search_sql);
// Fetch result
$first_search_row = $first_search_result->fetch();
// Free result
$first_search_result->freeResult();
$response['status'] = $first_search_row['firstsearch'] ;
echo json_encode($response);
Related
I'm trying to incorporate the jquery sortable functionality into my website and saving the positions in the database is giving me all sorts of headaches... I've been fighting this for 3 days now, and I cannot seem to get this work properly.
As it stands, it is saving positions to the database, but not in the order or positions, that you'd expect. Meaning, if I move the item in position 0 to position 1, it saves the positions in a different order in the db. check out a live version here.
Here is my code...
index.php file:
<div id="container">
<?php
require_once 'conn.php';
$q = ' SELECT * FROM items WHERE groupId = 3 ORDER BY position ';
$result = mysqli_query($db, $q);
if ($result->num_rows > 0) {
while($items = $result->fetch_assoc()) {
?>
<div id='sort_<?php echo$items['position'] ?>' class='items'>
<span>☰</span> <?php echo$items['description'] ?>
</div>
<?php
}
}
?>
</div>
js.js file:
$("#container").sortable({
opacity: 0.325,
tolerance: 'pointer',
cursor: 'move',
update: function(event, ui) {
var itId = 3;
var post = $(this).sortable('serialize');
$.ajax({
type: 'POST',
url: 'save.php',
data: {positions: post, id: itId },
dataType: 'json',
cache: false,
success: function(output) {
// console.log('success -> ' + output);
},
error: function(output) {
// console.log('fail -> ' + output);
}
});
}
});
$("#container").disableSelection();
save.php file:
require_once('conn.php');
$itId = $_POST['id'];
$orderArr = $_POST['positions'];
$arr = array();
$orderArr = parse_str($orderArr, $arr);
$combine = implode(', ', $arr['sort']);
$getIds = "SELECT id FROM items WHERE groupId = '$itId' ";
$result = mysqli_query($db, $getIds);
foreach($arr['sort'] as $a) {
$row = $result->fetch_assoc();
$sql = " UPDATE items
SET position = '$a'
WHERE id = '{$row['id']}' ";
mysqli_query($db, $sql);
}
echo json_encode( ($arr['sort']) );
Can anyone please point to where I am going wrong on this?
Thank you in advance.
Serge
In case someone lands on here, here is what worked in my case...
NOTE: I did not create prepared statements in the index.php select function. But you probably should.
index.php file:
<div id="container">
<?php
require_once 'conn.php';
$q = ' SELECT * FROM items WHERE groupId = 3 ORDER BY position ';
$result = mysqli_query($db, $q);
if ($result->num_rows > 0) {
while( $items = $result->fetch_assoc() ){
?>
<div id='sort_<?php echo $items['id'] ?>' class='items'>
<span>☰</span> <?php echo $items['description'] ?>
</div>
<?php
}
}
?>
</div>
jquery sortable file:
var ul_sortable = $('#container');
ul_sortable.sortable({
opacity: 0.325,
tolerance: 'pointer',
cursor: 'move',
update: function(event, ui) {
var post = ul_sortable.sortable('serialize');
$.ajax({
type: 'POST',
url: 'save.php',
data: post,
dataType: 'json',
cache: false,
success: function(output) {
console.log('success -> ' + output);
},
error: function(output) {
console.log('fail -> ' + output);
}
});
}
});
ul_sortable.disableSelection();
update php file:
$isNum = false;
foreach( $_POST['sort'] as $key => $value ) {
if ( ctype_digit($value) ) {
$isNum = true;
} else {
$isNum = false;
}
}
if( isset($_POST) && $isNum == true ){
require_once('conn.php');
$orderArr = $_POST['sort'];
$order = 0;
if ($stmt = $db->prepare(" UPDATE items SET position = ? WHERE id=? ")) {
foreach ( $orderArr as $item) {
$stmt->bind_param("ii", $order, $item);
$stmt->execute();
$order++;
}
$stmt->close();
}
echo json_encode( $orderArr );
$db->close();
}
Change your JS code like this:
{...}
tolerance: 'pointer',
cursor: 'move',
// new LINE
items: '.items', // <---- this is the new line
update: function(event, ui) {
var itId = 3;
var post = $(this).sortable('serialize'); // it could be removed
// new LINES start
var post={},count=0;
$(this).children('.items').each(function(){
post[++count]=$(this).attr('id');
});
// new LINES end
$.ajax({
{...}
With this $.each loop you overwrite your var post -> serialize and define your own sort order. Now look at your $_POST["positions"] with PHP print_r($_POST["positions"]); and you have your positions in your own order.
Below are the codes I am using,
When I selected values from the Database, they are submitted to the database, but if I type something not in the database and I want it submitted, It does not get submitted or echoed by PHP.
Sombody Please help me.
Thank You.
<?php
//Jason File
#Include the connect.php file
include('db_connect2.php');
//get county of selected district
$query = "SELECT * FROM primary_schools ";
$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$customers[] = array(
'Emis_No' => $row['Emis_No'],
'District' => $row['District'],
'County' => $row['County'],
'Subcounty' => $row['Subcounty'],
'Parish' => $row['Parish'],
'School' => $row['School']
);
}
echo json_encode($customers);
?>
//Script
<script type=”text/javascript”>
$(document).ready(function () {
//start EMIS code
var customersSourcel =
{
datatype: "json",
datafields: [
{ name: 'Emis_No'},
{ name: 'District'},
{ name: 'County'},
{ name: 'Subcounty'},
{ name: 'Parish'},
{ name: 'School'}
],
url: 'includes/emis.php',
cache: false,
async: false
};
var customersAdapterl = new $.jqx.dataAdapter(customersSourcel);
$("#emis_no").jqxComboBox(
{
source: customersAdapterl,
width: 200,
height: 25,
promptText: "emis",
displayMember: 'Emis_No',
valueMember: 'Emis_No'
});
$("#emis_no").bind('select', function(event)
{
if (event.args)
{
var index = $("#emis_no").jqxComboBox('selectedIndex');
if (index != -1)
{
var record = customersAdapterl.records[index];
document.form1.district.value = record.District;
$("#county").jqxComboBox({ disabled: false});
document.form1.county.value = record.County;
$("#sub_county").jqxComboBox({ disabled: false});
document.form1.sub_county.value = record.Subcounty;
$("#parish").jqxComboBox({ disabled: false});
document.form1.parish.value = record.Parish;
$("#school").jqxComboBox({ disabled: false});
document.form1.school.value = record.School;
}
}
});
Initialize $customers array with $customers = array(); in the begining of the PHP file before you start pushing values into it with $customers[] = ...
I'm using full calendar js and I am able to connect the events created into the database using phpmyadmin however it does not update the database. Here is the codes:
<link href='css/fullcalendar.css' rel='stylesheet' />
<script src='js/moment.min.js'></script>
<script src='js/jquery.min.js'></script>
<script src='js/fullcalendar.min.js'></script>
<script>
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
editable: true,
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
events: "calendarevents.php",
// Convert the allDay from string to boolean
eventRender: function(event, element, view) {
if (event.allDay === 'true') {
event.allDay = true;
} else {
event.allDay = false;
}
},
selectable: true,
selectHelper: true,
select: function(start, end, allDay) {
var title = prompt('Event Title:');
var url = prompt('Type Event url, if exits:');
if (title) {
var start = $.fullCalendar.moment(start).format();
var end = $.fullCalendar.moment(end).format();
$.ajax({
url: 'calendaraddevents.php',
data: 'title='+ title+'&start='+ start +'&end='+ end +'&url='+ url ,
type: "POST",
success: function(json) {
alert('Added Successfully');
}
});
calendar.fullCalendar('renderEvent',
{
title: title,
start: start,
end: end,
allDay: allDay
},
true // make the event "stick"
);
}
calendar.fullCalendar('unselect');
},
editable: true,
eventDrop: function(event, delta) {
var start = $.fullCalendar.moment(start).format();
var end = $.fullCalendar.moment(end).format();
$.ajax({
url: 'calendarupdateevents.php',
data: 'title=' + event.title + '&start='+ start +'&end=' + end + '&id=' + event.id ,
type: "POST",
success: function(json) {
alert("Updated Successfully");
}
});
},
eventResize: function(event) {
var start = $.fullCalendar.moment(start).format();
var end = $.fullCalendar.moment(end).format();
$.ajax({
url: 'calendarupdateevents.php',
data: 'title=' + event.title + '&start=' + start + '&end=' + end + '&id=' + event.id ,
type: "POST",
success: function(json) {
alert("Updated Successfully");
}
});
}
});
});
</script>
Here is the codes for calendarupdateevents.php
<?php
/* Values received via ajax */
$id = $_POST['id'];
$title = $_POST['title'];
$start = $_POST['start'];
$end = $_POST['end'];
// connection to the database
try {
$bdd = new PDO('mysql:host=localhost;dbname=ththy', 'calendar', '1234');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// update the records
$sql = "UPDATE evenement SET title=?, start=?, end=? WHERE id=?";
$q = $bdd->prepare($sql);
$q->execute();
?>
As halfer said, you aren't passing any parameters to your query.
Try this :
<?php
/* Values received via ajax */
$values = array(
'id' => int($_POST['id']),
'title' => htmlentities($_POST['title'], ENT_QUOTES | ENT_IGNORE, "UTF-8"),
'start' => htmlentities($_POST['start'], ENT_QUOTES | ENT_IGNORE, "UTF-8"),
'end' => htmlentities($_POST['end'], ENT_QUOTES | ENT_IGNORE, "UTF-8")
);
// connection to the database
try {
$bdd = new PDO('mysql:host=localhost;dbname=ththy', 'calendar', '1234');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// update the records
$sql = "UPDATE evenement SET title=?, start=?, end=? WHERE id=?";
$q = $bdd->prepare($sql);
$q->execute($values);
?>
The example is not returning the correct limits of the event. To return the event start-end moments, I suggest:
var start = event.start.format();
var end = event.end.format();
I want to upload multi-file (more than 1000 files, with total more than 2GB).
In PHP, i use function
if (move_uploaded_file($_FILES['files']['tmp_name'][$i], $original_file))
{
$stamp = '../contents/wm_watermark.png';
$this->create_watermark_photo($original_file, $stamp, $view_file, $ext);
$this->makeThumbnail($view_file, $thumb_file, $this->max_width_thumb, $this->max_width_thumb);
//insert photo info to DB
$this->Photo->create();
$this->Photo->save(
array(
'Photo' => array(
'folder_id' => $data_from_preparing_fileInfoList[$i]['sub'],
'name' => $filename
)
)
);
$status = '1';
$count++;
}
I found out that, when use move_upload_file , it didn't upload right now. It only keep in waiting stack. When this function run completedly, then it move file to server.
So, when i use upload process, it gain 100% , this ajax url still run.
$("#image_upload_form").ajaxSubmit({
//url: '/admin/photoGroup/ajax_upload_photo', //photo upload process bar
type: 'POST',
dataType: 'json',
data: { data_from_preparing: data_from_preparing},
beforeSend: function() {
//dialog 1
$("#upload-photo-process .progress-bar").css('width', '0');
$('#upload-photo-process').modal('show');
},
/* progress bar call back*/
uploadProgress: function(event, position, total, percentComplete) {
console.log('percentComplete' + percentComplete);
console.log('position: ' + position);
console.log('total' + total);
var mbPosition = position / 1024 / 1024;
var mbTotal = total / 1024 / 1024;
var txtProcess = percentComplete + '% | ' + mbPosition + 'Mb/' + mbTotal + 'Mb';
var pVel = percentComplete + '%';
$("#upload-photo-process .process-status").html(txtProcess);
$("#upload-photo-process .progress-bar").css('width', pVel);
},
/* complete call back */
complete: function(xhr) {
if (xhr.statusText == "OK") {
$('#upload-photo-process').modal('hide');
$('#upload-done').modal('show');
}
}
/*success: function(data_from_photo_upload) {
}*/
});
Now, i want to when upload progress gain 100%, all of files uploaded to server.
How do i can that?
Thank in advanced.
try this it may work..
//attach
function sendFileToServer(formData, status, file) {
var uploadURL = "index.php?p=ticket-attach&ajax=1"; //Upload URL
var extraData = {}; //Extra Data.
var jqXHR = $.ajax({
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
if (xhrobj.upload) {
xhrobj.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//Set progress
status.setProgress(percent);
}, false);
}
return xhrobj;
},
url: uploadURL,
type: "POST",
contentType: false,
processData: false,
cache: false,
data: formData,
dataType: "json",
success: function(data) {
if (data['error'] == "") {
status.setProgress(100);
status.setFileNameSize(data['fname'].split(",")[0], file.size);
status.appendFN(data['fname']);
//var namef= ;
} else {
//alert(data['error']);
status.errorMsg();
}
}
});
status.setAbort(jqXHR);
}
function createStatusbar(obj) {
this.statusbar = $("<div class='statusbar' id=''></div>");
this.filename = $("<div class='filename'></div>").appendTo(this.statusbar);
this.size = $("<div class='filesize'></div>").appendTo(this.statusbar);
this.abort = $("<div class='abort'>×</div>").appendTo(this.statusbar);
this.progressBar = $("<div class='progressBar'><div></div></div>").appendTo(this.statusbar);
obj.append(this.statusbar);
this.setFileNameSize = function(name, size) {
var sizeStr = "";
var sizeKB = size / 1024;
if (parseInt(sizeKB) > 1024) {
var sizeMB = sizeKB / 1024;
sizeStr = sizeMB.toFixed(2) + " MB";
} else {
sizeStr = sizeKB.toFixed(2) + " KB";
}
this.filename.html(name);
this.size.html("(" + sizeStr + ")");
this.statusbar.attr("sizev", size);
$("#attach_size").attr("sizev", parseInt($("#attach_size").attr("sizev")) + size);
this.setTotalSize();
}
this.setTotalSize = function() {
//set total size
var size = parseInt($("#attach_size").attr("sizev"));
var sizeStr = "";
var sizeKB = size / 1024;
if (parseInt(sizeKB) > 1024) {
var sizeMB = sizeKB / 1024;
sizeStr = sizeMB.toFixed(2) + " MB";
} else {
sizeStr = sizeKB.toFixed(2) + " KB";
}
if (sizeStr != "" && size > 0) $("#attach_size").html("(" + sizeStr + ")");
else $("#attach_size").html("");
}
this.setProgress = function(progress) {
var progressBarWidth = progress * this.progressBar.width() / 100;
this.progressBar.find('div').animate({
width: progressBarWidth
}, 10).html(progress + "%");
if (parseInt(progress) >= 100) {
this.progressBar.hide();
if ($.isFunction(tinymce.get)) tinymce.get('mail_body').isNotDirty = 0;
$("#save_status").html("Not saved");
//this.abort.hide();
} else {
if ($.isFunction(tinymce.get)) tinymce.get('mail_body').isNotDirty = 1;
$("#save_status").html("Not saved");
}
}
this.setAbortFD = function() {
var sb = this.statusbar;
var ts = this;
this.abort.click(function() {
$.ajax({
type: "POST",
url: "index.php?p=ticket-dattach&ajax=1",
data: "fname=" + sb.children(".filename").children("input").val(),
//dataType: "json",
success: function(data) {
tinymce.get('mail_body').isNotDirty = 0;
$("#save_status").html("Not saved");
},
error: function() {
alert('File is not deleted');
}
});
//alert(sb.children(".filename").children("input").val());
$("#attach_size").attr("sizev", (parseInt($("#attach_size").attr("sizev")) - parseInt(sb.attr("sizev"))));
sb.remove();
ts.setTotalSize();
});
}
this.setAbort = function(jqxhr) {
var sb = this.statusbar;
var ts = this;
this.abort.click(function() {
jqxhr.abort();
if (sb.children(".progressBar").children("div").html() == "100%") {
$.ajax({
type: "POST",
url: "index.php?p=ticket-dattach&ajax=1",
data: "fname=" + sb.children(".filename").children("input").val(),
//dataType: "json",
success: function(data) {
tinymce.get('mail_body').isNotDirty = 0;
$("#save_status").html("Not saved");
},
error: function() {
alert('File is not deleted');
}
});
$("#attach_size").attr("sizev", (parseInt($("#attach_size").attr("sizev")) - parseInt(sb.attr("sizev"))));
sb.remove();
} else {
sb.remove();
}
ts.setTotalSize();
});
}
this.appendFN = function(fn) {
this.filename.append("<input type=\"hidden\" name=\"ticket_attach[]\" value=\"" + fn + "\" />");
}
this.errorMsg = function() {
var sb = this.statusbar;
sb.children(".progressBar").children("div").html("File Error");
sb.children(".progressBar").show();
sb.children(".filename").children("input").remove()
}
}
function toggle_class(clas) {
$("." + clas).toggle();
}
function insert_attach(input) {
var files = input.files;
$.each(files, function(idx, file) {
var fd = new FormData();
fd.append('ticket_attach', file);
var obj = $(".note-attachbox");
var status = new createStatusbar(obj); //Using this we can set progress.
status.setFileNameSize(file.name, file.size);
sendFileToServer(fd, status, file);
});
$("#afile_browser").val("");
}
.abort {
color: red;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="note-attachbox" id="attachbox" style="position: relative; display: inline;"></div>
<input type='file' id='afile_browser' onchange='return insert_attach(this);' style="opacity: 0; position: relative; display: inline; cursor: pointer; width: 100px; padding: 1px 0px; border: medium none;" multiple>
<div style="cursor: pointer; color: rgb(59, 179, 36); display: inline-block; font-weight: bold; font-size: 20px; vertical-align: middle; background: none; width: auto; padding: 5px 0px; margin-left: -105px;">+<i style="font-size: 15px; font-weight: normal;">Attach files<span id="attach_size" sizev="0"></span ></i>
</div>
Hello You can follow the below approach to get it done.
I have try my best to make the example as simple as possible.
You need to implement this approach in your code to reach the result.
The below code is working and tested.
Users
Contains user details username, password, email, profile_image and profile_image_small etc.
CREATE TABLE `users` (
`user_id` int(11) AUTO_INCREMENT PRIMARY KEY,
`username` varchar(255) UNIQUE KEY,
`password` varchar(100),
`email` varchar(255) UNIQUE KEY
)
User Uploads
Contains user upload details upload_id, image_name, user_id_fk(foreign key) and timestamp etc.
CREATE TABLE `user_uploads` (
`upload_id` int(11) AUTO_INCREMENT PRIMARY KEY,
`image_name` text,
`user_id_fk` int(11),
`created` int(11)
)
Javascript Code
$("#photoimg").live('change',function(){})- photoimg is the ID name of INPUT FILE tag and $('#imageform').ajaxForm() - imageform is the ID name of FORM. While changing INPUT it calls FORM submit without refreshing page using ajaxForm() method. Uploaded images will prepend inside #preview tag.
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript" src="jquery.wallform.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#photoimg').live('change', function()
{
var A=$("#imageloadstatus");
var B=$("#imageloadbutton");
$("#imageform").ajaxForm({target: '#preview',
beforeSubmit:function(){
A.show();
B.hide();
},
success:function(){
A.hide();
B.show();
},
error:function(){
A.hide();
B.show();
} }).submit();
});
});
</script>
Here hiding and showing #imageloadstatus and #imageloadbutton based on form upload submit status.
index.php
Contains simple PHP and HTML code. Here $session_id=1 means user id session value.
<?php
include('db.php');
session_start();
$session_id='1'; // User login session value
?>
<div id='preview'>
</div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaxImageUpload.php' style="clear:both">
Upload image:
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<input type="file" name="photos[]" id="photoimg" multiple="true" />
</div>
</form>
ajaxImageUpload.php
Contains PHP code. This script helps you to upload images into uploads folder and it will rename image file into timestamp+session_id.extention format to avoid duplicates. This system will store image files into user_uploads with user session id tables
<?php
error_reporting(0);
session_start();
include('db.php');
$session_id='1'; //$session id
define ("MAX_SIZE","2000"); // 2MB MAX file size
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
// Valid image formats
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$uploaddir = "uploads/"; //Image upload directory
foreach ($_FILES['photos']['name'] as $name => $value)
{
$filename = stripslashes($_FILES['photos']['name'][$name]);
$size=filesize($_FILES['photos']['tmp_name'][$name]);
//Convert extension into a lower case format
$ext = getExtension($filename);
$ext = strtolower($ext);
//File extension check
if(in_array($ext,$valid_formats))
{
//File size check
if ($size < (MAX_SIZE*1024))
{
$image_name=time().$filename;
echo "<img src='".$uploaddir.$image_name."' class='imgList'>";
$newname=$uploaddir.$image_name;
//Moving file to uploads folder
if (move_uploaded_file($_FILES['photos']['tmp_name'][$name], $newname))
{
$time=time();
//Insert upload image files names into user_uploads table
mysql_query("INSERT INTO user_uploads(image_name,user_id_fk,created) VALUES('$image_name','$session_id','$time')");
}
else
{
echo '<span class="imgList">You have exceeded the size limit! so moving unsuccessful! </span>'; }
}
else
{
echo '<span class="imgList">You have exceeded the size limit!</span>';
}
}
else
{
echo '<span class="imgList">Unknown extension!</span>';
}
} //foreach end
}
?>
db.php
Database configuration file, just modify database credentials.
<?php
$mysql_hostname = "localhost";
$mysql_user = "username";
$mysql_password = "password";
$mysql_database = "database";
$prefix = "";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password) or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
?>
CSS
Style for image blocks.
#preview
{
color:#cc0000;
font-size:12px
}
.imgList
{
max-height:150px;
margin-left:5px;
border:1px solid #dedede;
padding:4px;
float:left;
}
I have a form with a text input and select option box. The text field uses an autosuggest to allow users to pick options from a list. Once a a value is selected from the autosuggest, the select option box is populated with options dependent on the selection.
I am working to change the code over so that the second box is a text input as well, so as not to limit the users choices (i.e. both fields should allow free text entries if the user does not want to select from the available choices).
I think I've stared at this code too long, and would love some help. Clearly the changes need to come in the loadCountry, populateSelect and loadcountrySelect functions.
I am using PHP, jQuery and jQuery UI Autocomplete.
Any help you could provide would be very much appreciated!
Scripts:
<script src="../../scripts/jquery-1.6.4.js"></script>
<script src="../../scripts/jqueryui/ui/jquery.ui.core.js"></script>
<script src="../../scripts/jquery.ui.widget.js"></script>
<script src="../../scripts/jquery.ui.position.js"></script>
<script src="../../scripts/jquery.ui.autocomplete.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function ord(chr) {
return chr.charCodeAt(0);
}
function chr(num) {
return String.fromCharCode(num);
}
function quote(str) {
return '"' + escape(str.replace('"', "'")) + '"';
}
String.prototype.titleCase = function () {
var chars = [" ", "-"];
var ths = String(this).toLowerCase();
for (j in chars){
var car = chars[j];
var str = "";
var words = ths.split(car);
for(i in words){
str += car + words[i].substr(0,1).toUpperCase() + words[i].substr(1);
}
ths = str.substr(1);
}
return ths;
}
function incrementTerm(term) {
for (var i = term.length - 1; i >= 0; i--){
var code = term.charCodeAt(i);
if (code < ord('Z'))
return term.substring(0, i) + chr(code + 1);
}
return '{}'
}
function parseLineSeperated(data){
data = data.split("\n");
data.pop(); // Trim blank element after ending newline
var out = []
for (i in data){
out.push(data[i].titleCase());
}
return out;
}
function guess(value){
var oldValue = $('.continent_autocomplete').val();
if (oldValue == value)
return;
$('.continent_autocomplete').val(value);
$('.continent_autocomplete').caret(oldValue.length, value.length);
}
function clearGuess(){
var field = $('.continent_autocomplete');
field.val(field.val().substring(0, field.caret().start));
}
function loadcontinent(request, response) {
var startTerm = request.term.toUpperCase();
var endTerm = incrementTerm(startTerm);
$.ajax({
url: '/db/continent.php?startkey='+startTerm+'&endkey='+endTerm,
success: function(data) {
var items = parseLineSeperated(data);
response(items);
},
error: function(req, str, exc) {
alert(str);
}
});
}
function loadcountry(handler) {
var continent = $('.continent_autocomplete').val().toUpperCase();
$.ajax({
url: '/db/country.php?key=' + continent,
success: function(data) {
handler(parseLineSeperated(data));
},
error: function(req, str, exc) {
alert(str);
}
});
}
function populateSelect(select, options) {
select.html('');
if (options.length) {
enableSelect();
for (i in options){
var option = options[i];
select.append($('<option></option>').val(option).html(option));
}
} else {
disableSelect('Country');
}
}
function loadcountrySelect(continentObj){
disableSelect('Loading...');
loadcountry(function(options){
populateSelect($('.country_autocomplete'), options);
});
}
function disableSelect(message){
var select = $('.country_autocomplete');
select.html("<option>" + message + "</option>");
select.attr('disabled', true);
}
function enableSelect(){
var select = $('.country_autocomplete');
select.attr('disabled', false);
}
populateSelect($(".country_autocomplete"), []);
$("input.continent_autocomplete").autocomplete({
source: loadcontinent,
select: function(event, ui){
$("input.continent_autocomplete").val(ui.item.value);
loadcountrySelect(event.target);
}
});
$("input.continent_autocomplete").keyup(function (event){
var code = (event.keyCode ? event.keyCode : event.which);
if (code == 8) { // Backspace
clearGuess();
}
event.target.value = event.target.value.titleCase();
loadcountrySelect(event.target);
});
});
</script>
HTML:
<div id="continent_name">
<label> Continent Name:</label>
<input type="text" id="continent_name" name="continent_name" class="continent_autocomplete" />
</div>
<div id="country">
<label> Country:</label>
<input type="text" id="country_autocomplete" name="country_autocomplete" class="country_autocomplete" />
</div>
continent.php
<?php
$db_host = 'XXX';
$db_user = 'XXX';
$db_password = 'XXX';
$db_name = 'XXX';
$db = new mysqli($db_host , $db_user ,$db_password, $db_name);
if(!$db) {
echo 'There was a problem connecting to the database';
} else {
if(isset($_GET['startkey'])) {
$mysearchString = $db->real_escape_string($_GET['startkey']);
if(strlen($mysearchString) >0) {
$query = $db->query("SELECT DISTINCTROW Continent
FROM locations
WHERE Continent
LIKE '$mysearchString%'
LIMIT 10");
if($query) {
while ($result = $query ->fetch_object()) {
print ucwords(strtolower($result->Continent))."\n";
}
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
}
} else {
echo 'Access denied.';
}
}
?>
country.php
<?php
$db_host = 'XXX';
$db_user = 'XXX';
$db_password = 'XXX';
$db_name = 'XXX';
$db = new mysqli($db_host , $db_user ,$db_password, $db_name);
if(!$db) {
echo 'There was a problem connecting to the database';
} else {
if(isset($_GET['key'])) {
$mysearchString = $db->real_escape_string($_GET['key']);
if(strlen($mysearchString) >0) {
$query = $db->query("SELECT Continent,Country,Abbrev
FROM locations
WHERE Continent
LIKE '$mysearchString%'
ORDER BY Country
LIMIT 20");
if($query) {
while ($result = $query ->fetch_object()) {
print ucwords(strtolower($result->Country))."/".
ucwords(strtolower(strtok($result->Abbrev,";")))."\n";
}
} else {
echo 'ERROR: There was a problem with the query.';
}
} else {
}
} else {
echo 'Access denied.';
}
}
?>
You're going to need to modify your PHP to get this to work optimally (filtering occurring on the server). I would update your PHP so that it queries your database with two parameters (one for country, one for continent):
$continent = $db->real_escape_string($_GET['continent']);
$country = $db->real_escape_string($_GET['country']);
$query = $db->query("SELECT Continent,Country,Abbrev
FROM locations
WHERE Continent ='$continent' and Country like '$country%'
ORDER BY Country
LIMIT 20");
(Please take with a grain of salt; I don't know PHP)
Basically, pass a continent (which was selected in the first input) along with the country search string (which was typed in the second input).
Next, you're going to need to apply the autocomplete widget to the second input. Something like:
$("#country_autocomplete").autocomplete({
source: function (request, response) {
var continent = $("#continent_autocomplete").val()
, country = request.term;
$.ajax({
url: '/db/country.php?continent=' + continent + "&country=" + country,
success: function(data) {
response(parseLineSeperated(data));
},
error: function(req, str, exc) {
alert(str);
}
});
}
});
Just for some polish, you'll probably want to clear #country_autocomplete when #continent_autocomplete changes. You can do that by adding an event handler for autocomplete's change event:
$("input.continent_autocomplete").autocomplete({
source: loadcontinent,
change: function () {
$("#country_autocomplete).val('');
}
});
Lastly, you'll want to remove any code that has to do with populating the country select, since you no longer need it.
The jQuery plugin Autocomplete like Google supports such functionality:
autocomplete.php (agly style, the whole logic at one place -- just to show the principle)
if(!empty($_GET['foo_name']) && !empty($_GET['bar_number'])) {
$sql = 'SELECT ... FROM ... WHERE';
$db = new MySQLi(...);
$db->query($sql);
$numbers = [];
while($row = $result->fetch_assoc()){
$numbers[] = $row['bar_number'];
}
}
echo json_encode($numbers);
autocomplete.html
<link href="/components/autocompletelikegoogle/jquery.autocomplete.css" media="screen" rel="stylesheet" type="text/css">
<script type="text/javascript" src="/components/autocompletelikegoogle/jquery.autocomplete.js"></script>
<script type="text/javascript" src="/js/autocomplete.js"></script>
<input type="text" name="foo_name" id="foo-name" value="">
<input type="text" name="bar_number" id="bar-number" value="">
autocomplete.js
$(function() {
$("#foo").autocomplete({
minLength: 3,
limit: 5,
source : [{
url:"/my/ajax/controller/foo?data[foo_name]=%QUERY%",
type:'remote'
}],
});
});
$(function() {
$("#bar").autocomplete({
minLength: 3,
limit: 5,
appendMethod:'replace',
source : [
function(query, add) {
fooName = $('#foo-name').val();
$.getJSON("/my/ajax/controller/bar?data[bar_number]=" + query + "&data[foo_name]=" + fooName, function(response) {
add(response);
})
}],
});
});