How to use data entered into JQuery Autocomplete form? - php

So i'm trying to pull the info entered into this form and use it for other things.
<form onsubmit="return false;">
Enter a School:
<input id="schoolsearch" type="text" />
<INPUT TYPE=SUBMIT VALUE="GO">
</form>
I know this may seem like a simple question- but i just can't figure it out. This form is acting with a .php file that helps power the autocomplete function.
Would i just use METHOD=post or what?
Thanks in advance for any help

Here is the outline of how ajax works in javascript. For more info see here http://api.jquery.com/jQuery.post/.
run this on.keypress()
$.ajax({
type: 'POST',
url: url, //url of the php file that searches for schools with the given value
data: data, // the data you are sending so something like $('#school').val()
success: success, // prepare to catch what the php returns
dataType: dataType
});

Hiya please see demo here: http://jsfiddle.net/vZtGs/ or please see one of my old replies using few more options in here: jquery autocomplete using '#'
good read here: http://jqueryui.com/demos/autocomplete/ (with other options and events supported)
Code
$( "#autocomplete, #schoolsearch" ).autocomplete({
source: function( req, resp ) {
$.post( "/echo/json/", {
json: '["School1", "School2", "School3", "School4", "School5"]',
delay: 1
}, function(data) {
resp( data );
}, "JSON" );
},
select: function(event, ui) {
//var terms = split(this.value);
alert('Do whatever with this value man: ' + ui.item.value);
return false;
}
});
​

Related

AJAX on keypress?

So i'm a completely rookie at AJAX so I was wondering if someone could help.
I'd like to get this, SQL command to be activated onkeyup:
SELECT * FROM commands WHERE tag=$_POST['search_input']
This is the current code I have for the form:
<form method="post">
<input class="search_input" type="text" name="search_input" placeholder="Search..." onkeyup="suggest()" autocomplete="off" />
</form>
Current jQuery:
$(document).ready(function() {
$('.search_input').keypress(function(event) {
if (event.keyCode == 13) {
event.preventDefault();
}
});
function handleKeyPress(e,form){
var key=e.keyCode || e.which;
if (key==13){
form.submit();
return false;
}
}
});
the function suggest() is what I'd like your guy's help on. To send the command above on a keypress.
Use $.post(). You have here examples http://api.jquery.com/jquery.post/
The basic structure is
$.post(url(string), data(object), function(response){ /* do something */ });
A delay between inputs would be really good so it won't continuously send requests to the server. You may also want to use keyup instead of keypress, test it and you'll see why.
I would recommend to use...
HTML
<form method="post">
<input class="search_input" type="text" name="search_input" placeholder="Search..." autocomplete="off"/>
</form>
JS
// shorthand for document ready
$(function(){
var $input = $('.search_input');
// using on-function (see jQuery Docs)
// bind event instead of using on-attribute (nicer)
// bind input event instead of keyup, because it will fire on paste too
$input.on('input', function(evt){
$.ajax({
// maybe use GET?
type: 'POST',
url: '/yourQueryPath',
// assign the input value to the needed query parameter
data: {'search_string': $input.val()},
success: function(response){
// whatever you want to to with your response
}
)};
});
});
Additionally a hint: Never use unfiltered user input like your SQL does (MySQL-Injection)!
E.g. if you are with PHP please use filter_input() and mysql_real_escape_string() or simliar.

Jquery Autocomplete "almost" working but list doesn't populate completely

