Return results in different inputs

Asked

Viewed 77 times

0

Guys, here’s my code. My query is returning the results I want, but it’s only returning in an input. How do I return the name_id in one input and 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>
	<script src="js/global.js"></script>
</body>
</html>

1 answer

0

Echo a JSON with json_encode, so you receive a json object in Javascript. Will you have more than one result? but you also have LIMIT 1 in the query and do directly echo of fetch without the while.

But test 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);
    });
  }
});
  • I followed your example, but now the results have stopped coming. =/

  • @Rodrigocaio some error on the console?

  • No. Only the results stopped going to input

  • @Rodrigocaio on the console can see the toolbar/folder network. Any mistakes there? You can see the .post to leave and the return?

  • The data is not coming out I think

  • Any errors in PHP? what version of PHP do you have?

  • My Version 5.5.38

  • @Rodrigocaio you will have more than 1 result in this research?

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.