I am trying to autocomplete a text box in my search.php code using autocomplete.php
I know that my php code works perfectly and echo's back exactly what is needed for the autocomplete function in jQuery.
Here is the html for the text box.
<input type="text" name='search' id="search" class="input-block-level" autocomplete="off" placeholder="search...">
Here is my script for the autocomplete function
<script>
jQuery(document).ready(function($){
$('#search').autocomplete({source:'autocomplete.php', minLength:2});
});
</script>
Here is the php file
<?php
if ( !isset($_GET['term']) )
exit;
$conn = odbc_connect('Abilis', 'infosysreader', 'Wilsons12');
$query = "SELECT TOP 10 [Del_ad1] FROM [Abilis].[dbo].[Customers] WHERE Del_ad1 LIKE '%".$_GET['term']."%'";
$rs = odbc_exec($conn, $query);
$data = array();
for($i = 0; $i<odbc_num_rows($rs);$i++){
$row = odbc_fetch_array($rs, $i);
$data[] = array(
'label' => $row['Del_ad1'],
'value' => $row['Del_ad1']
);
}
// jQuery wants JSON data
echo json_encode($data);
flush();
Edit:
I found my error at the end of my html file. It was just a mistake on my part, the method I use above works fine.
Not sure what your problem is but since your PHP correctly returns json encoded string then problem is with autocomplete call. Try this and let me know if it makes any difference:
$('#search').autocomplete({
minLength:2,
source: function(request, response) {
$.ajax({
url: 'autocomplete.php',
dataType: 'json',
data: { term : request.term },
success: function(result) {
response(result);
}
});
}
});
Also try changing autocomplete="off" to autocomplete="on"
Remove the following from input element:
class="input-block-level" autocomplete="off" placeholder="search..."
and try with <input type="text" name='search' id="search" />
Related
Actually, I have done location search for normal HTML input type in my site (not functionality wise), I have stored locations name in database, if I search any location it should come jQuery autocomplete also and if I click a bangalore means bangalore records will open, fetching from database how will fix and please help me anyone.
Here my HTML markup:
<div class="form-group keyword">
<input type="text" id="location" placeholder="Search by location" name="location" list="locations" class="searchlocation" />
</div>
Here my PHP code:
<?php
require_once ('config.php');
$q=$_REQUEST["q"];
$sql="SELECT `pg_address` FROM `tbl_master_property` WHERE pg_address LIKE '%$q%'";
$result = mysql_query($sql);
$json=array();
while($row = mysql_fetch_array($result)) {
$data[] = $row['pg_address'];
}
echo json_encode($data);
?>
Ajax and jQuery code:
<script type="text/javascript">
$(function() {
$( "#location" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "locationsearch.php",
dataType: "json",
data: {
q: request.term
},
success: function( data ) {
response( data );
}
});
},
});
});
</script>
I'm developing a WordPress theme and I have a PHP function that is supposed to handle and asynchronous request that gives the server both JSON and an image. My form (for readability, stripped of a bunch of inner HTML) looks like
<form method="POST" action="member-update" enctype="multipart/form-data" id="member-form">
9">
<input type="text" name="fullname" value="">
<input type="text" name="title" value="">
<textarea rows="4" name="bio" form="member-form"></textarea>
<input type="text" name="sord" value="">
<input type="file" name="pic">
<input type="hidden" name="memberAction" value="" />
</form>
and my JavaScript for making the AJAX request is
jQuery('.member-update-button').click( function() {
var parentForm = jQuery(this).closest('form');
var postData = parentForm.serializeArray();
jQuery.post( ajaxurl,
{'action': 'member_update', 'formStuff' : postData},
function(response) { alert('Got this from the server: ' + response); }
);
});
and my PHP function that, through a WordPress hook, handles the request starts out like
function member_update ( )
{
// there must be a more elegant way of getting those values out ....
$name = $_POST['formStuff'][0]['value'];
$title = $_POST['formStuff'][1]['value'];
$bio = $_POST['formStuff'][2]['value'];
$sord = $_POST['formStuff'][3]['value'];
$targetFileName = basename($_FILES['pic']['name']);
$targetFileNameAndPath = 'assets/' . $targetFileName;
I'm getting values out of the $_POST['formStuff'] array, but I am getting nothing for the $_FILES['pic']['name']. Any idea what I'm doing wrong?
You need to use an instance of FormData.
Make following changes in your code.
Add id attribute in your html
<input type="file" name="pic" id="pic">
Changes in js code
jQuery('.member-update-button').click( function() {
formdata = new FormData();
formdata.append( 'action', 'member_update' );
jQuery.each(jQuery('#pic')[0].files, function(i, file) {
formdata.append('file_to_upload', file);
});
jQuery.post( ajaxurl, formdata,function(response) {
alert('Got this from the server: ' + response);
});
});
Finally changes in php function
function member_update()
{
$file = $_FILES['file_to_upload']['tmp_name'];
}
Ok, so I have the following form in a jQuery overlay:
<div class="profile_about_edit_container" id="profile_about_edit_container">
<form id="profile_edit_form" name="profile_edit_form" method="post" action="validation.php">
<label>First Name:</label>
<input type="text" name="firstname" maxlength="50" size="30">
<label>Last Name:</label>
<input type="text" name="lastname" maxlength="50" size="30">
<button type="submit" class="save">Save</button>
<button class="close">Cancel</button>
</form>
</div>
This is displayed using an <a> with class="profile_popups_form" and the following Javascript:
$(document).ready(function() {
$(".profile_popups_form").overlay({
});
});
This shows correctly, and validation.php then echo's an array of error messages like so:
if (count($errors) > 0) {
echo json_encode($errors);
}
But now I'm trying to use jQuery client & server validation on this form.
I tried this:
$(document).ready(function(){
var form = $("#profile_edit_form");
$("#profile_edit_form").submit(function(e) {
e.preventDefault();
var input = $("#profile_edit_form").validator();
$.getJSON(form.attr("action") + "?" + form.serialize(), function(json) {
if (json !== '') {
input.data("validator").invalidate(json);
}
else
$('#profile_edit_form').unbind('submit').submit();
});
});
With the objective of submitting the form and displaying this array of error messages in the normal way jQuery Tools Validation does. But I'm having no luck.
Am I approaching this right? If so, what am I doing wrong? I'm not sure if it's the Javascript causing the issue, or if I'm approaching this right logically. I can find literally no resources explaining how to use JQuery Tools Validation with PHP successfully.
Currently the array is just displayed on the screen as if you echo'd text.
I used the following resource to get the code for returning the array:
http://www.abdullahyahya.com/2012/06/20/javascript-client-side-form-validation-using-server-side-form-validation/
Try doing an ajax request to a php file and get back the response from server. The client side can be done with various ways; from HTML5 tags to plain regex
data = $(this).serializeArray();
//we serialized the data of the form and then we do the ajax request
$.ajax({
url: 'validate.php',
type: 'post',
data: data,
dataType : 'json',
success: function (dat) {
if(dat.error==0){
//dat.error is my returned error from the php file
}else{
//handle the errors
}
}
},
error: function(){
//that's if something is wrong with sent data
alert('failure');
}
});
i have some problem i couldn't figure. I have written the function to get autocomplete searching system using Type-ahead.
This function works perfectly in localhost machine, but when it uploaded to server, the function is broken.
Here's my type-ahead syntax:
<script>
$(document).ready(function(){
$('#q').typeahead({
source: function(query, process){
$.ajax({
url:'autosearch.php',
type:'POST',
data:'query=' + query,
dataType: 'JSON',
async: true,
success:function(data){
process(data);
}
});
}
})
});
</script>
It get value from text input (html below)
<form method="GET" action="search.php" class="form-inline pull-right">
<input name="q" id="q" class="span5" type="text" placeholder="search" data-provide="typeahead" autocomplete="off">
<button type="submit" class="btn btn-primary"> <i class="icon-search icon-white"></i></button>
</form>
what's wrong with this function?
thanks
UPDATE
After getting result from firebug, it shows that error occured on php file
Notice: Undefined index: q in C:\xampp\htdocs\kbase\panel\autosearch.php on line 5
the php code is like this:
<?php
require_once "configuration.php";
$q = mysql_real_escape_string(strtolower($_GET['q']));
$sql = "SELECT DISTINCT title as title FROM ** WHERE title LIKE '%" . $q ."%'";
$rsd = mysql_query($sql);
$cname = array();
while ($rs = mysql_fetch_assoc($rsd))
{
$cname[] = $rs['title'];
}
echo json_encode($cname);
?>
autosearch.php is sent a POST request and not a GET one. It's also sending the variable name as query and not q.
As a head's up, you can simplify the ajax query:
$(document).ready(function(){
$('#q').typeahead({
source: function(query, process) {
$.ajax({
url:'autosearch.php',
type:'POST', // <- defaults to GET (desired by your PHP)
data:'query=' + query, // <- change to {'q': query} for your PHP
dataType: 'JSON', // <- 'json' LOWERCASE
async: true, // <- defaults to true anyway
success: process // <- same function signature
}
})
});
I want to submit a POST form that contains a textarea field and an input field(s) (type="checkbox" with an arbitrary/variable number of checkboxes) on my website via jQuery's .ajax(). PHP receives the textarea data and the ajax response is correctly displayed to the user. However, it seems that PHP is not receiving the checkbox data (was it checked, or not). How can I get this to work? Here is the code I have:
The HTML:
<form method="post" action="myurl.php" id=myForm>
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
...(maybe some more checkboxes - dynamically generated as necessary)
<input id="submit" type="submit" name="submit" value="Submit" onclick="submitForm()" />
</form>
The jQuery:
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: { myField:$("textarea[name=myField]").val(),
myCheckboxes:myCheckboxes },
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
Now, the PHP
$myField = htmlspecialchars( $_POST['myField'] ) );
if( isset( $_POST['myCheckboxes'] ) )
{
for ( $i=0; $i < count( $_POST['myCheckboxes'] ); $i++ )
{
// do some stuff, save to database, etc.
}
}
// create the response
$response = 'an HTML response';
$response = stripslashes($response);
echo($response);
Everything works great: when the form is submitted a new record is stored in my database, the response is ajaxed back to webpage, but the checkbox data is not sent. I want to know which, if any, of the checkboxes have been checked. I've read about .serialize(), JSON, etc, but none this has worked. Do I have to serialize/JSON in jQuery and PHP? How? Is one method better than another when sending form data with checkboxes? I've been stuck on this for 2 days. Any help would be greatly appreciated. Thanks ahead of time!
Yes it's pretty work with jquery.serialize()
HTML
<form id="myform" class="myform" method="post" name="myform">
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
<input id="submit" type="submit" name="submit" value="Submit" onclick="return submitForm()" />
</form>
<div id="myResponse"></div>
JQuery
function submitForm() {
var form = document.myform;
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url:'myurl.php',
data: dataString,
success: function(data){
$('#myResponse').html(data);
}
});
return false;
}
NOW THE PHP, i export the POST data
echo var_export($_POST);
You can see the all the checkbox value are sent.I hope it may help you
var myCheckboxes = new Array();
$("input:checked").each(function() {
data['myCheckboxes[]'].push($(this).val());
});
You are pushing checkboxes to wrong array data['myCheckboxes[]'] instead of myCheckboxes.push
Check this out.
<script type="text/javascript">
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: 'myField='+$("textarea[name=myField]").val()+'&myCheckboxes='+myCheckboxes,
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
}
</script>
And on myurl.php you can use print_r($_POST['myCheckboxes']);
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like.
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
You may also try this,
var arr = $('input[name="myCheckboxes[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
The code you have at the moment seems to be all right. Check what the checkboxes array contains using this. Add this code on the top of your php script and see whether the checkboxes are being passed to your script.
echo '<pre>'.print_r($_POST['myCheckboxes'], true).'</pre>';
exit;