Nikola Markovic Nikola Markovic - 7 months ago 12
Javascript Question

AJAX response from PHP script not working

I am searching this and other sites for hours now, so I'm getting pretty desperate. No code from many questions with the same topic here works.

I need to insert data into the database and display a message after it is done. Also, I am using AJAX with jQuery so it would be asynchronous. It works just fine, the data gets inserted, but no response message shows.

I am a beginner at PHP and can't understend why this won't work. Relevant code below.

PHP function call:

if(isset($_POST["function"]) && !empty($_POST["function"]) && $_POST["function"] == "cl-add") {
$dbb->addMember("MyUsername", $_POST["name"]);
//$dbb is a DataBaseBroker instance
}


PHP function from the Broker:

function addMember($username, $ime) {
$query = "INSERT INTO clan";
$query.=" (username, ime) ";
$query.="VALUES ('".$username."','".$ime."');";

$result = $this->mysqli->query($query);

if ($result) {
echo("You added a member: ".$ime);
} else {
$response = "An error occured. Please try again.";
$response .= "<br>";
$response .= "Error: ".mysqli_error($connection);
echo $response;
}
}


JQuery function declarations:

var addMember = function(name, responseFn) {
if (name === "") {
alert("Please enter a name");
return;
}
$.ajax({
type : 'POST',
url: '../includes/layout/cl.php',
dataType : 'json',
data : {
'name' : name,
'function' : 'cl-add'
},
success : function(data) {
responseFn(data); //not working, should alert
}
});
}

var responseCallback = function(data) {
alert(data);
}


And inside $(document).ready():

$(document).on('click', '#cl-add', function(evt) {
var name = $("#cl_frm input").val();
addMember(name, responseCallback);
});

Answer

On your code:

dataType : 'json',

Is waiting for a JSON response but you are giving a text response

You should change the dataType: to text or html

dataType : 'html',

or

dataType : 'text',

PHP changes:

<?php
function addMember($username, $ime)
{
    $query = "INSERT INTO clan";
    $query .= " (username, ime) ";
    $query .= "VALUES ('" . $username . "','" . $ime . "');";

    $result = $this->mysqli->query($query);

    $response = null;

    if ($result) {
        $response = "You added a member: " . $ime;
    } else {
        $response = "An error occured. Please try again.";
        $response .= "<br>";
        $response .= "Error: " . mysqli_error($connection);
    }

    echo $response;
    exit;
}
Comments