Hello guys i wrote an public function to create a project, but i need to call it in my javascript file. How can i do this.

this is the public function i want to use. the public funtion is in data.php

                public function create($projectid,$projectnaam,$startdatum,$einddatum,$omschrijving)
                {
                    try
                    {
                        $stmt = $this->db->prepare("INSERT INTO projects (projectid, projectnaam, startdatum, einddatum, omschrijving) VALUES (".$projectid.",'".$projectnaam."', '".$startdatum."', '".$einddatum."', '".$omschrijving."')";
                        $stmt->bindparam(":projectid",$projectid);
                        $stmt->bindparam(":projectnaam",$projectnaam);
                        $stmt->bindparam(":startdatum",$startdatum);
                        $stmt->bindparam(":einddatum",$einddatum);
                        $stmt->bindparam(":einddatum",$omschrijving);
                        $stmt->execute();
                        return true;
                    }
                    catch(PDOException $e)
                    {
                        echo $e->getMessage();  
                        return false;
                    }


            }

and this is where i need to call the function, but how? I tryd it like this, but it doesnt work. this is in a javascript file

      url:          'data.php?update',

You could use jquery ajax post method. The data for the post would be all the parameters, that are needed for the public function. The page won't refresh but you will still be able to carry out the insertion into the database. But you need a javascript event to triger the jquery call. It can be page load / ready, click change or similar, depending on what you want to do. This is a made uo example for teh click event (i.e. clicking a submit button in the form).

<script>
$("trigger-element").on("click", function() {
    $.post(
        "data.php",
        { 
            projectid: "<?php echo $projectid;?>",
            projectnaam: "<?php echo $projectnaam;?>",
            startdatum: "<?php echo $startdatum;?>",
            ...
        }
    );
});
</script>

On the data.php page you will catch the parameters in the $_POST array.

<?php
$projectid = $_POST['projectid'];
$projectnaam = $_POST['projectnaam'];
...

// now when you have parameters call the create() function
$myObject->create($projectid,$projectnaam,$startdatum,$einddatum,$omschrijving);

You might also want to do some checking of input data before you use it in your query. Hopefuly the example above does not contain typos since I did not test it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.