简体   繁体   中英

Update MySQL using AJAX and PHP

I'll go slow, not for your sake..for mine. I'm real new at trying to to do this. What I'm trying to do is update live a MySQL DB from an HTML table. This is how each is built.

 echo ("<td id=\"callsign:$row[recordID]\" contenteditable=\"true\" 
                onClick=\"showEdit(this)\"
                onBlur=\"saveToDatabase(this,'callsign',$row[recordID])\" 
                style='text-transform:uppercase'>
                $row[callsign]</td>");

This is how it renders.

 <td id="callsign:6" contenteditable="true" onclick="showEdit(this)" onblur="saveToDatabase(this,'callsign',6)" style="text-transform: uppercase; background-color: rgb(253, 253, 253); background-position: initial initial; background-repeat: initial initial;">
                KA0SXY</td>

Here is the function that gets called.

 function saveToDatabase(editableObj,column,id) {

        $(editableObj).css("background","#FFF url(loaderIcon.gif) no-repeat right");
            $.ajax({
                url: "saveedit.php",
                type: "POST",
                data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
                success: function(data){
                    $(editableObj).css("background","#FDFDFD");
                }  
            });
      }

And here is the PHP.

 <?php
require_once "dbConnectDtls.php";

    $result = mysql_query("UPDATE NetLog set " . $_POST["column"] . " = '".$_POST["editval"]."' WHERE  recordID=".$_POST["id"]);
    echo $result;

 ?>

When I tab from this cell to the next the only thing that gets executed is the .gif. The MySQL does not get updated, what am I doing wrong?

Thanks in advance for not treating me like a dummy, but helping me learn.

Followup to suggestions:

I'm afraid I'm making no headway on this. Is anyone willing to actually write a working example that I can follow?

For a newcomer there are many things you should take care in your script:

  1. First you have to avoid the insertion of $_POST values directly into a query as it may lead to sql injection problems.
  2. You should use PDO or MySQLi to perform the query for the same paranoidal reasons.
  3. You should be consistent. Why use .innerhtml when you are using JQuery? You could use $(editableObj).html()
  4. You don't show any javascript errors: Are you viewing the console? Try right clicking in the body of the page and selecting "inspect element" Then click on the "console" tab of the frame that appears.
  5. Also you are not printing the "data" variable that gets returned to see if is the expected result in server. You could do it with:

    console.log(data);

Other than that everything looks good in your script ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM