I used ajax to create a live search connected to the database(site e-commerce). when there is a value in the input several suggestions are fetched in the screen . I want to take the id when the client click in a suggestion. The suggestions cant be clickable i dont know why!! here is my jquery code :
$('.clicked').click(function() {
console.log($("#input_value").val());
});
var x;
var value = $("#input_value").val();
$('.clicked').click(function() {
$.ajax({
type:'GET',
// // url: 'test.php?name=' + $("#testo").val(),
data: { name : value },
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
success: function()
{
window.location.href = 'un_produit.php?id=' + $("#input_value").val();
}
});
I tried to add the class to a div and it works when i click but it doesnt work with the suggestions of the live search .
Instead of using an AJAX request you could use JQUERY autocomplete.
This is an easy example on how this works, your URL source should return the data in this format:
[{"label": "item 1", "value": "0"}, {"label": "item 2", "value": "2"}, {"label": "item 3", "value": "3"}]
I used this url as reference: https://www.codexworld.com/autocomplete-textbox-using-jquery-php-mysql/
$(function() {
$("#autocomplete").autocomplete({
source: [{"label": "item 1", "value": "0"}, {"label": "item 2", "value": "2"}, {"label": "item 3", "value": "3"}], // this can be an url as well
select: function( event, ui ) {
var label = ui.item.label;
if (label === "no results") {
// this prevents "no results" from being selected
event.preventDefault();
}
else {
/* do something with the selected result */
$("#autocomplete").val(ui.item.label);
event.preventDefault();
// or get the id
$("#autocomplete").val(ui.item.value);
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- jQuery UI library -->
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js"></script>
<input type="text" id="autocomplete">
The problem is solved, I had to add the class="clicked" into the the child element of the suggestion div and not to the div itself. thank you
Related
I am using jQuery data tables and fill the data via ajax as json:
https://datatables.net/examples/ajax/simple.html
var tbl = $('.mytbl').DataTable({
"ajax": {
url: "ajax/getData.php",
type: "POST"
}
});
The response of getData.php will be like this:
$myArray['data'][] = array(
"Value 1",
"Value 2",
"Value 3"
}
echo json_encode($myArray);
This works fine:
But how can I define that - for example - value 2 should be text-align right in my table?
Try this
var tbl = $('.mytbl').DataTable({
"ajax": {
url: "ajax/getData.php",
type: "POST"
},
'columnDefs': [{
"targets": 1,
"className": "text-right",
}]
});
You can use render method available in Datatables.
{
data: 'value 2 column',
render: function ( data, type, row ) {
return `<span style="text-align:right">${data}</span>`;
}
}
You can also use css if all column values are right aligned.
I'm struggling to create a dynamic auto-suggest list for a search field using Jquery with data in JSON format. This JSON data is retrieved from an API using PHP.
I want the auto-suggest list to update with each new key typed into the search field. This means that the API has to be called with PHP for each new key pressed, and new JSON data is generated with each key. I can't figure out how to use Jquery/Ajax to:
call the API with each key entered into the search box and
to repopulate the HTML list with the results
I know I'm not doing this right because I can't get the Jquery/Ajax component right. I know I should be using the keyup event and $.ajax to get my JSON data in event callback, but I don't know how to do it properly. Currently I'm able to create a list of autosuggestions/autocompletes from the JSON data that the PHP gets from the API when the page loads with a default query "sail".
Here is my code:
<?php
$subscriptionKey = "12345678";
$host = "https://api.com";
$path = "/Suggestions";
$mkt = "en-US";
$query = "sail";
/*This function calls the API and returns the JSON data in a PHP variable*/
function get_suggestions ($host, $path, $key, $mkt, $query) {
$params = '?mkt=' . $mkt . '&q=' . $query;
$headers = "Content-type: text/json\r\n" .
"Ocp-Apim-Subscription-Key: $key\r\n";
$options = array (
'http' => array (
'header' => $headers,
'method' => 'GET'
)
);
$context = stream_context_create ($options);
$result = file_get_contents ($host . $path . $params, false, $context);
return $result;
}
$result = get_suggestions ($host, $path, $subscriptionKey, $mkt, $query);
echo json_encode (json_decode ($result), JSON_PRETTY_PRINT);
$suggestions = json_decode ($result, true);
$suggestionsArray = call_user_func_array('array_merge',$suggestions["suggestionGroups"]);
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="assets/css/style.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$( "#search" ).keyup(function() {
*When a new key is typed into the search box:*
*call PHP function get_suggestions($host, $path, $subscriptionKey, $mkt, $query) with the current value of the text input in the search box being the value for $query. This function gets the JSON data from the API*
*Parse the JSON data and populate the UL element with the results*
*Do these above steps each time a new key is typed, to create a dynamic list of autosuggestions/autocompletes for the given query*
;
});
</script>
</head>
<body>
<div align="center>
<input type="text" name="search" id="search" placeholder="Search" class="form-control">
</div>
<ul class="list-group" id="result">
<!-- This code was to test to make sure I could format the JSON data from the API, and I know this is not how to properly create an autosuggest list -->
foreach ($suggestionsArray as $name => $arr) {
foreach($arr as $data){
echo "<li class=urlname>";
echo "<a class=urlnamelink href='/search.php?
q=".$data["displayText"]."'>".$data["query"]."</a>\n";
echo "</li>";
}
}
</ul>
</body>
</html>
Here's a sample of the JSON data that the PHP code gets from the API:
{
"_type": "Suggestions",
"queryContext": {
"originalQuery": "sail"
},
"suggestionGroups": [
{
"name": "Web",
"searchSuggestions": [
{
"url": "https:\/\/www.api.com\/search?q=sailpoint&FORM=USBAPI",
"displayText": "sailpoint",
"query": "sailpoint",
"searchKind": "WebSearch"
},
{
"url": "https:\/\/www.api.com\/search?q=sailor+moon&FORM=USBAPI",
"displayText": "sailor moon",
"query": "sailor moon",
"searchKind": "WebSearch"
},
{
"url": "https:\/\/www.api.com\/search?q=sailboats+for+sale&FORM=USBAPI",
"displayText": "sailboats for sale",
"query": "sailboats for sale",
"searchKind": "WebSearch"
},
{
"url": "https:\/\/www.api.com\/search?q=sailrite&FORM=USBAPI",
"displayText": "sailrite",
"query": "sailrite",
"searchKind": "WebSearch"
},
{
"url": "https:\/\/www.api.com\/search?q=sailor&FORM=USBAPI",
"displayText": "sailor",
"query": "sailor",
"searchKind": "WebSearch"
},
{
"url": "https:\/\/www.api.com\/search?q=sailing+anarchy&FORM=USBAPI",
"displayText": "sailing anarchy",
"query": "sailing anarchy",
"searchKind": "WebSearch"
},
{
"url": "https:\/\/www.api.com\/search?q=sailfish&FORM=USBAPI",
"displayText": "sailfish",
"query": "sailfish",
"searchKind": "WebSearch"
},
{
"url": "https:\/\/www.api.com\/search?q=sailflow&FORM=USBAPI",
"displayText": "sailflow",
"query": "sailflow",
"searchKind": "WebSearch"
}
]
}
]
}
$("#search").autocomplete({
source: function (request, response) {
var aObj = {
"ReviseReason": $("#search").val(),
"headId":91
};
var urlpath = base + "Common/GetReason";
$.ajax({
type: "POST",
url: urlpath,
dataType: "JSON",
contentType: "application/json;charset=utf-8",
data: JSON.stringify(aObj),
success: function (result) {
if (result.IsSessionOut != null) {
notify('danger', "Your Session Is Over,Please Login Again");
return false;
} else if (result.Error != null && result.Error != "") {
return false;
} else {
$('#hdByAirShipReason').val("");
response(result.ListAutoCpomplete);
}
}
});
},
//delay: 500,
minLength: 1,
select: function (event, ui) {
$('#hdByAirShipReason').val(ui.item.id);
}
});
This is the type of autocomplete with ajax code you're looking. Mind one thing, you're Json markup is invalid with autocomplete. in autocomplete json data, the field you want to display must have property name 'label' and value as 'id'. You can always include additional property fields however.
I have simple trouble in json
This is my Json code
{ "id" : "1", "name" : "test1" },
{ "id" : "2", "name" : "test2" },
{ "id" : "3", "name" : "test3" },
{ "id" : "4", "name" : "test4" },
{ "id" : "5", "name" : "test5" }
And this it the ajax code I am getting the data
function load_res()
{
$.ajax({
url: 'data.js',
type: 'POST',
dataType: 'json',
success: function(data) {
var div_data='';
$.each(data, function(index, element) {
div_data +="<div ><a href='"+data.name+"'>"+data[index].name+"</a></div>";
});
$('#9lessonsLinks').append(div_data);
}
});
}
HTML part
<a onclick="load_res()">Button</a>
<div id="9lessonsLinks"></div>
Above code it working well and data retrieve and display. But my problem is, when I add a new row to JSON file and I click on load_res() function, it will show old printed data with new data again, multiple printing with multiple clicking. I only want to get the newly added data as last line.
please help me to resolve this. appreciate your great ideas.
Thanks!
Easy fix: change .append to .html
$('#9lessonsLinks').html(div_data);
Empty the list before adding the items to it...
$('#9lessonsLinks').empty().append(div_data);
With javascript like this:
document.getElementById("9lessonsLinks").innerHTML = div_data;
I have a json file that has about twenty objects like this:
{
"firstName": "User1",
"lastName" : "UserLname",
"title": "Human",
"description": "Something Facinating",
"photoURL": "http://www.example.com/wp-content/themes/mytheme/images/profile/user1.jpg",
"contact": {
"email" : "user1#example.com"
}
}
I have a javascript code to display images/description from these objects to a page. I want this site to be uploaded in more than one place. So it doesn't make sense for me to use absolute url in this json file. I overcame the issue in js by passing a variable templateUrl from header.php file and calling it inside the javascript file.
<script type="text/javascript">
var templateUrl = '<?= get_bloginfo("template_url"); ?>';
</script>
And in javascript:$.getJSON(templateUrl+"/scripts/file.json", function(file){....}
I want a way to pass this templateUrl variable to json file too. So I can have image path set to just images/profile/user1.jpg, and I can prepend the url to this depending on where the site is uploaded.
#json.php
{
"firstName": "User1",
"lastName" : "UserLname",
"title": "Human",
"description": "Something Facinating",
"photoURL": "<?= $_GET['var']; ?>/images/profile/user1.jpg",
"contact": {
"email" : "user1#example.com"
}
}
#main page
<script type="text/javascript">
var templateUrl = encodeURI("http://example.com");
$(function(){
$.getJSON(
'json.php?var=' + templateUrl,
function(data){
$.each(data, function(key, val){
console.log(key + ": " + val);
});
}
);
});
</script>
Output:
firstName: User1
lastName: UserLname
title: Human
description: Something Facinating
photoURL: http://example.com/images/profile/user1.jpg
contact: [object Object]
I havent tried this before and my solution hasnt worked.
In mysql I would be able to write it using a while loop but im trying to pull the data through ajax.
Can someone help
var qString = 'country=' +country+'&continent='+continent;
$.post('/assets/inc/get-country.php', qString, function (data) {
$('#'+continent).append('<li>'+data[0].country+' '+data[0].company+'</li>');
}, "json");
The above returns in console.log's ajax response the following
[{
"continent": "Europe",
"country": "Spain",
"company": "Universidade de Vigo CITI",
"comments": "We are very satisfied with the disrupter. It's equipment is very easy to use and effective in breaking cells. I also would like to thank Constant System for for the assistance provided."
}, {
"continent": "Europe",
"country": "Spain",
"company": "IPLA",
"comments": "The Constant Systems cell disruptor has made extraction of membrane proteins from Gram positives a reproducible and efficient task in our lab."
}]
How can I get this to display as an li list on my page?
Thanks in advance
EDIT
$("#comments-tabs div.country a").click(function(e){
e.preventDefault();
var continent = $(this).parent().attr("id");
var country = $(this).attr("name");
console.log(continent+country);
var qString = 'country=' +country+'&continent='+continent;
$.post('/assets/inc/get-country.php', qString, function (data) {
for(company_nr in data){
$('#'+continent).append('<li>'+data[company_nr].country+' '+data[company_nr].company+'</li>')
}
}, "json");
});
Just loop it in javascript:
function (data)
{
for(company_nr in data)
{
$('#'+continent).append('<li>'+data[company_nr].country+' '+data[company_nr].company+'</li>')
}
}