Make search box with autosuggest - php

I'm trying to make a search box with the google/bing "autosuggest" functionality. Having searched the site, the closest I have found to this is here: Custom box with autocomplete from Google/Bing. Is there any way to read the received json file?
The script on the jsfiddle.net works great, however when I try to replicate the code it doesn't work.
Here is my code:
<html>
<head>
<script>
$(function () {
$("#hulk").autocomplete({
source: function (request, response) {
console.log("source");
$.ajax({
url: "http://api.bing.com/osjson.aspx?Query=" + encodeURIComponent(request.term) + "&JsonType=callback&JsonCallback=?",
dataType: "jsonp",
/*data: {
"Query": request.term,
"JsonType": "callback",
"JsonCallback" : "?"
},*/
success: function (data) {
console.log("success!");
var suggestions = [];
$.each(data, function (i, val) {
console.log("suggestion: " + val);
suggestions.push(val);
});
response(suggestions);
}
});
}
});
});
</script>
</head>
<body>
<input type="text" id="hulk" />
</body>
</html>
I am no expert when it comes to coding (mainly use php) and would appreciate any help to make this work :)
Thanks in advance!

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/js/standalone/selectize.min.js" integrity="sha256-+C0A5Ilqmu4QcSPxrlGpaZxJ04VjsRjKu+G82kl5UJk=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.12.6/css/selectize.bootstrap3.min.css" integrity="sha256-ze/OEYGcFbPRmvCnrSeKbRTtjG4vGLHXgOqsyLFTRjg=" crossorigin="anonymous" />
</head>
<body>
<select id="select-state" placeholder="Pick a state...">
<option value="">Select a state...</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
<option value="CA">California</option>
<option value="CO">Colorado</option>
<option value="CT">Connecticut</option>
<option value="DE">Delaware</option>
<option value="DC">District of Columbia</option>
<option value="FL">Florida</option>
<option value="GA">Georgia</option>
<option value="HI">Hawaii</option>
<option value="ID">Idaho</option>
<option value="IL">Illinois</option>
<option value="IN">Indiana</option>
</select>
</body>
</html>
<script>
$(document).ready(function () {
$('select').selectize({sortField: 'text'});});</script>

Related

Unable to trigger ajax with onclick (but it triggered if use onchange)

New to ajax here. I have a php file that have a form with simple elements in it.
I want to be able to click "Submit" and then have the form data sent to another php to process it
(and this process may take long time), and then when its done, shall return some result (text etc) to the first php file. Here's my code:
<html>
<head>
<script src="jquery.min.js"></script>
<script>
function submitBorrow() { // Call to ajax function
$.ajax({
type: "POST",
url: "sendEmail.php",
data: { test:'yes', wat:'no' },
success: function(html)
{
$("#emailResultDiv").html(html);
}
});
}
</script>
</head>
<body>
<form id="borrowForm" name="borrowForm">
<select name="duration" id="duration" onchange="submitBorrow();">
<option value="3 days">3 days</option>
<option value="4 days">4 days</option>
<option value="5 days">5 days</option>
<option value="6 days">6 days</option>
<option value="1 week">7 days</option>
<option value="2 week">14 days</option>
<option value="3 week">21 days</option>
<option value="1 month">30 days</option>
<option value="40 days">40 days</option>
<option value="60 days">60 days</option>
</select>
<button onclick="submitBorrow();">submitBorrow</button>
<div id="emailResultDiv">Here</div>
</form>
</body>
</html>
Here is content of my sendEmail.php (just a simple php with fake process command sleep.)
<?php
if ($_POST) {
sleep(5);
echo "DONE!";
}
?>
When i change the select item, after 5 secs, the value DONE! is displayed at the div. but when I press the button, it doesn't do that. Why is that, and how to achieve what I need?
You can always use preventDefault() to prevent the form from submitting in such kind of cases.
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"
type="text/javascript"
></script>
<script>
$(document).ready(function () {
$("#submitBorrow").click(function (event) {
event.preventDefault();
// Call to ajax function
$.ajax({
type: "POST",
url: "sendEmail.php",
data: { test: "yes", wat: "no" },
success: function (html) {
$("#emailResultDiv").html(html);
},
});
});
$("#duration").on("change", function (event) {
$("#submitBorrow").click();
});
});
</script>
</head>
<body>
<form id="borrowForm" name="borrowForm">
<select name="duration" id="duration">
<option value="3 days">3 days</option>
<option value="4 days">4 days</option>
<option value="5 days">5 days</option>
<option value="6 days">6 days</option>
<option value="1 week">7 days</option>
<option value="2 week">14 days</option>
<option value="3 week">21 days</option>
<option value="1 month">30 days</option>
<option value="40 days">40 days</option>
<option value="60 days">60 days</option>
</select>
<button id="submitBorrow">submitBorrow</button>
<div id="emailResultDiv">Here</div>
</form>
</body>
</html>
Rookie mistake. After posting a question, I just realized that all buttons in a form shall be Submitting the form if a type is not given.
So just did this and it works:
<button type="button" onclick="submitBorrow();">Borrow</button>
I specified type="button" and it ceased to be a submit button and solved the issue I am having.

