I'm using AJAX to send some form data to a php file, where an INSERT into is done. The code I'm using seems correct, but it inserts nothing.

This is the form:

    <form id = "nameform" name ="nameform" method="POST">
        <p>
        <label>Title<input id = "title" type="text" name="title"></label>
    </p>
    <p>
      <label><button id="title" type="button" onclick = "createCollection()">Create a new collection</button></label> 
    </p>

    </form>

The AJAX function:

    <?php
    session_start();

    if(isset($_SESSION["username"])) {
    header("Location: home.php");
    exit;        
    }

    function createCollection(){
    var title = document.getElementById('title').value;
    var photo = "default.png";

    if(title == ''){
    alert("Insert title first!");
     }
    else {

    $.ajax({ 
    type: "POST",
    url: "createCollection.php",
    data: {
       title:title,
       photo:photo
      },
    success: function(){

    console.log(title);
    alert("Success!");
    }
    })};
    }

createCollection.php

   if(isset($_POST["title"]) && isset($_POST["photo"])) {
   $conn = mysqli_connect("localhost", "root", "", "test") or die("Error: 
   ".mysqli_connect_error());

   $title=$_POST["title"]; 
   $photo = $_POST["photo"];
   $username = $_SESSION["username"];



   $query = "insert into collection (title, photo, username) values 
   ('$title','$photo','$username')";

   $res = mysqli_query($conn, $query) or die("Error 
   ".mysqli_error($conn));



   if($res == true)
   {

    echo "Success";


    }
    else {
    echo "fail"; 
    }
    mysqli_close($conn);
    }
    ?>

Everytime I insert a title in the "title" field and then press the submission button, I get the "Success" alert from "success function()". I think the problem is on createCollection.php, as it seems it's never running. Thank you in advice.

P.S: I have already checked the other questions related to mine and it seems that I'm doing correctly, but, still, it's not doing what it should.

0 Answers