JQuery autocomplete with ajax request as source data - javascript

What I want to do:
I want to do a input text field with a jquery autocomplete function which gets the source data from a cross-domain curl request. The result should look similar like this: http://abload.de/img/jquerydblf5.png (So I actually want to show additional infos which I get from the curl Request). The URL to get the source data is http://www.futhead.com/15/players/search/quick/?term= and in the end I add those letters which are currently typed in at my input field (for example "Ronaldo").
At the moment I only tried to perform the searchrequest without showing all infosin the dropdown as shown in the screen above. I only want to see which playernames I actually got back by the curl request. Later I will try to add more information for the dropdown. Maybe you guys can help me as well with this as well (I think its called custom renderItem ??).
This is what I've tried:
<script>
$( "#tags" ).autocomplete({
source: function (request, response) {
$.ajax({
type: 'GET',
url: 'playerscraper.php',
dataType: "json",
data: function () {
return $("#results").val()
},
success: function (data) {
// I have no idea what this response and map is good for
response($.map(data, function (item) {
return {
label: item.label,
id: item.value,
};
}));
},
});
}
});
</script>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
My playerscraper.php is performing the curl request and actually returns a array (tested with echo):
$term = $_GET['term'];
$curlRequest = new CurlRequest();
$result = $curlRequest->get('http://www.futhead.com/15/players/search/quick/?term=' . $searchterm);
$players = array();
return json_encode($result);
My problem:
I have no idea how to do the source part for the autocomplete function this way, that I get the right results from the ajax request with my searchterm from the input field. When I type in something in the input field, nothing happens (the function which defines the source is getting called - tested with an alert).

Related

Last chance at jQuery AJAX Toggle

I posted this question ealier today, however I recieved a fix (thank you) that works great against my RequestBin endpoint for testing, however when submitting to my AJAX script, its a different story.
Problem: I cant submit my jQuery toggle values to my PHP AJAX script because there is no form name associated with the POST request (so db never updates). I proven this by making a HTML form with the field names and the database updated right away. However this is not the case with this JS toggle method.
jQuery code
$(document).ready(function() {
$('.switch').click(function() {
var $this = $(this).toggleClass("switchOn");
$.ajax({
type: "POST",
url: "https://--------.x.pipedream.net/",
data: {
value: $this.hasClass("switchOn") ? 'pagination' : 'infinite'
},
success: function(data) {
console.log(data);
}
});
});
});
HTML
<div class="wrapper-toggle" align="center">
<label>
<div class="switch"></div>
<div class="switch-label">Use <b>Paged</b> results instead (Current: <b>Infinite</b>)</div>
</label>
</div>
PHP AJAX script
if (array_key_exists('pagination', $_POST)) {
$stmt = $conn->prepare("UPDATE users SET browse_mode = 'pagination' WHERE user_id = 1");
//$stmt->bindParam(":user_id", $account->getId(), PDO::PARAM_INT);
$stmt->execute();
} else if (array_key_exists('infinite', $_POST)) {
$stmt = $conn->prepare("UPDATE users SET browse_mode = 'infinite' WHERE user_id = 1");
//$stmt->bindParam(":user_id", $account->getId(), PDO::PARAM_INT);
$stmt->execute();
}
I cant figure out how to assign a field name to this, as it is not a traditional post form. This is driving me nuts. So the previous solution was applying hasClass() and calling var $this outside of $ajax(), great (and RequestBin receives both requests), but when submitting to PHP its a dead end (no form names).
Given the code above fixed and revised twice, where do I even start without a form ??
We need:
name="pagination"
name="infinite"
But this toggle JS doesn't allow for this. prop() has been removed to get toggle submitting values over (just not my AJAX script).
Any solution appreciated. Thank you again.
You can set your values as Form Data. So the PHP Function will get it just like a traditional form submission:
$(document).ready(function() {
$('.switch').click(function() {
var $this = $(this).toggleClass("switchOn");
var formdata = new FormData();
$this.hasClass("switchOn") ? formdata.append('pagination', 'name') : formdata.append('infinite', 'name');
$.ajax({
type: "POST",
url: "https://--------.x.pipedream.net/",
data: formdata,
success: function(data) {
console.log(data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
More info on JS Form Data: https://developer.mozilla.org/en-US/docs/Web/API/FormData

passing data from laravel view to controller via ajax onchange event

I have a dropdown list in a blade view. I want to send the value of the selected item to the controller immediately onchange. I have 2 routes in web.php:
Route::get('/plots', 'PlotController#index');
Route::get('/plots/{testId}', 'PlotController#getData');
The first one populates the dropdown list. The second one is supposed send the value of the dropdown list to the controller, which pulls stuff from mysql and sends the data back to the view, which draws a chart. I can get the dropdown to populate ok, but I can't figure out how to send the selected value to the controller. I'm trying to use ajax to do it like this:
$(document).ready(function() {
$('#sel_test').change(function() {
var testId = $(this).val();
console.log("testId=" + testId);
$.ajax({
url: 'plots/' + testId,
type: 'get',
dataType: 'json',
success: function(response) {
console.log("success");
}
});
});
});
The testId output to the console is correct but it never makes it to the controller. The error I see in the console is:
GET http://homestead.test/plots/1 500 (Internal Server Error)
I'm pretty new to laravel and find it extremely confusing. Can anyone explain the correct way to do this?
EDIT:
After testing and confirming Rian's answer as correct, I then tried to implement the real code, which of course is much more complicated. Instead of the controller returning the input test_id:
return $request->test_id;
It actually returns a more complex structure:
return view('plot')
->with('measurements',json_encode($result))
->with('events',json_encode($timeline))
->with('limits',json_encode($limits));
When I uncomment the original controller code, including the return section above, it seems to affect the ability of the controller to return anything at all. Here is the first few lines of the PlotController getData method:
public function getData(Request $request) {
Log::debug("made it to PlotController.php#getData");
Log::debug("test_id="+$request->testId);
And here is the log output:
[2020-02-23 16:43:52] laravel.DEBUG: made it to
PlotController.php#getData
The second line does not output anything. Here is what I see in the javascript console after I select an item from the dropdown list:
testId=49 jquery.min.js:2 GET
http://homestead.test/get-data-by-id?test_id=49 500 (Internal Server
Error)
Any ideas?
The easiest way is to get the data in Laravel Request. At least that's how I do it.
So your route shouldn't contain any parameter for that.
Your route will look like this:
Route::get('get-data-by-id', 'PlotController#getData')->name('get.data.by.id');
Your ajax should be like this:
$(document).on('change', '#sel_test',function(){
var testId = $(this).val();
$.ajax({
type:'GET',
url:"{{ route('get.data.by.id') }}",
data:{'test_id':testId},
success:function(data){
console.log(data);
}
});
});
In your controller's getData() function just use Laravel Request to fetch the data.
public function getData(Request $request)
{
// You can return the ID to see if the ajax is working
return $request->test_id;
}
Make it post from Get for easier
At Web.php
Route::post('/list/plots', 'PlotController#getData')->name('getData');
At Blade file Ajax Request :
$(document).ready(function() {
$('#sel_test').change(function() {
var testId = $(this).val();
var url = '{{ route("getData")}}';
var token = "{{ csrf_token()}}";
$.ajax({
method:"post",
url: url,
data:{testId:testId,_token:token}
dataType: 'json',
success: function(response) {
console.log("success",response);
}
});
});
});
At Controller :
public function getData(Request $request){
$testId = $request->testId;
// Write your logic here
}
Try this. Hopefully work for you

Show the data of JSON response using jQuery

I am using an API, which returns a JSON whenever you search something. It is basically a auto complete search API. Whenever you start typing in the box, it hits the API endpoint with a GET request and returns a JSON. Suppose, you start typing "lucky" , then request is https://autocomplete.clearbit.com/v1/companies/suggest?query=lucky and JSON response is
[{"name":"Lucky Brand","domain":"luckybrand.com","logo":"https://logo.clearbit.com/luckybrand.com"},{"name":"LuckyVitamin.com","domain":"luckyvitamin.com","logo":"https://logo.clearbit.com/luckyvitamin.com"},{"name":"Lucky Gunner Ammo","domain":"luckygunner.com","logo":"https://logo.clearbit.com/luckygunner.com"},{"name":"Lucky Orange","domain":"luckyorange.com","logo":"https://logo.clearbit.com/luckyorange.com"},{"name":"Lucky's Market","domain":"luckysmarket.com","logo":"https://logo.clearbit.com/luckysmarket.com"}]
It returns name, domain and logo. I have a html search box so, whenever you start typing, I want to show the logo image, name and domain in a row of each item. But it is not properly showing. This is my code,
html :-
<input type="text" placeholder="type something ..." id="suggest" />
css :-
body{
padding: 30px;
}
JS :- (I am using jQuery)
$(document).ready(function () {
$("#suggest").autocomplete({
delay: 100,
source: function (request, response) {
// Suggest URL
var suggestURL = "https://autocomplete.clearbit.com/v1/companies/suggest?query=%QUERY";
suggestURL = suggestURL.replace('%QUERY', request.term);
// JSON Request
$.ajax({
method: 'GET',
dataType: 'json',
jsonCallback: 'jsonCallback',
url: suggestURL
})
.success(function(data){
response(data[]); //Here I want to pass all the return
//items. I can show only one item,
//like data[1].name but not sure how
//to go through each item.
});
}
});
});
You can use the forEach() Method to go through your Response e.g.
data.forEach(function(item) {
console.log(item.name, item.logo, item.domain);
});
more about forEach here

How to visualize a codeigniter array from a query on my view?

On my model I have the following function which is a query to inner join 3 tables
function get_all_listaproveedorfamilia($clave)
{
$this->db->select('proveedor.razonSocial, proveedor.nombre1, proveedor.telefonoFijo1, proveedor.telefonoMovil1, proveedor.correoElectronico1, proveedor.tipo, familia.clave');
$this->db->from('proveedor');
$this->db->join('relacionproveedorfamilia', 'relacionproveedorfamilia.idProveedor = proveedor.id', 'inner');
$this->db->join('familia', 'familia.id = relacionproveedorfamilia.idFamilia', 'inner');
$this->db->where('familia.clave', $clave);
$this->db->order_by('proveedor.razonSocial');
$query = $this->db->get();
if($query->num_rows() > 0){
return $query->result_array();
}
}
The $clave value is a string retrieved from a select dropdown, and I send it to my controller using ajax
Jquery function in my view to send $clave value
$('#idFamilia').change(function(){
var clave = $("#idFamilia option:selected").text();
if (clave != "Seleccione"){
$.ajax({
url: '<?php echo base_url(); ?>index.php/Proveedor/obtenerListaProveedorFamilia',
method: 'POST',
data: {
clave: clave
}
});
}
});
Here is the code from my controller, where I use the clave value and call the function in my controller
function obtenerListaProveedorFamilia(){
$this->load->model('Proveedormodel');
$clave = $_POST['clave'];
$data['listaproveedorfamilia'] = $this->Proveedormodel->get_all_listaproveedorfamilia($clave);
$data['_view'] = 'proveedor/index';
$this->load->view('layouts/main',$data);
}
I want to visualize the array returned by the function to check if the query is working and getting the values i want to retrieve. I have already tried the following methods to visualize the array adding addtional code to my jquery function $('#idFamilia').change(function(){});
-Get the array from the view and check it on the browser's console
var test = <?php echo json_encode($listaproveedorfamilia); ?>;
console.log(test);
-Trying to append print_r to a pre tag
$('#prueba').append('<?php print_r($listaproveedorfamilia) ?>');
With both options I get the following PHP error on my view
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: listaproveedorfamilia
Filename: proveedor/index.php
This error appears as soon as the page loads, but it should wait for the user to select an option from the select dropdown and then use that option to build the query. How can I fix this and check the content of my array?
You need to add the success method to your ajax call. This is where the data created at the server will be sent.
$('#idFamilia').change(function () {
var clave = $("#idFamilia option:selected").text();
if (clave != "Seleccione") {
$.ajax({
url: '<?php echo base_url(); ?>index.php/Proveedor/obtenerListaProveedorFamilia',
method: 'POST',
data: {
clave: clave
},
success: function (returned) {
console.log(returned);
}
});
}
});
You can use your browser's web dev tool to see what the javascript console has logged.
Because we don't know what the view file contains it's hard to comment on what to expect.
Typically ajax calls are used to return html that return is put into the DOM using $("some_selector").html() or a variety of other DOM manipulation methods to update the current browser screen.
Another way to "visualize" the return would be to simply append it to what is already on the screen. This is not likely what you'll eventually want. But you'll be able to see what came back.
Change the success function to this
success: function (returned) {
$('body').append(returned);
}

display ajax called data in an UI

i have been able to fetch data with an ajax call from active directory .
the php file used to make the ajax call to active directory :http://pastebin.com/tSRxwQL8
The browser console shows that an ajax call returns this :
<p> sn: xxxxxx<br/>givenname: xxxxx<br/>
employeeID: 0050<br/
>distinguishedName: CN=xxxx xxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxxxxx,DC=com<br/>
displayName: Mark Hewettk<br/>sAMAccountName: xxxxxxx<br/>
department: xxxxx<br/>manager: CN=xxxxxx xxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxx,DC=com
<br/>
mail: mhewettk#abc.com<br/>
title: xyz<br/>
I want to take only some attributes above like mail,displayname etc and display in my HTML :
<h2 class="profile__name" id="emailOfUser">Email : </h2>
Now the problem is the jquery that I have used here :
$('.leaderboard li').on('click', function() {
$.ajax({
url: "../popupData/activedirectory.php", // your script above a little adjusted
type: "POST",
data: {
id: $(this).find('.parent-div').data('name')
},
success: function(data) {
console.log(data);
$('#popup').fadeIn();
$('#emailOfUser').html(data); //this line displays all data whereas I want to select only email,displayname from the above console data
//whatever you want to fetch ......
// etc ..
},
error: function() {
alert('failed, possible script does not exist');
}
});
});
problem is this :
$('#emailOfUser').html(data);
this line displays all data whereas I want to select only email,displayname from the above console data
kindly help me how to select only desired attribute data from the above browser console data.
Ideally you should return JSON from PHP file, however if it is not possible for you to make changes to PHP file then you can use split("mail:") and split("title:") to extract data
success: function(data) {
console.log(data);
$('#popup').fadeIn();
var email=(data.split("mail:")[1]).split("title:")[0];
$('#emailOfUser').html(email); //this line displays all data whereas I want to select only email,displayname from the above console data
//whatever you want to fetch ......
// etc ..
},
You are getting response in HTML which makes difficult for you to extract mail, displayname, etc.
You should get the response in JSON which will make it easy for you to extract the required info.
Ask your back-end team to send response in JSON format.
Working Fiddle
Try :
var lines = 'sn: xxxxxx<br/>givenname: xxxxx<br/>employeeID: 0050<br/>distinguishedName: CN=xxxxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxxxxx,DC=com<br/>displayName: Mark Hewettk<br/>sAMAccountName: xxxxxxx<br/>department: xxxxx<br/>manager: CN=xxxxxx xxxxxxx,OU=Employees,OU=Accounts,OU=India,DC=asia,DC=xxxx,DC=com<br/>mail:mhewettk#abc.com<br/>title:xyz<br/>'.split('<br/>');
jQuery.each(lines, function() {
var val = this;
if (val.indexOf('mail') > -1)
// alert(val.split(':')[1]); //Only for test
$('#emailOfUser').html(val.split(':')[1]);
});

Categories