How to pass select value to url using Jquery

how to pass the select dropdown value to url
Here is what I tried.
<select name="value">
<option value="1">1</option>
<option value="2">2</option>
<option value="4">4</option>
<option value="10">10</option>
</select>
$(document).ready(function(){ $('select').on('click', function(e){
e.preventDefault();
var value = $('#one').val();
window.location.href = url+'?&'+value;
} }); });
Here is working thing. Also, I am not sure, what exactly do you mean by "pass select value to URL simply"
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var url = "http://www.google.com";
var value = "";
$(document).ready(function(){
$("select").change(function(){
alert($(this).val());
value = $(this).val();
window.location.href = url+'?&'+value;
});
});
</script>
</head>
<body>
Select:
<select name="value">
<option value="1">1</option>
<option value="2">2</option>
<option value="4">4</option>
<option value="10">10</option>
</select>
</body>
</html>
You should use .change instead of on.click. Also add an id for select
<select name="value" id="selectedID">
<option value="1">1</option>
<option value="2">2</option>
<option value="4">4</option>
<option value="10">10</option>
</select>
and
$(document).ready(function(){
$("#selectedID").change(function(){
var value = $('#selectedID').val();
window.location.href = url+'?&'+value;
}
});
The question is not clear if you want to get the value from option and reload the page with a REQUEST query "value?=" with the selected value, use this code
$(document).ready(function()
{
$('select').on('change', function(e)
{
var value = $(this).val();
window.location.href = '?value='+value;
});
});
if you want to just replace the url without reloading try replacing the history state, use this code
$(document).ready(function()
{
$('select').on('change', function(e)
{
var value = $(this).val();
var urlNow = window.location.href.replace(/\?.*/g,'').replace(/\/$/g,'');
history.replaceState({},'',urlNow+'/?value='+value);
});
});

jquery check specific options in a multiselect

Alright I have a multiselect like this :
<select id="filtreMultiselectModif" name="groupes[]" multiple="multiple">
<script>
$('#filtreMultiselectModif').multiselect(
{
includeSelectAllOption: true,
enableFiltering: true,
maxHeight: 200
});
</script>
which give me that :
What I would like to do is to set checked some specific items that I store in a PHP table.
Here's my jquery code (that didn't work)
<script>
$(document).ready(function ()
{
var arrayFromPHP = <?php echo json_encode($tableauIntitule); ?>;
$('#filtreMultiselectModif').multiselect(
{
includeSelectAllOption: true,
enableFiltering: true,
maxHeight: 200
});
$('#filtreMultiselectModif option').each(function(i,option)
{
$.each(arrayFromPHP,function(index,groupe){
if ($(option).text() === groupe)
{
alert (option.text);
$(this).attr('checked', 'checked');
}
});
});
});
Basicly I want every item stored in arrayFromPHP to be checked in the dropdown list but it doesn't seem to work..
Here's the code for my PHP array just in case :
<?php
$tableauIntitule = [];
$i = 0;
while ($data3 = mysqli_fetch_array($req3)) { // Remplissage du SELECT
$intitule = $data3['intitule'];
$tableauIntitule[$i] = $intitule;
}
?>
First of all - your question is regarding bootstrap-multiselect (and not jquery-multiselect).
You can use the multiselect('select', VALUES) in order to set the selected values.
Here is an example:
$(document).ready(function() {
$('#s1').multiselect();
$('#s1').multiselect('select', ['a', 'c', '2']);
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css">
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.min.js"></script>
<select id="s1" multiple="multiple">
<option value="a">Option A</option>
<option value="b">Option B</option>
<option value="c">Option C</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
In your case, if arrayFromPHP is an array (ie arrayFromPHP = ['v1', 'v2', 'v3']) you can do multiselect('select', arrayFromPHP).
One important thing to remember - the data in the array should be the values and not the options data (<option value="VAL">OPTION</option>).

Send text instead of value

I have a HTML attribute in my script:
<select name="cars" onChange="getPrice(this.value)">
<option value="1">Volvo XC90</option>
<option value="2">Saab 95</option>
<option value="3">Mercedes SLK</option>
<option value="4">Audi TT</option>
</select>
When I select the first item and post this to the database my script sends the wrong data to the database. In my database I get the value instead of the text.
By selecting the first <option> I want to post Volvo XC90 instead of s. How can I solve this?
The Ajax script I am using is:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getPrice() {
// getting the selected id in combo
var selectedItem = jQuery('#cars option:selected').val();
// Do an Ajax request to retrieve the product price
jQuery.ajax({
url: 'get.php',
method: 'POST',
data: {'cars': selectedItem },
success: function(response){
// and put the price in text field
jQuery('#cars').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
send.php
<?php
$correct = true;
$product1 = $_POST['product1'] ;
if($correct){
$db = new PDO('mysql:host=localhost;dbname=database', 'root', '');
$query = "INSERT INTO forms(product1) VALUES (?)";
$stmt = $db->prepare($query);
$stmt->execute(array($product1));
header("Location: ./print.php");
}
else
{
echo "<br /><br />Error.<br />\n";
}
?>
Update 1:
Something like this is ideal for my situation:
html:
<select name="cars" onChange="getPrice(this.value)">
<option id="1" value="Volvo XC90">Volvo XC90</option>
<option id="2" value="Saab 95">Saab 95</option>
<option id="3" value="Mercedes SLK">Mercedes SLK</option>
<option id="4" value="Audi TT">Audi TT</option>
</select>
function:
$('[id=cars]').change(function()
{
alert($('[id=cars] option:selected').text());
});
Use html as
<select name="cars" onChange="getPrice(this.value)">
<option value="">Select</option>
<option value="Volvo XC90">Volvo XC90</option>
<option value="Saab 95">Saab 95</option>
<option value="Mercedes SLK">Mercedes SLK</option>
<option value="Audi TT">Audi TT</option>
</select>
and little change in your js function as
function getPrice(selectedItem) {
Instead of
function getPrice() {
You are already sending onChange="getPrice(this.value)" selected value here, just needed to catch it.
so there is no need to code to get again, remove this line
var selectedItem = jQuery('#cars option:selected').val();
Also added new option with blank value as you are sending value in onchange, there will be no effect on first load and it will be selected first column.
I suggest first check not empty for selectedItem then go for ajax.
function getPrice(selectedItem) {
alert(selectedItem);
}
<select name="cars" onChange="getPrice(this.value)">
<option value="">Select</option>
<option value="Volvo XC90">Volvo XC90</option>
<option value="Saab 95">Saab 95</option>
<option value="Mercedes SLK">Mercedes SLK</option>
<option value="Audi TT">Audi TT</option>
</select>
Bunch of things :
1.Replace .val() with .text().
2.Use name selector ( since there is no such element with id = cars )
var selectedItem = jQuery('[name=cars] option:selected').text();
EDIT:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getPrice()
{
var selectedItem = $( "#cars" ).val();
alert(selectedItem);
}
</script>
<select name="cars" onChange="getPrice(this.value)" id="cars">
<option id="1" value="Volvo XC90">Volvo XC90</option>
<option id="2" value="Saab 95">Saab 95</option>
<option id="3" value="Mercedes SLK">Mercedes SLK</option>
<option id="4" value="Audi TT">Audi TT</option>
</select>

Getting value of a dynamically created select

Apologies if my question is a little badly worded but I am not quite sure how to ask it correctly.
I am using PHP to dynamically generate some selects and I was just wondering if it is possible to do this?
Or would I need to add something like {onChange="some_function();"} to each of the selects, passing some variable(s) to id it ?
<script type="text/javascript">
$('Selects ID or class').change(function(event) {
$.post('formupdate.php', { selected: $('Selects ID or class').val() },
function(data) {
$('update the div linked to select').html(data);
}
);
});
</script>
<p>Q1</p>
<select name="Q1select" id="Q1select" class="Q1">
<option value="-">-</option>
<option value="type1">Type One</option>
<option value="type2">Type Two</option>
<option value="type3">Type Three</option>
</select>
<div id="update1" class="Q1"></div>
<p>Q2</p>
<select name="Q2select" id="Q2select" class="Q2">
<option value="-">-</option>
<option value="type1">Type One</option>
<option value="type2">Type Two</option>
<option value="type3">Type Three</option>
</select>
<div id="update2" class="Q2"></div>
<p>Q3</p>
<select name="Q3select" id="Q3select" class="Q3">
<option value="-">-</option>
<option value="type1">Type One</option>
<option value="type2">Type Two</option>
<option value="type3">Type Three</option>
</select>
<div id="update3" class="Q3"></div>
Updated working script :
<script type="text/javascript">
$(document).ready(function () {
$('.question').change(function (event) {
var $this = $(this);
$.post('formupdate.php', { selected:$this.val() },
function (data) {
$('#' + $this.data('div')).html(data);
}
);
});
});
</script>
Updated html :
<select name="select_Q1" id="select_Q1" class="question" data-div="update_Q1">
<option value="-">-</option>
<option value="type1">Type One</option>
<option value="type2">Type Two</option>
<option value="type3">Type Three</option>
</select>
<div id="update_Q1"></div>
<p>Q2</p>
<select name="select_Q2" id="select_Q2" class="question" data-div="update_Q2">
<option value="-">-</option>
<option value="type1">Type One</option>
<option value="type2">Type Two</option>
<option value="type3">Type Three</option>
</select>
<div id="update_Q2"></div>
<p>Q3</p>
<select name="select_Q3" id="select_Q3" class="question" data-div="update_Q3">
<option value="-">-</option>
<option value="type1">Type One</option>
<option value="type2">Type Two</option>
<option value="type3">Type Three</option>
</select>
<div id="update_Q3"></div>
You can assign an event handler to all the select elements using the following:
$('select').change(function(event) {
....
});
​
In the event handler, you can get the value of the select using:
$(this).val()
To get the ID of the select in the event handler, you can use;
$(this).attr('id')
Yes that would work ... but you could simplify a touch :
$('Selects ID or class').change(function(event) {
$.post('formupdate.php', { selected: $(this).val() },
function(data) {
$('update the div linked to select').html(data);
}
);
});
changed the selector within the function to $(this) instead of a class or id that way it will work when you use on multiple elements
To link the select to a div you could either name the div similar to the select ie select id = select_1 and div = div_1 or use the data property
<select name="Q2select" id="Q2select" data-div="divid" class="Q2">
then within your AJAX callback you can do :
$('#' + $(this).data('div')).html(data);
this will set the HTML content of the div with the id = divid ... just an idea
Update
there are a couple of things to try and debug this, first :
function (data) {
$('#update_Q3').html(data);
}
this puts the content in a div - this checks the content returned from the post is working and that you can insert HTML at this point
and try this :
function (data) {
alert($(this).data('div'));
}
this will confirm your selecting the correct div by getting the data
Update 2
My screw up !!!!! $(this) is not working in the callback, try this :
$('.question').change(function (event) {
var $this = $(this);
$.post('formupdate.php', { selected:$(this).val() },
function (data) {
$('#' + $this.data('div')).html(data);
}
);
});
we save $(this) into a variable $this for later use
Here's how I would do it, using a class of question on each <select> and using the id as the unique identifier. The benefit of using a class to grab the selects is if you ever add any other select to the page, they won't be affected.
<script type="text/javascript">
$('.question').change(function(event) {
$.post('formupdate.php', { selected: $(this).val() },
function(data) {
// lets find the div that matches this question and update it
var questionNum = $(this).attr('id').replace('select_Q', '');
var divId = 'update_Q' + questionNum;
$('#' + divId).html(data);
}
);
});
</script>
<p>Q1</p>
<select name="select_Q1" id="select_Q1" class="question">
<option value="-">-</option>
<option value="type1">Type One</option>
<option value="type2">Type Two</option>
<option value="type3">Type Three</option>
</select>
<div id="update_Q1"></div>
<p>Q2</p>
<select name="select_Q2" id="select_Q2" class="question">
<option value="-">-</option>
<option value="type1">Type One</option>
<option value="type2">Type Two</option>
<option value="type3">Type Three</option>
</select>
<div id="update_Q2"></div>
<p>Q3</p>
<select name="select_Q3" id="select_Q3" class="question">
<option value="-">-</option>
<option value="type1">Type One</option>
<option value="type2">Type Two</option>
<option value="type3">Type Three</option>
</select>
<div id="update_Q3"></div>
Yes you could do
//For every select whose id ends with select
$('select[id$=select]').change(function(event) {
//getthe id so that you can post it
var id = this.id;
//save the variable this to another one to use in the callback
var that = this;
//post the selected value and thew id of the select
$.post('formupdate.php', { selected: $(this).val(), id : id },
function(data) {
update the next element after the select
$(that).next().html(data);
}
);
});

Categories