Hello I have code Ajax to return value from databse:
function showResult(str) {
action = 'http://localhost/mateusz/mateusz/public/villages/query/';
if (str.length==0) {
document.getElementById("resultSearch").innerHTML="";
document.getElementById("resultSearch").classList.remove("border-search-city");
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("resultSearch").innerHTML=this.responseText;
document.getElementById("resultSearch").classList.add("border-search-city");
}
}
xmlhttp.open("GET",action + str, true);
xmlhttp.send();
}
And code php to connect with databse:
public function query($name) {
$villages = Village::select('id','name', 'province_id')->where('name', 'like', '%' . $name . '%')->get();
for ($i=0; $i<=count($villages); $i++) {
$returnQuery = $villages;
}
if ($returnQuery != '' || $returnQuery != null) {
return '<a href="">'.$returnQuery.'</a>';
} else {
return "Nic nie mam";
}
}
This is code form to search value:
{!! Form::text('string', NULL, ['class' => 'form-control', 'placeholder' => 'podaj frazę', 'onkeyup' => 'showResult(this.value)']) !!}
<div id="resultSearch"></div>
Code php return me value in Json, look like this:
[{"id":261,"name":"Dobre","province_id":2},{"id":1128,"name":"Dobre","province_id":7},{"id":1992,"name":"Dobre Miasto","province_id":14}]
I need return value in a href, and every record from the new line.
Method pluck() and toArray() not work.
Edit:
I used json_decode():
for ($i=0; $i<=count($villages); $i++) {
$returnQuery = $villages;
}
if (!empty($returnQuery)) {
$someArray = json_decode($returnQuery, true);
print_r($someArray);
echo $someArray[0]["name"];
}
But when I search name "Dobre" return only one record, but in databse I have 3 records with name "Dobre". Method print_r() return:
Array ( [0] => Array ( [id] => 261 [name] => Dobre [province_id] => 2 ) 1 => Array ( [id] => 1128 [name] => Dobre [province_id] => 7 ) [2] => Array ( [id] => 1992 [name] => Dobre Miasto [province_id] => 14 ) )
I don't know how I can set number of number of array in this line [0]:
echo $someArray[0]["name"];