Alexandre Cristo Alexandre Cristo - 9 days ago 6
PHP Question

Ajax request not changing HTML

I created a form with two selects and my idea was when the first select is changed, a query is made to the database and the second select is updated with new information.
Since is the first time I'm doing this kind of things, I tried insert some data from that query in a H3 tag instead of using a select tag, but something is not working... The H3 tag starts empty and after changing the select box, the H3 tag remains empty.

This is my code:

<script>
$(document).ready(function(){
$("#show-form-button").click(function(){
$("#show-form-button").hide();
$("#bot-form").show();
});

$("#distrito").on('change', function() {
var selected = $(this).val();
makeAjaxRequest(selected);
});
});

function insertResults(json){
alert("cenas");
$("#teste").val(json["nome"]);
}

function makeAjaxRequest(placeID){
$.ajax({
type: "POST",
data: {placeId: placeID},
dataType: "json",
url: "http://localhost/Paulo%20Cristo%20LDA/insert.php",
success: function(json) {
insertResults(json);
}
});
}


</script>


And this is my PHP script:

<?php

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "paulocristo";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$placeId = $_GET["placeId"];

$query = "SELECT nome from local WHERE id =".$placeId ." AND tipo=0";

$result = $conn -> query($query) or die("Query failed");

if($result -> num_rows > 0)
{
while ($row = $result -> fetch_assoc())
{
echo $row['nome'];
echo json_encode($row);
}
}

?>


Any idea what can be wrong?

I think the problem must be with AJAX because when I run this code, the right information is being displayed in the browser.

Thanks for your patience and sorry for my bad english.

Answer

1) Remove echo $row['nome']; if you echo ANYTHING along with the JSON response, the full response will not be valid JSON and the success function will not be called

2) dont echo your JSON for each row like that, that's not valid either. –

Instead do this:

$response = [];
while ( $row = $result->fetch_assoc() ){
    $response[] = $row;
}
echo json_encode($response);

3) you're checking $_GET['placeId'] but your ajax is using type: "POST". Change your php to $placeId = $_POST["placeId"];

Additionally, and an error function after your success function in your AJAX like the following to better see what is going wrong:

        $.ajax({
            type: "POST",
            data: {placeId: placeID},
            dataType: "json",
            url: "http://localhost/Paulo%20Cristo%20LDA/insert.php",
            success: function(json) {
                insertResults(json);
            },
            error: function(xhr, status, error){
                console.log(xhr); 
            }
        }); 

4) Remember also that the response will be an array of rows not a single row so you'll need to update your function like so:

 function insertResults(json){
        alert("cenas");
        $("#teste").val(json[0]["nome"]); // grab the 'nome' property from the first row in the response
 }
Comments