简体   繁体   English

带有xmlhttpRequest的html5 Canvas签名板错误

[英]html5 Canvas signature pad error with xmlhttpRequest

I am following this post: Can't get html5 Canvas signature pad to submit to database , and is a great signature script, but I already have a error when I tried to save it into DB...the console give me this error: 我正在关注此帖子: 无法将html5 Canvas签名板提交到数据库 ,这是一个很棒的签名脚本,但是当我尝试将其保存到数据库中时我已经遇到了一个错误...控制台给了我这个错误:

Error: Failed to construct 'XMLHttpRequest': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

Can you help me with this part of javascript to fix it: 您能帮我解决这部分javascript问题吗?

$("#saveSig").click(function saveSig() {
    //encode URI
    var sigData = encodeURIComponent(canvas.toDataURL("image/png"));
    $("#imgData").html('Thank you! Your signature was saved');
    var ajax = XMLHttpRequest();
    ajax.open("POST", 'sign/signature.php');
    ajax.setRequestHeader('Content-Type', 'application/upload');
    ajax.send(sigData);
    $('#debug').html(sigData);
});

I already found the answer! 我已经找到答案了!

this is the hidden input in the canvas: 这是画布中的隐藏输入:

<input type="hidden" value="<?php echo $user_id; ?>" name="user_id" id="user_id" />

here is the code which will run this script: 这是将运行此脚本的代码:

$("#saveSig").click(function saveSig() {
    //encode URI
    var sigData = canvas.toDataURL("image/png");
    var user_id = $("#user_id").val();  //here the id is showed, like 1, 2, etc
    $("#firm").html("Thank you! Your signature was saved with the id: "+user_id);
    $("#debug").html(sigData);
    var ajax = new XMLHttpRequest(); 
    ajax.open("POST", "sign/signature.php",false);
ajax.onreadystatechange = function() {
    console.log(ajax.responseText);
}
ajax.setRequestHeader("Content-Type", "application/upload");
ajax.send("imgData="+sigData);
   // ajax.send("user_id"+user_id);  //here give me this error: InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.
});

DB connection: 数据库连接:

<?php
  if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
  {
  $session_id = $_SERVER['REMOTE_ADDR'];
  // Get the data
  $imageData=$GLOBALS['HTTP_RAW_POST_DATA'];

//$user_id = (isset($_POST['user_id'])) ? $_POST['user_id'] : ""; //not works
//$user_id = $_POST['userId']; //not works

$user_id = '1'; // when I put a number the id is saved

// process your sigData here (e.g. save it in the database together with the user_id)

  // Remove the headers (data:,) part.
  // A real application should use them according to needs such as to check image type
  $filteredData=substr($imageData, strpos($imageData, ",")+1);

  // Need to decode before saving since the data we received is already base64 encoded
  $unencodedData=base64_decode($filteredData);

  //echo "unencodedData".$unencodedData;
  $imageName = "sign_" . rand(5,1000) . rand(1, 10) . rand(10000, 150000) . rand(1500, 100000000) . ".png";
  //Set the absolute path to your folder (i.e. /usr/home/your-domain/your-folder/
  $filepath = "../signature/" . $imageName;

  $fp = fopen("$filepath", 'wb' );
  fwrite( $fp, $unencodedData);
  fclose( $fp );

  //Connect to a mySQL database and store the user's information so you can link to it later

include_once("CONN/configs.php");
        try{
    $statement = $conn->prepare("INSERT INTO SIGNATURE (`session`, `user_id`, `signature`) VALUES (?, ?, ?)");
    if ($statement->execute(array($session_id, $user_id, $imageName)));

        echo '<div class="alert alert-success">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times</button>
        Firma con id: '.$user_id.' guardada correctamente.</div>';
    }
    catch (Exception $e) 
    {
        echo '<div class="alert alert-danger">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times</button>
        Error al tratar de guardar la firma.</div>';
        die;
    }
}
?>

I hope someone will need this. 我希望有人会需要这个。

Best regards! 最好的祝福!

The error message says what you should do: you should use the 'new' operator to construct 'XMLHttpRequest'. 该错误消息说明了您应该做什么:您应该使用“ new”运算符来构造“ XMLHttpRequest”。

Where you create your ajax object, change var ajax = XMLHttpRequest(); 在创建ajax对象的地方,更改var ajax = XMLHttpRequest(); to var ajax = new XMLHttpRequest(); var ajax = new XMLHttpRequest();

Since you are using jquery anyway, you can use jquerys ajax method to make the ajax request instead of dealing with the browser specifics of XMLHttpRequest . 由于无论如何都在使用jquery,因此可以使用jquerys ajax方法发出ajax请求,而不用处理XMLHttpRequest浏览器细节

$("#saveSig").click(function saveSig() {
  //encode URI
  var sigData = encodeURIComponent(canvas.toDataURL("image/png"));
  $.ajax({
    type: "POST",
    url: 'sign/signature.php',
    contentType: 'application/upload',
    data: sigData,
    success: function () {
      $("#imgData").html('Thank you! Your signature was saved');     
    }
  });
  $('#debug').html(sigData);
});

Update In response to you comments: 更新以回应您的评论:

You must understand, that this javascript and the ... click(function saveSig() {...} is executed in the browser. So you shouldn't put any php in there, because the php must be executed by the webserver. When you click on the "#saveSig" element, the browser executes this function and with the call of $.ajax(...) it sends a new HTTP POST request to the webserver in the background calling the url 'sign/signature.php'. The response data to that request is available to the success function. Here follows an example of how the webserver (php) and the browser (javascript) could work together. 您必须了解,此javascript和... click(function saveSig() {...}是在浏览器中执行的。因此,您不应在其中放置任何php,因为该php必须由网络服务器执行。当您单击“ #saveSig”元素时,浏览器将执行此功能,并调用$.ajax(...)它将在后台将新的HTTP POST请求发送到Web服务器,并调用url'sign / signature。 php'。该请求的响应数据可用于成功功能,以下是一个示例,说明了网络服务器(php)和浏览器(javascript)如何协同工作。

sign/signature.php sign / signature.php

<?php
// read the request data:
$sigData = (isset($_POST['data'])) ? $_POST['data'] : "";
$user_id = (isset($_POST['UserId'])) ? $_POST['userId'] : "";

// process your sigData here (e.g. save it in the database together with the user_id)

//generate the response:
echo "Successfully saved signature for user id: ".$user_id.".";
?>

javascript: javascript:

$("#saveSig").click(function saveSig() {
  //encode URI
  var sigData = encodeURIComponent(canvas.toDataURL("image/png"));
  $.ajax({
    type: "POST",
    url: 'sign/signature.php',
    contentType: 'application/upload',
    data: {
      data: sigData,
      user_id: $('#user_id').val() // this get's the value from the hidden user_id input
    },
    success: function (responseData) {
      $("#imgData").html('Thank you!' + responseData);
    }
  });
  $('#debug').html(sigData);
});

Maybe the AJAX Introduction by w3schools is interesting to you 也许w3schools的AJAX简介对您来说很有趣

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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