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
Related
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
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]);
});
That's my script on my view.
$(function () {
$('#buttonx').on("click", function (e) {
e.preventDefault();
$.ajax({
url: 'Ficha/VerificarPatrocinador',
contentType: 'application/json; charset=utf-8',
type: 'GET',
dataType: 'json',
data: {i: 100036},
success: function (data) {
$(data).each(function (index, item) {
//$('#NomePatr').append(item.Nome)
$("#NomePatr").val(item.Nome);
});
}
});
});
});
</script>
That's my action on my controller.
public JsonResult VerificarPatrocinador(int i)
{
var db = new FMDBEntities();
db.Configuration.ProxyCreationEnabled = false;
db.Configuration.LazyLoadingEnabled = false;
var consulta = db.Tabela_Participante.Where(p => p.ID_Participante == i);
return Json(consulta.
Select(x => new
{
Nome = x.Nome
}).ToList(), JsonRequestBehavior.AllowGet);
}
I'm a newbie in Ajax/Jquery, when I exclude the parameter it is ok, however, when I try to put the data: {i: 100036} in my script and the parameter in my action. It doesn't work. Why is it happening?
The controller is going fine. The parameter even passes, but I can't return this result in my View.
Thank you.
use [HttpPost] attribute on your controller method
[HttpPost]
public JsonResult VerificarPatrocinador(int i)
{
//Write Your Code
}
and change the ajax type attribute from "GET" to "POST" and use JSON.stringify. Also check the url carefully. your ajax should look like this
$(function () {
$('#buttonx').on("click", function (e) {
e.preventDefault();
$.ajax({
url: 'Ficha/VerificarPatrocinador',
contentType: 'application/json; charset=utf-8',
type: 'POST',
dataType: 'json',
data: JSON.stringify({i: 100036}),
success: function (data) {
$(data).each(function (index, item) {
//$('#NomePatr').append(item.Nome)
$("#NomePatr").val(item.Nome);
});
}
});
});
});
Hope it will help you
I think that #StephenMuecke may be on to something, because I was able to reproduce the (intended) logic with a new project.
The first thing to determine is where the code is going wrong: the server or the client.
Try using the Visual Studio debugger, and placing a breakpoint in VerificarPatrocinador. Then run the client code to see if the breakpoint is hit. When this succeeds, this means the problem is on the client end.
From there use the web browser's debugger in order to determine what is happening. Use the .fail function on the return result from .ajax in order to determine if there was a failure in the HTTP call. Here is some sample code that you can use to analyze the failure:
.fail(function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
});
For more information check out http://api.jquery.com/jquery.ajax/
Change following code when ajax success
$.each(data, function (index, item) {
$("#NomePatr").val(item.Nome);
});
because when you are getting data as object of array, array or collection you can iterate using this syntax and then you can pass to var,dom...and so on where you want to display or take.
jQuery.each() means $(selector).each() you can use for dom element like below syntax: for example
<ul>
<li>foo</li>
<li>bar</li>
</ul>
<script>
$("li").each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
</script>
Using GET is working fine but if it is not secure because data is visible to user when it submit as query string.
while post have
Key points about data submitted using HttpPost
POST - Submits data to be processed to a specified resource
A Submit button will always initiate an HttpPost request.
Data is submitted in http request body.
Data is not visible in the url.
It is more secured but slower as compared to GET.
It use heap method for passing form variable
It can post unlimited form variables.
It is advisable for sending critical data which should not visible to users
so I hope you understand and change ajax type:'GET' to 'POST' if you want.
$.each() and $(selector).each()
Change this line
url: 'Ficha/VerificarPatrocinador'
to:
url: '/Ficha/VerificarPatrocinador'
Because when you use this url "Ficha/VerificarPatrocinador", it will call the API from url: current url + Ficha/VerificarPatrocinador,so it isn't correct url.
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).
i have a html page, which contains a form and i want when the form is successfully submited, show the below div:
<div class="response" style="display: none;">
<p>you can download ithere</p>
</div>
i also have a jquery function:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
$(".response").show();
}
});
});
});
</script>
and in my views.py (code behind) i create a link and pass it to html page. i have:
def backup(request):
if request.is_ajax():
if request.method=='POST':
//create a link that user can download a file from it. (link)
variables = RequestContext(request,{'link':link})
return render_to_response('backup.html',variables)
else:
return render_to_response('backup.html')
else:
return render_to_response("show.html", {
'str': "bad Request! :(",
}, context_instance=RequestContext(request))
backup = login_required(backup)
my problem: it seems that my view doesn't execute. it doesn't show me the link that i send to this page. it seems that only jQuery function is executed. i'm confused. how can i make both of them to execute(i mean jQuery function and then the url i set in this function which make my view to be executed.)
i don't know how to use serialize function. whenever i searched, they wrote that:
The .serialize() method creates a text string in standard URL-encoded notation and produces query string like "a=1&b=2&c=3&d=4&e=5.
i don't know when i have to use it, while i can access to my form field in request.Post["field name"]. and i don't know what should be the data which is in success: function(data) in my situation.
thank very much for your help.
You have to get and display the data from your ajax post function, where data is the response you render through your DJango server, for example:
t = Template("{{ link }}")
c = Context({"link": link})
t.render(c):
Your JS / jQuery should become something like this:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
// 'data' is the response from your server
// (=the link you want to generate from the server)
// Append the resulting link 'data' to your DIV '.response'
$(".response").html('<p>you can download ithere</p>');
$(".response").show();
}
});
});
});
</script>
Hope this helps.