2

I want for user to click a button to delete de div, and for it to no longer show on he webpage i want to change a value in my db so the webpage knows it was deleted and no longer appears in the 'newsfeed'. It does delete the div , but doesnt do anything to the DB.

JS code:

var xmlHttp = createXmlHttpRequestObject();

function createXmlHttpRequestObject() {
var xmlHttp;

//for IE
    if(window.ActiveXObject) {
        try{
            xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");//THIS object is the heart of AJAX for users using IE
        }
        catch(e) {
            alert("Connection Error1");
            xmlHttp = false;
        }
    }
    else {
        try {
            xmlHttp = new XMLHttpRequest(); //THIS object is the heart of AJAX
        }
        catch(e) {
            alert("Connection Error2");
            xmlHttp = false;
        }
    }

    if(!xmlHttp) {
        alert("Connection Error");
    }
    else {
        return xmlHttp;
    }
}

function deletePreview(id){
    xmlHttp.open("GET","entOfferDeletePreview.php?id=" + id + "&t=" +                Math.random(),true);
    xmlHttp.send(null);
    alert(id);
}

function removeDummy(id) {
    var elem = document.getElementById(id);
    elem.parentNode.removeChild(elem);
}

PHP

<?php
include('classes/dbConnection.php');

$link = new dbConnection;

$id = $_GET['id'];

$query = 'UPDATE entoffers SET preview = 1 WHERE id = "$id" ';
$res = $link->query($query);
if($res){
    echo '<script>alert("done");</script>';
}
?>
Cliff Burton
  • 3,414
  • 20
  • 33
  • 47
  • are you calling `deletePreview(id)`? – Sean Feb 18 '15 at 05:31
  • yep, i even put an alert() on it to be positive – user3634777 Feb 18 '15 at 05:56
  • @user3634777 - how is the connection made to your database engine? I can see the code `$link = new dbConnection;` along with the preceding line, but still don't see where you connect to it (and) if it's a mySql one, where you select the database you'd like to use. Sqlite3 only has one db per file, so you wouldn't need to explicitly send the "USE" sql command to it. – enhzflep Feb 18 '15 at 11:50
  • I created a class for db connection, $this->objConnect = new mysqli(SERVER1, USER1, PASS1, DB1); – user3634777 Feb 18 '15 at 16:09

2 Answers2

3

The error is in $query = 'UPDATE entoffers SET preview = 1 WHERE id = "$id" '; 8th row of your PHP file:

From php.net:

Unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.

It means that single quote text is considered as string so your query will be literally UPDATE entoffers SET preview = 1 WHERE id = "$id" with no rows affected.

Double quote text will parse the variables by replacing and processing their value.

If your id field is an integer use:
$query = "UPDATE entoffers SET preview = 1 WHERE id = " . $id;

else if it is a varchar (e.g. 'db1_42') use:
$query = "UPDATE entoffers SET preview = 1 WHERE id = '" . $id; . "';

Note: Data inside the query should be properly escaped to prevent SQL injections.

Community
  • 1
  • 1
Cliff Burton
  • 3,414
  • 20
  • 33
  • 47
  • although I have another question, It does update the DB now, but doesn't alert("done"). Why is that? – user3634777 Feb 18 '15 at 16:08
  • 1
    @user3634777 - this is because you never do anything with the `.responseText` member of the ajax object. In order for this to work, you'd have to (a) capture the response generated by the PHP followed by (b) inserting it into the DOM somewhere so that the script would have a chance to be evaluated. Have a look at `onAddBtn` and `onCommentAddedOrDeleted` in my code - my code would simply print the returned text to the console ``. If you add a div, and then set it's innerHTML to be the ajax's response, it can work. – enhzflep Feb 18 '15 at 16:25
  • @enhzflep Oh ok! Thanks again man, you should be a teacher haha! – user3634777 Feb 18 '15 at 16:35
  • @user3634777 - I've updated the code in my solution to demonstrate this. As it turns out, my idea of adding a new script element didn't work. Instead, I just return one of two strings. In the ajax completion callback function, I grab the returned string and display it via an alert. You could throw it onto the console, or even return html if you'd prefer to create it on the server, rather than the client. – enhzflep Feb 18 '15 at 16:35
  • :grins: Well, they do say that teaching is its own reward... :) – enhzflep Feb 18 '15 at 16:36
1

Here's a rough single-file implementation. It uses prepared statements to mitigate against injection attacks, it implements the ability to add/remove from the database, all db transactions are done via an ajax request to itself.

I've used functions to handle Ajax work, so you can easily fire-off several one after the other, getting notified when the request completes or a message if it fails (you could easily change this to call you if an error occured instead) Since the ajax object passed to the callbacks is the same object that was created when making the request, you've got access to the responseText, responseXML etc, etc members. In this example, I dont do anything with the result - though you can see a commented-out line that prints it.

Notes:

■ it will create a file test.db.sqlite in the same folder as the script.

