|
You last visited: Today at 16:40
Advertisement
Select2 Ajax Api
Discussion on Select2 Ajax Api within the Web Development forum part of the Coders Den category.
12/13/2018, 21:38
|
#1
|
elite*gold: 200
Join Date: Mar 2011
Posts: 352
Received Thanks: 9
|
Select2 Ajax Api
Hi,
ich wollte eine Select box haben wo man seinen Stadtnamen eingeben muss. Dann sollte die Stadt angezeigt werden in der Select-Box was jedoch bei mir nicht passiert. Habe ich irgendwas falsch gemacht oder etwas vergessen?
Hier ist meine Seite, dort könnt ihr euch ein Überblick erschaffen der Select-Box
Hier ist die Api
Code:
enter_city.php
HTML Code:
<script src="../js/jquery.min.js"></script>
<script src="../js/select2.min.js"></script>
<link rel="stylesheet" href="../css/select2.min.css">
<select class="js-data-example-ajax">
</select>
<script type="text/javascript">
$(document).ready(function() {
$('.js-data-example-ajax').select2({
width:'100%',
ajax: {
url: 'api.php',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});
});
</script>
Api.php
PHP Code:
<?php header("Content-Type: application/json; charset=UTF-8"); require_once __DIR__ . '/../config/connect.php'; if($stmt = $pdo->prepare("SELECT * FROM `dataset` WHERE `city` LIKE :city LIMIT 500;")) { $param = ["city" => "{$_GET['q']}%"]; $stmt->execute($param); $ct = $stmt->rowCount(); $prod = array(); $prod['records'] = array(); if($ct > 0) { while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { extract($row); $product = array( 'id' => $row['primary_key'], 'zipcode' => $row['zipcode'], 'city' => $row['city'], 'state' => $row['state'], 'community' => $row['community'] ); array_push($prod["records"], $product); } http_response_code(200); echo json_encode($prod, JSON_UNESCAPED_UNICODE); } else { echo json_encode(array("Message" => "City not found")); } } ?>
|
|
|
12/13/2018, 22:38
|
#2
|
elite*gold: 0
Join Date: Apr 2011
Posts: 11,118
Received Thanks: 2,435
|
Quote:
Originally Posted by Cc_Cc_Cc
Hi,
ich wollte eine Select box haben wo man seinen Stadtnamen eingeben muss. Dann sollte die Stadt angezeigt werden in der Select-Box was jedoch bei mir nicht passiert. Habe ich irgendwas falsch gemacht oder etwas vergessen?
Hier ist meine Seite, dort könnt ihr euch ein Überblick erschaffen der Select-Box
Hier ist die Api
Code:
enter_city.php
HTML Code:
<script src="../js/jquery.min.js"></script>
<script src="../js/select2.min.js"></script>
<link rel="stylesheet" href="../css/select2.min.css">
<select class="js-data-example-ajax">
</select>
<script type="text/javascript">
$(document).ready(function() {
$('.js-data-example-ajax').select2({
width:'100%',
ajax: {
url: 'api.php',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});
});
</script>
Api.php
PHP Code:
<?php header("Content-Type: application/json; charset=UTF-8"); require_once __DIR__ . '/../config/connect.php'; if($stmt = $pdo->prepare("SELECT * FROM `dataset` WHERE `city` LIKE :city LIMIT 500;")) { $param = ["city" => "{$_GET['q']}%"]; $stmt->execute($param); $ct = $stmt->rowCount(); $prod = array(); $prod['records'] = array(); if($ct > 0) { while($row = $stmt->fetch(PDO::FETCH_ASSOC)) { extract($row); $product = array( 'id' => $row['primary_key'], 'zipcode' => $row['zipcode'], 'city' => $row['city'], 'state' => $row['state'], 'community' => $row['community'] ); array_push($prod["records"], $product); } http_response_code(200); echo json_encode($prod, JSON_UNESCAPED_UNICODE); } else { echo json_encode(array("Message" => "City not found")); } } ?>
|
Du solltest bevor du so etwas fragst erstmal die grundlegenden Sachen überprüfen...
Du hast in deinem css Ordner eine select2.min.js Datei statt einer select2.min.css liegen.
Wenn ich diese nun manuell über
Code:
$('body').append('<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.css">')
einbinde, wird der Input schon einmal richtig dargestellt.
Allerdings funktioniert dieser nicht korrekt da deine processResults beim inizialiseren des select2 nicht korrekt ist.
Du solltest die Dokumentation von select2 mal durchlesen was genau dort zurück gegeben werden muss.
P.s.
Wenn du folgendes einfach mal in die Konsole eingibst und dann im Input suchst, siehst du in der Konsole das auch richtig gesucht wird...
Nur das Json ist u.a. falsch aufgebaut
Code:
$('body').html("<link rel='stylesheet' type='text/css' href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css'><select class='js-data-example-ajax'></select><script>$(document).ready(function() { $('.js-data-example-ajax').select2({ width:'100%', ajax: { url: 'https://wantdatas.eu/pages/api.php', dataType: 'json', delay: 250, processResults: function (data) { console.log(data); return { results: data.records }; }, cache: true } });});</script>")
|
|
|
12/14/2018, 00:30
|
#3
|
elite*gold: 200
Join Date: Mar 2011
Posts: 352
Received Thanks: 9
|
Quote:
Originally Posted by .ƒaℓsє.
Wenn du folgendes einfach mal in die Konsole eingibst und dann im Input suchst, siehst du in der Konsole das auch richtig gesucht wird...
Nur das Json ist u.a. falsch aufgebaut
|
Hab grad 1-2 Stunden alles durchgeguckt blicke aber nicht durch. In der Konsole sucht ja er richtig wie du gesagt hast, aber ich versteh nicht wieso er es nicht auch anzeigt. Bin auf das hier gestoßen:
Code:
<script type="text/javascript">
$(document).ready(function() {
$(".js-data-example-ajax").select2(
{
width:'100%',
ajax: {
url: 'https://api.github.com/search/repositories',
dataType: 'json',
type: "GET",
delay: 250,
data: function (params) {
return {
q: params.term
};
},
processResults: function (data) {
var res = data.items.map(function (item) {
return {id: item.id, text: item.name};
});
return {
results: res
};
}
},
});
});
</script>
Wenn ich die URL eingebe klappt es mit der API:
wenn ich meine URL eingebe: api.php
steht da:
Quote:
jQuery.Deferred exception: Cannot read property 'map' of undefined TypeError: Cannot read property
|
Du meintest ja das mein JSON falsch aufgebaut ist, hab das aber so gemacht wie im Tutorial auf einer Seite.
|
|
|
12/14/2018, 02:02
|
#4
|
elite*gold: 0
Join Date: Apr 2011
Posts: 363
Received Thanks: 166
|
if u compare the two apis, the one of github has an array named items, the one of yours is named records
So change:
$(".ajax2").select2(
{
width:'100%',
ajax: {
url: 'api.php',
dataType: 'json',
type: "GET",
delay: 250,
data: function (params) {
return {
q: params.term
};
},
processResults: function (data) {
var res = data. records.map(function (item) {
return {id: item.id, text: item.name};
});
return {
results: res
};
}
},
});
});
|
|
|
12/14/2018, 02:12
|
#5
|
elite*gold: 200
Join Date: Mar 2011
Posts: 352
Received Thanks: 9
|
Quote:
Originally Posted by elmarcia
if u compare the two apis, the one of github has an array named items, the one of yours is named records
So change:
$(".ajax2").select2(
{
width:'100%',
ajax: {
url: 'api.php',
dataType: 'json',
type: "GET",
delay: 250,
data: function (params) {
return {
q: params.term
};
},
processResults: function (data) {
var res = data. records.map(function (item) {
return {id: item.id, text: item.name};
});
return {
results: res
};
}
},
});
});
|
Thank you for the answer. I have change it. The error message is away but It doesnt shows the Results
|
|
|
12/14/2018, 02:31
|
#6
|
elite*gold: 0
Join Date: Apr 2011
Posts: 363
Received Thanks: 166
|
Quote:
Originally Posted by Cc_Cc_Cc
Thank you for the answer. I have change it. The error message is away but It doesnt shows the Results
|
That's because there is not field name in the json
{"id":"5","zipcode":"01945","city":"Guteborn","sta te":"Brandenburg","community":"Landkreis Oberspreewald-Lausitz"}
//simplified version
processResults: function (data) {
var res = data.records.map(function (item) {
return {id: item.id, text: item. city};
});
return {
results: res
};
You will also have to check if not cities found
Code:
$(".ajax2").select2({
width:'100%',
ajax: {
url: 'api.php',
dataType: 'json',
type: "GET",
delay: 250,
data: function (params) {
return {
q: params.term
};
},
processResults: function (data) {
//check if results found
var res;
if(data.hasOwnProperty("records")){
res = data.records.map(function (item) {
return {id: item.id, text: item.city};
});
return {
results: res
};
}else{
return {results:[]};
}
},
noResults: function(query) {
return 'No results matching: ' + query;
}
}
});
|
|
|
12/14/2018, 22:18
|
#7
|
elite*gold: 0
Join Date: Apr 2011
Posts: 11,118
Received Thanks: 2,435
|
Quote:
Originally Posted by Cc_Cc_Cc
Hab grad 1-2 Stunden alles durchgeguckt blicke aber nicht durch.
|
Naja dann solltest du dir Gedanken machen wie du in Zukunft besser suchen/googeln kannst.
Habe dir ja schon den Tipp gegeben das dein Json was zurückgegeben wird falsch ist, daraufhin hättest du dir sofort die Seite zu json/data Format durchlesen können ( ).
Dort ist ein minimum Beispiel und im dritten Satz steht
Quote:
Each object should contain, at a minimum, an id and a text property.
|
Habe dir dann noch den Tipp gegeben das deine processResults function falsch ist, hättest du nach "processResults" in der Select2 Dokumentation gesucht wärst du sofort auf die Seitehttps://select2.org/data-sources/ajax#transforming-response-data gekommen.
Dort steht (mit einem Beispiel)
Quote:
You can use the ajax.processResults option to transform the data returned by your API into the format expected by Select2
|
Das erwartete Format hättest du im ersten Punkt schon erfahren.
|
|
|
|
Similar Threads
|
API Error Code: 100 API Error Description: Invalid parameter Error Message: redirect_
04/08/2012 - elite*gold Trading - 2 Replies
API Error Code: 100
API Error Description: Invalid parameter
Error Message: redirect_uri URL is not properly formatted
Das bekomme ich wenn ich ne App installiere... ich habe schon 3 Apps richtig installiert, danach kam immer das bei anderen Apps die ich installiert habe..
was heisst das? redirect_uri URL is not properly formatted
|
Frage zu dem Befehl "Select2"
03/24/2012 - Metin2 Private Server - 0 Replies
Kann mir jemand bitte diesen Befehl besser erläutern, weil ich keine ahnung habe was der unterschied zu "Select" ist.
|
[GUIDE]Api Sheild to be against API Tools!
10/15/2011 - Metin2 PServer Guides & Strategies - 8 Replies
I got lot's of pm's from people asking me about api tool shield , so i decided to make a guide to show ya all how to get rid of the nowadays hackers in your servers ...
First ... Open CONFIG of each channel , set pk_server:0 to pk_server:1
then in set adminpage_ip1 with adminpage_ip1: 192.168.2.(write yur real ip here) without quotes or space , just write it after the 192.168.2 directly like this ..
example : adminpage_ip1: 192.168.2.ip
And keep doing that for all CONFIG of all...
|
[ ALL IN ONE ] Lizenserver 7120 | API Server | API Tools
07/07/2011 - Metin2 PServer Guides & Strategies - 45 Replies
Hallo @all ServerAdmins!
Hier möchte ich euch ein Projekt von mir vorstellen der vieles einfacher macht.
Was ist das?
Ein Arbeitsplatz für Administratoren von Mt2 Server.
Was kann es?
behebt das Problem
socket_connect: HOST 220.95.239.40:7120, could not connect.
|
[HELP] Api tool v2 and other api's
05/28/2011 - Metin2 Private Server - 0 Replies
Hi,
can someone tell me where i can find the api tool v2 fix?
and if there are other types of API tools
Thank you very much
|
All times are GMT +2. The time now is 16:40.
|
|