0

I have a form, the form has text fields and a canvas in it that preforms as a signiture pad.

link to the form

I use ajax in order to send the form. What I have troubles doing is to confirm that the form is inserted to the database.

I think that there is a collision between the ajax and the php I use in order to insert the form data to the mysql db how can I do it?

This is the content of the js file

                var fd = new FormData(document.forms["form1"]);

                var xhr = new XMLHttpRequest();
                xhr.open('POST', 'upload_data.php', true);

                xhr.upload.onprogress = function(e) {

                    if (e.lengthComputable) {
                        var percentComplete = (e.loaded / e.total) * 100;
                        alert(percentComplete + '% uploaded');
                    }
                };


                xhr.onload = function() { 
                };


                xhr.send(fd);

This is the content of the upload_data.php file:

<?php

    require 'inc/inc.php';

    $upload_dir = "upload/";
    $img = $_POST['hidden_data'];
    $idNo = $_POST['idno'];
    $name = $_POST['fname'];
    $img = str_replace('data:image/png;base64,', '', $img);
    $img = str_replace(' ', '+', $img);
    $data = base64_decode($img);
    $file = $upload_dir . mktime() ."-" . $idNo . ".png";
    $success = file_put_contents($file, $data);
    print $success ? $file : 'Unable to save the file.';


    $suc = new Form;
    $suc->insert_data($name, $file, $idNo);
    ?>

This is the insert_data() php function content

public function insert_data($name, $file, $idNo){
            $query = $this->dbh->prepare("INSERT INTO signitures (name, file, idno) VALUES(?, ?, ?)"); 
            $query->bindparam(1, $name);
            $query->bindparam(2, $file);
            $query->bindparam(3, $idNo);



            try {

            $query->execute();
                if ($query) {
                   echo "success!! ";
                } else {
                     echo "Failure conncting db!";
                }
            }
            catch (PDOException $e) {
                die($e->getMessage());
            }
        }

I know that if $query->execute(); returns true than the data was inserted. How can I notify the user that the data was really inserted to the database? Even pass the user to a new page is an option. Actualy, redirect the user to a new page will be great!

DavSev
  • 1,005
  • 4
  • 22
  • 47
  • Possible duplicate of [how to find out if XMLHttpRequest.send() worked](https://stackoverflow.com/questions/10876123/how-to-find-out-if-xmlhttprequest-send-worked) – Carlos Alves Jorge Sep 06 '17 at 12:59
  • I don't know PHP so I can't give you implementation details, but the concept is simple. Once PHP is done querying the database, have it send a response to the client that requested insertion. You could simply use HTTP status codes, e.g. 200 if successfully inserted. Then read the response headers from JavaScript. – Daniel Lane Sep 06 '17 at 13:06

2 Answers2

2

Hi you need to add in the function insert_data on the try{ at the end} a echo of your success to send to ajax script as response so a simple.

$success['success'] = "You request just sending to the server ...";
echo json_encode($success);

In your fonction ajax

            xhr.onload = function(data) { 
                console.log(data);
                console.log(data.success);
            };

You need to adapt, this method show you how send data PHP to JS regards.

  • thank you, I tried what you suggested, for some reason the page gets refreshed after pressing the submit button and I don't get to see the data at the console. What can cause to that? – DavSev Sep 07 '17 at 05:03
  • also while checking the js file in sources tab, the run dosen't get into the `xhr.onload` block so i cant get the `console.log(data);` object data. what can cause to that? – DavSev Sep 07 '17 at 05:17
  • Why i don't use this code to do an ajax request? Because this is an old code and not Cross Browser. I suggested using ajax lib from jquery or ... for example gave you the best choice for Cross Browser ajax request. –  Sep 07 '17 at 07:24
1

You can also send the response inside a "body" key-value pair, and put the success/error indication inside the HTTP status code:

$success["body"] = "You request just sending to the server ...";
header("HTTP/1.1 200 OK", true, 200);

And receive it in js:

xhr.onload = function(data) { 
    console.log(data.status);
    console.log(data.body);
};

see: Set Response Status Code

or: http://php.net/manual/de/function.http-response-code.php

explanation of codes: https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Guntram
  • 961
  • 14
  • 19
  • 1
    Thank you. Tried it like so `try { $query->execute(); if (!$query) { echo "Failure conncting db!"; }else{ $success["body"] = "You request just sending to the server ..."; header("HTTP/1.1 200 OK", true, 200); } }` but for some reason i cant understand. the run dosen't get into the xhr.onload block so i cant get the console.log(data); object data. what can cause to that? – DavSev Sep 07 '17 at 05:30
  • Hmmm if the backend crashes, it would eventually send a status code like 500 internal server error. If the request keeps in pending state, the backend might be deadlocked in a loop or something... – Guntram Sep 07 '17 at 07:01