在数据库中创建新数据

It's my first time tryng to use AJAX to send data to php, and i think im doing something wrong because i cant see any new data in mysql, here is what i tried.

This script calls ajax by clicking img:

$s .= "
\t<td>";
$canEdit = getPermission('tasks', 'edit', $a['task_id']);
$canViewLog = getPermission('task_log', 'view', $a['task_id']);
if ($canEdit) {
    $s .= ("
\t\t".'<a href="#">'
           . "
\t\t\t".'<img src="./images/icons/tick.png" alt="' . $AppUI->_('Check') 
           . '" border="0" width="12" height="12" onclick="javascript:insertData()" />' . "
\t\t</a>");
}
$s .= "
\t</td>";
$currentTasken=$a['task_id'];
$currentUser=$AppUI->user_id;

This is my ajax function which sends data to php file:

?>
<script type="text/javascript">

    function insertData()
    {
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.open("POST","datafile.php",true);
xmlhttp.send("<?php echo $currentUser; ?>");
xmlhttp.send("<?php echo $currentTasken; ?>")
    }

</script>

And this is PHP file which receives data from AJAX:

<?php
$currentUser = $_POST['$currentUser'];
$currentTasken = $_POST['$currentTasken'];
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
if(!$con)
    die('Could not connectzzz: ' . mysql_error());
mysql_select_db("foxi" , $con) or die ("could not load the database" . mysql_error());

$check = mysql_query("SELECT * FROM dotp_task_log");
$numrows = mysql_num_rows($check);
if($numrows == 0)
{
    $pass = md5($pass);

        $ins = mysql_query("INSERT INTO dotp_task_log (`task_log_creator`,`task_log_Task`) VALUES ('$currentUser' , '$currentTasken')" ) ;

   if($ins)
        die("Succesfully Created Log!");

    else
        die("ERROR");

}
else
{
    die("Log already exists!");
}

?>

Change as below :

<?php
$currentUser = $_POST['currentUser'];
$currentTasken = $_POST['currentTasken'];
$con = mysql_connect("localhost", "root", "") or die(mysql_error());
if(!$con)
    die('Could not connectzzz: ' . mysql_error());
mysql_select_db("foxi" , $con) or die ("could not load the database" . mysql_error());

$check = mysql_query("SELECT * FROM dotp_task_log");
$numrows = mysql_num_rows($check);
if($numrows == 0)
{
    $pass = md5($pass);

        $ins = mysql_query("INSERT INTO dotp_task_log (`task_log_creator`,`task_log_Task`) VALUES ('$currentUser' , '$currentTasken')" ) ;

   if($ins)
        die("Succesfully Created Log!");

    else
        die("ERROR");

}
else
{
    die("Log already exists!");
}

?>

Also your script to :

    <script type="text/javascript">

    function insertData()
    {
    if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.open("POST","datafile.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("currentUser=<?php echo $currentUser; ?>&currentTasken=<?php echo $currentTasken; ?>");
    }
    </script>

Working with ajax needs diferent way to thinking. I`ll give you some concepts (if you don't have yet) that will help you not only solve this problem but future problems too and save time:

  • After you write server side and client side logic, you have to test it separately. so, test first the server side (php part): HOW? make a simple sily static form just for post data to your server side logic to test if it's saving data correctly in database and returing expeted data.

  • After testing your server side, you have sure that if your application it's not working, the problem certainly is on the client side. So, we need to test it. Do you already know how to use Browser's console? In Firefox MacOS is [Command]+[Option]+[k] in Windows should be [ctrl]+[shift]+[k] it will open on the bottom of the browser, you should mark [network] to keep logging network requests, If your client side is working, you can see the page you're requesting by ajax and it's http status code (should be 200).

  • If client side is able to call server side through ajax and you're sure it's doing because you see the post request on the browser's console but still have not saving data properly on database, maybe you have a problem on the data is sending, or it's not sending by ajax. You can test it on the browser's log too, click on the page shown in log with right button and mark the option, maybe in english will be writen as: "Store request/response content" (my browser is in portuguese). after you mark this option, make a request again and click on the requested page with left button. You will see all headers and data you sent to server side through ajax. so, check it if is nothing wrong

This is all. But, consider using jQuery, it's not so hard to understand and it's ajax way to work is more uncomplicated. look at this sample:

var request = $.ajax({
  url: "script.php",
  method: "POST",
  data:$('#form-id').serialize(), // gets all form fields serialized creating a string fieldName1=value1&fieldName2=value2...
  dataType: "html"
}).done(function( msg ) { // after it's done
  $( "#log" ).html( msg );
  alert(msg)
}).fail(function( jqXHR, textStatus ) {
  alert( "Request failed: " + textStatus );
});

by the way, if you have to echo some php value on any part of your html including javascript parts as you did in:

xmlhttp.send("$currentUser");
xmlhttp.send("$currentTasken");

to get variable values, you should echo it as:

xmlhttp.send("<?=$currentUser?>");
xmlhttp.send("<?=$currentTasken?>");

good luck!