1

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}]

enter image description here 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"];
1
  • have you tried the json_decode() method. Commented Dec 20, 2017 at 11:12

4 Answers 4

3

first you convert json into array. used json_decode(). for more information about json handle in PHP

// Convert JSON string to Array
  $someArray = json_decode($someJSON, true);
  print_r($someArray);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, for your answer, but still not correct work, where there are the same place names. I edit my post when I used json_decode()
0

For PHP

You can use json_decode()

$array = json_decode('[{"id":261,"name":"Dobre","province_id":2},{"id":1128,"name":"Dobre","province_id":7},{"id":1992,"name":"Dobre Miasto","province_id":14}]');

for ($i=0; $i<=count($array); $i++) {
  echo $array [$i]->name;
}

If you are receiving this json in your javascript code block then you need to use JSON.parse() .

you need to pass your json into parse method like ,

var obj = JSON.parse('[{"id":261,"name":"Dobre","province_id":2},{"id":1128,"name":"Dobre","province_id":7},{"id":1992,"name":"Dobre Miasto","province_id":14}]'); 

alert(obj[0]['id']) // it will return 261

2 Comments

Thanks, but I need convert Json in php
Not work in colnsole I have error: 500 (Internal Server Error)
0

I found solution, just I change loop to foreach:

    foreach ($villages as $key => $value) {
      echo "<a href='".$value["id"]."'>".$value["name"]."</a><br>";
    }

Help me this link: Convert and Loop through JSON with PHP and JavaScript Arrays/Objects from Bilal Ahmed.

Comments

0

Based on you text "But when I search name "Dobre" return only one record, but in databse I have 3 records with name "Dobre". Method print_r() return:"

Your problem is not the json related but it return only one record instead of third right?

You need to iterate through your records data.

something like this maybe

public function query($name) {
    $villages = Village::select('id','name', 'province_id')->where('name', 'like', '%' . $name . '%')->get();
    $returnQuery = '';

    try {
        $villages = json_decode($villages, true);
        for ($i=0; $i < count($villages); $i++) {
          $returnQuery = '<a href="">' . $villages[$i]['name'] . '</a>';
        }
    } catch (Exception $e) {
        // Always good idea to catch json to prevent error if bad data is pass.
    }

    if ($returnQuery != '') {
      return $returnQuery;
    } else {
      return "Nic nie mam";
    }
}

1 Comment

Thank, I've already solved this problem ;) link

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.