0

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.

4
  • check console what is your post url? Commented Jan 20, 2015 at 12:45
  • Did you set any header in PHP? Consider doing exit() at the end of PHP code. Commented Jan 20, 2015 at 12:45
  • post URL is: process.php?section=continent Commented Jan 20, 2015 at 12:45
  • make your post url to be accessed directly, it seems like ajax is not able to post the data on your mentioned url. Commented Jan 20, 2015 at 12:48

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.