I'm trying to use autocomplete in jquery, and it works with the demo data, but I haven't been able to make it work with my own data source. I'm trying to write a mailer where the user just enters a few letters of a person's name, and the contacts database helps autocomplete so that the corresponding emails show up in the "To" field.
I've included the following files:
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
My jQuery code in document.load is below:
$(function() {
function log( message ) {
$('#to').append(message);
console.log(message);
}
$( "#search" ).autocomplete({
source: "search.php",
minLength: 2,
select: function( event, ui ) {
log( ui.item? ui.item.email : "NO" );
}
});
});
And my HTML is:
<div class='ui-widget'><input type='text' class='medium' id='search' /></div> <br />
To:<br />
<div class='ui-widget'> <textarea type='text' style='width:80%; height:24px;' id='to' class='ui-widget-content'></textarea></div>
The result of search.php is fine as far as json is considered, here's a sample of the output when the letters "Ahmed" are pressed:
[{"email":"saddi#yahoo.com","name":"Ahmed Qasim"},{"email":"aaaab#alangari.com.sa","name":"Ahmed Abbas"},{"email":"mokhlef#yahoo.com","name":"Ahmed Sahdi"}]
I know I'm getting this response from search.php because I check Firebug and see it, but it doesn't show up below the search input field... Instead, what does show up is just a stump of a list... as in the image below.
But this exact same thing worked as expected when I used the demo code here: demo Why doesn't the list show up properly? Is there a limit on how much data can be displayed? I've pasted only 3 entries from the JSON output I got, but there were tens.
I think keune has the correct diagnosis. If you don't want to change the output of search.php, you could do something like this:
$( "#search" ).autocomplete({
source: function (request, response) {
$.ajax({
url: "search.php",
type: "POST",
dataType: "json",
data: { searchText: myQuery, maxResults: 10 },
success: function(data) {
var mappedData = $.map(data,
function(item) {
return {
label: item.name,
value: item.email,
id: item.email
};
});
response(mappedData);
}
});
}, ....
What you are returning from server contains email and name fields, jquery ui needs an value and label field.
[{"label":"Ahmed Abbas", value: "Ahmed Abbas"}]
label is what you see on autocomplete list, and value is the value you will get when you select an item.

Reading serialized jquery data in PHP (multiple checkboxes)

JQUERY:
$(document).ready(function(){
$('form').submit(function(){
var content = $(this).serialize();
//alert(content);
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/test/generate',
timeout: 15000,
data:{ content: content },
success: function(data){
$('.box').html(data).fadeIn(1000);
},
error: function(){
$('.box').html('error').fadeIn(1000);
}
});
return false;
});
});
HTML:
<form>
<input type="checkbox" value="first" name="opts[]">
<input type="checkbox" value="second" name="opts[]">
<input type="checkbox" value="third" name="opts[]">
<input type="submit">
</form>
How do i process (or read) multiple checked checkbox's value in PHP? I tried doing $_POST['content'] to grab the serialized data but no luck.
Replace:
data:{ content: content } // <!-- you are prefixing with content which is wrong
with:
data: content
Now in your PHP script you can use $_POST['opts'] which normally should return an array.
Try
echo $_POST['opts'][0]. "<br />";
echo $_POST['opts'][1]. "<br />";
echo $_POST['opts'][2]. "<br />";
You post an array to the Server and it is available in the post variable 'opts'. Remember: Unchecked boxes dont get posted.
The chosen answer still didn't work for me, but here is what did:
var checkedBoxesArr = new Array();
$("input[name='checkedBoxes']:checked").each(function() {
checkedBoxesArr.push($(this).val());
});
var checkedBoxesStr = checkedBoxesArr.toString();
var dataString = $("#" + formID).serialize() +
'&checkedBoxesStr=' + checkedBoxesStr;
[The above code goes in your javascript, before serializing the form data]
First, cycle through the checked boxes and put them into an array.
Next, convert the array to a string.
Last, append them to the serialized form data manually - this way you can reference the string in your PHP alongside the rest of the serialized data.
This answer came partly from this post: Send multiple checkbox data to PHP via jQuery ajax()
there are an Error in your code :
The url should be url: 'http://localhost/test/generate.php' with the extension name

How to send two inputs with jQuery

