Home » Javascript » Magento insert data into database through ajax

Magento insert data into database through ajax

Posted by: admin November 1, 2017 Leave a comment

Questions:

I’m new to ajax so I’m not sure if i’m approaching this correctly, basically I have a variable in javascript that need to be inserted into the database, this is what I have so far…

onInit: function() {
    window.fcWidget.on('widget:loaded', function() {
        window.fcWidget.user.get().then(function(resp) {
            var status = resp && resp.status,
            data = resp && resp.data;
            if (status === 200) {
                if (data.restoreId) {
                    // Update restoreId in  database

                    $.ajax({
                        type: "POST",
                        url: "insert.php",
                        data: data.restoreId, 
                        success: function(data) { alert("Success"); },
                        failure: function(data) { alert("Failure"); }

                    })

                }
            }
        });
    });
}

I have placed the file “insert.php” in the same folder but it seem like it doesn’t get called at all…

This is what insert.php looks like

<?php
    if(Mage::getSingleton('customer/session')->isLoggedIn()){

        if(isset($_POST['data.restoreId']){
            $restoreId =$_POST['data.restoreId'];
        }

        $first = Mage::getSingleton('customer/session')->getCustomer()->getFirstname();
        $last = Mage::getSingleton('customer/session')->getCustomer()->getLastname();

        $fullName = $first . "." . $last;

        //get resource model
        $resource = Mage::getSingleton('core/resource');
        //retrieve write connection
        $writeConnection = $resource->getConnection('core_write');
        //read connection
        $readConnection = $resource->getConnection('core_read');

        $exId = $fullName;
        $resId = $restoreId;

        $testQuery = "SELECT `externalId` FROM `freshchat_user` WHERE `restoreId` = '$fullName'";

        $result = $readConnection->fetchAll($testQuery);

        if(count($result) == '0'){
            $query = "INSERT INTO `freshchat_user`(`externalId`, `restoreId`) VALUES ('$exId','$resId')";
            $writeConnection->query($query);
        }else{
            //echo "nope";
        }
    }
?>

I checked the network tab but insert.php doesn’t seem to be called at all, what is wrong with my code?

Answers:

//Please put your insert.php file in root path(Magento installation path) and change below line in your javascript code.

url: "www.yourwebsite.com/insert.php",