Return results on different inputs

0

Well, here's my code. My query is returning the results I want, however, it is only returning in one input. How do I return the name_id in an input and the location in another?

<?php   
    $nome = $_POST['name'];

    if (isset($_POST['name'])){
        require '../db/conexao.php';
        $consulta = "SELECT * FROM names where name = '" . $nome . "'";
        $resultado = $conexao->query($consulta);

         while ($row = $resultado-> fetch()){
         echo $row['location'];
         echo $row['name_id'];  }
    }
        //echo (mysql_num_rows($resultado) !== 0) ? mysql_result($resultado,0,'location') : 'Not found';

?>

$('input#name-submit').on('click',function(){
	var name= $('input#name').val();
	if ($.trim(name) != ''){
		$.post('ajax/name.php',{name: name}, function(data){
			$('#name-data').val(data);			
		});
	}
});
<html>
<head>
	<title>AJAX</title>
</head>
<body>
	Name: <input type="text" id="name">
	<input type="button" id="name-submit" value="Grabs">	
	<input type="text" id="name-data">
	<input type="text" id="name-datado">
	<script src="http://code.jquery.com/jquery-3.2.1.min.js"></script><scriptsrc="js/global.js"></script>
</body>
</html>
    
asked by anonymous 29.04.2017 / 23:08

1 answer

0

It echoes a JSON with json_encode , so you get a json object in JavaScript. Are you going to have more than one result? but also have LIMIT 1 in the query and directly echo of fetch without while .

But it looks like this:

PHP:

$ name = $ _POST ['name'];

if (isset($_POST['name'])){
    require '../db/conexao.php';
    $consulta = "SELECT * FROM names where name = '" . $nome . "'";
    $resultado = $conexao->query($consulta);

     while ($row = $resultado-> fetch()){
         echo json_encode($row);
     }
}

and in jQuery:

$('input#name-submit').on('click', function() {
  var name = $('input#name').val();
  if ($.trim(name) != '') {
    $.post('ajax/name.php', {
      name: name
    }, function(data) {
      $('#name-data').val(data.location);
      $('#name-datado').val(data.name_id);
    });
  }
});
    
29.04.2017 / 23:14