ok, i have these two input fields where a user puts in two twitter names. When the submit button is pressed, both names should be send to a .php file with the POST method that checks if both usernames exsist on twitter.
Sending and receiving the answer for one value already works, but how can i also add the second? I already have this:
<script type="text/javascript">
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
**data: {'user1' : $('#user1').val() },** //how to append user2?
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}
</script>
the fields in the form:
<td><input type="text" name="user1" id="user1"/></td>
<td><input type="text" name="user2" id="user2" /></td>
and this is how the values should be able to be cathed in the .php:
$user1 = $_POST['user1'];
$user2 = $_POST['user2'];
So the question really is: how can I append the second username to the above jQuery POST function?
p.s. I am starting with javascript and jQuery, how do you guys work with this as no error messages are shown ever.. is there an environment/programm where I get debugging help with javascript?
data: {
'user1' : $('#user1').val(),
'user2' : $('#user2').val()
},
It's a simple enough extension-- just follow the same pattern.
<script type="text/javascript">
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
data: {
'user1' : $('#user1').val(),
'user2' : $('#user2').val()
},
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}
</script>
That said, jQuery does also have a .serialize() function that you could apply on the containing form, which automatically serializes the whole form. This could prove useful for you.
EDIT: It's worth mentioning that the jQuery selectors above look on the id for the name "user1" (etc.), whereas the PHP script expects the form elements' name to be "user1" (etc.). Here you have them as the same thing.
A more reliable jQuery selector that would allow you to always use the name in both jQuery and PHP is simply to use an attribute selector in jQuery:
$('input[name="user1"]').val()
This will catch any <input> element with the name attribute set to "user1".
You're probably looking for serialize. Your code would look something like this:
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
data: $("#your_form").serialize(),
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}
If you're sure you don't want serialize you could try this:
data: {'user1' : $('#user1').val(), 'user2' : $('#user2').val() }
As for your PS, check out Firebug and Webkit developer tools.
You actually don't even need the serialize function. If you just select your form, all form elements will be passed. This way if you just add another form element, like another textbox, it will all be passed in your ajax call.
function checkUsername()
{
$.ajax({
type: 'POST',
url: 'tu.php',
data: $("#your_form"),
dataType: "json",
success: function(data){
$('#uitslag').html(JSON.stringify(data));
$('#user1text').html(data['user1']);
$('#user2text').html(data['user2']);
}
});
}

Sending a value from a dropdown box to PHP via jQuery

I'm trying to take values from a dropdown two boxes and send them to a PHP file which will draw an appropriate field from a mySQL database depending on the combination chosen and display it in a div without refreshing the page using AJAX. I have the second part sorted, but I'm stuck on the first part.
Here is the HTML: http://jsfiddle.net/SYrpC/
Here is my Javascript code in the head of the main document:
var mode = $('#mode');
function get() {$.post ('data.php', {name: form.him.value, the_key: #mode.val()},
function(output) {$('#dare').html(output).show();
});
}
My PHP (for testing purposes) is:
$the_key = $_POST['the_key'];
echo $the_key;
After I have it in PHP as a variable I can manipulate it, but I'm having trouble getting it there. Where am I going wrong? Thanks for your replies!
You need a callback function as well to have the server response to the POST.
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
This snippet will post to ajax/test.html and the anonymous function will be called upon its reply with the parameter data having the response. It then in this anonymous function sets the class with result to have the value of the server response.
Help ? Let me know and we can work through this if you need more information.
Additionally, $.post in jQuery is a short form of
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
your jquery selectors are wrong:
html:
<select id="mode">
jquery selector:
$("#mode").val();
html:
<select name="player">
jquery selector:
$("select[name=player]").val();
You want to add a callback to your ajax request, its not too hard to do, here ill even give you an example:
$.ajax({
url: "http://stackoverflow.com/users/flair/353790.json", //Location of file
dataType: "josn",//Type of data file holds, text,html,xml,json,jsonp
success : function(json_data) //What to do when the request is complete
{
//use json_data how you wish to.;
},
error : function(_XMLHttpRequest,textStatus, errorThrown)
{
//You fail
},
beforeSend : function(_XMLHttpRequest)
{
//Real custom options here.
}
});​
Most of the above callbacks are optional, and in your case i would do the following:
$.ajax({
url: "data.php",
dataType: "text",
data : {name: ('#myform .myinput').val(),the_key: $('#mode').val()},
success : function(value)
{
alert('data.php sent back: ' + value);
}
});​
the ones you should always set are url,success and data if needed, please read The Documentation for more information.

Categories