Haring10
Haring10

Reputation: 1557

PHP Not passing variables through to ajax

I am passing through The continent to the PHP file from a js file. Basically I need to insert the data to the database (put the continent in) and get the ID of it, but no matter what I do, it returns either an empty string or a 500 Internal Service Error.

Here is the PHP Code:

$continent = $_POST['continent'];

$sql = "INSERT INTO location_continent (`name`) VALUES ('". $continent ."')";

if(!$result = mysqli_query($con, $sql)){
    die('There was an error running the query [' . $db->error . ']');
}

$sql = "SELECT id FROM location_continent WHERE `name` = '". $continent ."'";
$result2 = $con->query($sql);
if(!$result2){
    die('There was an error running the query [' . $con->error . ']');
}
return $result2->num_rows;

Here is the JS Code:

$.ajax({
        url: 'process.php?section=continent',
        type: 'POST',
        data: 'continent='+key,
        success: function(res) {
            continentid = res;
            console.log(res);
        },
        error: function(res) {
            console.log(res);
        }
    });

The Key that is passed through would be something like Africa.

I have tried the following in the php file:

return mysqli_insert_id($conn);
return $result;
$result = mysqli_query($con, $sql);

I have struggled for around 2 hours now. I cannot seem to find the error.

Note Please note that the information is being inserted to the database just fine, just that I cannot get the ID.

Upvotes: 0

Views: 64

Answers (2)

Rakesh Sharma
Rakesh Sharma

Reputation: 13728

In ajax you need to print/echo output for return data rather return statement so try to replace

return $result2->num_rows;

to

echo $result2->num_rows;

also you can send your query string like:-

$.ajax({
        url: 'process.php',
        type: 'POST',
        data: {'section':'continent','continent':key},
        success: function(res) {
            continentid = res;
            console.log(res);
        },
        error: function(res) {
            console.log(res);
        }
    });

Then check your post data by echo if correct something wrong with query executing can't find $con and $db defined on posted code

Upvotes: 2

rwacarter
rwacarter

Reputation: 2004

You are returning but you are not in a function, so try echoing instead (echo mysqli_insert_id($conn);)

Upvotes: 0

Related Questions