■ you'd need make minimal changes to work with mysql. This code is adapted from some running on a free host, that doesn't include a SQlite3 PDO driver, and has a low limit on the number of MySql dbs (Basically, # of databases is limited only by diskspace, rather than their artificially low number, designed to tempt you into buyinga primo plan). The changes that come to mind are (1) the way that you make the connection to the db in the first couple of lines, and (2) The code that gets the result set from a query. PDO allows the retrieval of rows as objects - I've returned them as arrays with named keys. Given the task that you're aiming to achieve, I guess #2 is largely irrelevant to you, but still worth mentioning.

Hope it helps! :)

oneFile.php (name is important, since it makes ajax requests to itself)

<?php
    /*
        ensure database and table exist
    */
    $dbFilename = "test.db.sqlite3";
    $sqlDb = new SQLite3($dbFilename);
    $queryStr = "CREATE TABLE if not exists "
              . "`sampleTable` "
              . "(`id` INTEGER PRIMARY KEY AUTOINCREMENT, `comment` TEXT ); ";
    $sqlDb->query($queryStr);

    /*
        do the db insert/delete and then exit (without producing any output)
    */
    if ( isset($_POST['submit']) == true )
    {
        $rawData = $_POST['submit'];
        $parsedData = json_decode( $rawData );
        $newComment = $parsedData->comment;
        $query = $sqlDb->prepare("insert into `sampleTable` (comment) values (:newComment)");
        $query->bindParam(":newComment", $newComment);
        $query->execute();
        printf("comment successfully added");
        exit;
    }

    else if (isset($_POST['delete']) == true)
    {
        $rawData = $_POST['delete'];
        $parsedData = json_decode( $rawData );
        $removeId = $parsedData->id;
        $query = $sqlDb->prepare("delete from `sampleTable` where id = :idToRemove");
        $query->bindParam(":idToRemove", $removeId);
        $query->execute();
        printf("comment successfully deleted");
        exit;
    }

    /*
        Otherwise, just display the html - the remaining code in _this_ php block 
        only contains utility functions.
    */


function getResultArray( $sqlResult )
{
    $resultArray = array();
    while ($curRow = $sqlResult->fetchArray(SQLITE3_ASSOC))
    {
        $j = $sqlResult->numColumns();
        $resultRow = array();
        for ($i=0; $i<$j; $i++)
        {
            $resultRow[ $sqlResult->columnName($i) ] = $curRow[$sqlResult->columnName($i)];
        }
        $resultArray[] = $resultRow;
    }
    return $resultArray;
}

function addCommentSelectorOrMessage($stringSelectorId)
{
    global $sqlDb;      // declared as global so we access the variable defined on line 6 of this file.

    $queryStr = "select * from sampleTable order by id asc";
    $sqlResult = $sqlDb->query($queryStr);

    $resultArray = getResultArray( $sqlResult );

    $nResults = count($resultArray);
    if ($nResults != 0)
    {
        printf("<select id='%s'>\n", $stringSelectorId);
        for ($i=0; $i<$nResults; $i++)
        {
            printf("<option value='%d'>%s</option>\n", $resultArray[$i]['id'], $resultArray[$i]['comment'] );
        }
        printf("</select>\n");
    }
    else
        printf("No database entries yet..<br>\n");
}
?>
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}
function allByClass(className){return document.getElementsByClassName(className);}
function newEl(tag){return document.createElement(tag);}
function newTxt(txt){return document.createTextNode(txt);}
window.addEventListener('load', onDocLoaded, false);

function onDocLoaded()
{
    byId('addBtn').addEventListener('click', onAddBtn, false);
    byId('delBtn').addEventListener('click', onDelBtn, false);
}

function onAddBtn()
{
    var newComment = byId('commentInput').value;
    var params = { comment: newComment };
    myAjaxPost("oneFile.php", "submit", JSON.stringify(params), onCommentAddedOrDeleted);
}

function onDelBtn()
{
    var commentId = byId('commentSelList').value;
    var params = { id: commentId }; //new Object();
    myAjaxPost("oneFile.php", "delete", JSON.stringify(params), onCommentAddedOrDeleted);
}

function onCommentAddedOrDeleted(ajax)
{
    //alert(ajax.responseText);
    if (ajax.responseText.length != 0)
        alert(ajax.responseText);

    window.location.reload();
}

function myAjaxGet(url, callback)
{
    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function()
    {
        if (this.readyState==4 && this.status==200)
            callback(this);
    }
    ajax.onerror = function()
    {
        console.log("AJAX request failed to: " + url);
    }
    ajax.open("GET", url, true);
    ajax.send();
}
function myAjaxPost(url, phpPostVarName, data, callback)
{
    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function()
    {
        if (this.readyState==4 && this.status==200)
            callback(this);
    }
    ajax.onerror = function()
    {
        console.log("AJAX request failed to: " + url);
    }
    ajax.open("POST", url, true);
    ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    ajax.send(phpPostVarName+"=" + encodeURI(data) );
}
</script>
</head>
<body>
        <h3>Add new comment</h3>
        <input id='commentInput'/> <button id='addBtn'>Add comment to DB</button>
        <br>

        <h3>Saved comments</h3>
        <?php addCommentSelectorOrMessage('commentSelList'); ?><button id='delBtn'>Delete</button>
        <div id='ajaxResponseTgt'></div>
</body>
</html>
enhzflep
  • 12,927
  • 2
  • 32
  • 51