XMLHttpRequest action after success - javascript

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!

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.

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

Related

Creating a PHP session variable after successful AJAX call

I am having problems creating a PHP session following a successful AJAX call. Here is the AJAX code:
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var id = profile.getId();
var em = profile.getEmail();
var name = profile.getName();
var pic = profile.getImageUrl();
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('confirm-login').style.display = 'block';
}
};
xhttp.open("GET", "./assets/inc/profile.php?id="+id+"&e="+em+"&n="+name+"&p="+pic, true);
xhttp.send();
}
This part works perfectly. I only include it for completeness sake.
Here's the contents of profile.php
<?php
$id = $_GET["id"];
$email = $_GET["e"];
$name = $_GET["n"];
$pic = $_GET["p"];
require_once("db.php");
$result = $mysqli->query("SELECT googleid FROM user_tbl WHERE googleid = '$id' LIMIT 1");
if($result->num_rows == 0) {
$sql = "INSERT INTO user_tbl (googleid, email, fullname, pic, loc) VALUES ('$id', '$email', '$name', '$pic', '')";
if (mysqli_query($mysqli, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "" . mysqli_error($mysqli);
}
} else {
echo "already exists";
}
$mysqli->close();
session_start();
$_SESSION['gid'] = $id;
?>
All of this code works except for session_start(); and $_SESSION['gid'] = $id; when I return to another PHP page (which correctly has session_start(); at the very top of the page) the variable has not been created in profile.php
Any help as to what I'm doing wrong would be much appreicated.
You can't start a session after the script has sent output. (There should have been output to that effect; if there wasn't, try changing PHP's warnings.) The session_start() call must come before any echo call that is actually executed.
On an unrelated topic, you will want to learn how to escape your database parameters.

File is corrupted after converting

I am using recorder.js library and want to send the recorded message to my gmail account using PHPMailer. I have done everything but the only problem that I am getting is that when I send the file as an attachment and download it from my mail, it is corrupted (or whatever) and my system says "The file is unplayable". Moreover, when I check my local uploads/ folder where I am writing all the files, they are unplayable too. I don't know what seems to be the problem and I am stuck on this since past two days. Thanks in advance.
My JS call to upload.php
function sendMessage() {
var xhr = new XMLHttpRequest();
xhr.onload = function (e) {
if (this.readyState === 4) {
console.log("Server returned: ", e.target.responseText);
}
};
var fd = new FormData();
fd.append("audio_data", blob, filename);
xhr.open("POST", "upload.php", true);
xhr.send(fd);
}
and my upload.php
<?php
require "php-mailer-master/PHPMailerAutoload.php";
define('UPLOAD_DIR', 'uploads/');
$a = $_FILES['audio_data']['name'];
$a = str_replace('data:audio/wav;base64,', '', $a);
$a = str_replace(' ', '+', $a);
$data = base64_decode($a);
$file = UPLOAD_DIR . uniqid() . '.wav';
$success = file_put_contents($file, $data);
print $success ? $file : 'Unable to save the file.';
Please note that I have skipped the part of code which is actually sending mail because I believe that is irrelevant.

Canvas will not save server side PHP

I have a canvas which I need to save to a directory and store the URL in a database.
When I save the file without storing the URL in the database it works fine, and vice versa.
However, when I put the two together and specify the PHP file through AJAX, for some reason it doesn't recognise the session variable?
When I try to call the "success" on AJAX, nothing shows up. I get no response.
This could possibly be an easy fix! I think I've been staring at this code for too long.
JavaScript:
function doodleSave() {
var canvas = document.getElementById("doodle-canvas");
var canvasData = canvas.toDataURL("image/png");
$.ajax({
url:'doodleupload.php',
type:'POST',
data:{ data:canvasData },
success: function(response){
alert(response);
//echo what the server sent back...
}
});
}
PHP:
<?php
session_start();
/* AUTOMATED VARIABLES */
$url = md5(uniqid(rand(), true));
$unique_user_id = $_SESSION['unique_user_id'];
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';
$upload_dir = "images/external/doodles/";
$img = $_POST['data'];
$img = substr($img,strpos($img,",")+1);
$data = base64_decode($img);
$file = $upload_dir . $url . ".png";
$success = file_put_contents($file, $data);
echo $success ? $file : 'Unable to save the file.';
require_once 'php/connect.php';
try
{
$stmt = $pdo->prepare("INSERT INTO posts (unique_user_id, unique_post_id, nature, image_url, timestamp) VALUE (:unique_user_id, :unique_post_id, :nature, :image_url, :timestamp)");
$stmt->bindParam(":unique_user_id",$unique_user_id);
$stmt->bindParam(":unique_post_id",$unique_post_id);
$stmt->bindParam(":nature",$nature);
$stmt->bindParam(":image_url",$imageUrl);
$stmt->bindParam(":timestamp",$timestamp);
if($stmt->execute())
{
echo "File in database";
}
else
{
echo "Not in database";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
?>
Move $upload_dir at the top, as you are calling it before you initialize it.
$upload_dir = "images/external/doodles/";
$url = md5(uniqid(rand(), true));
$unique_user_id = $_SESSION['unique_user_id'];
$unique_post_id = md5(uniqid(rand(), true));
$timestamp = time();
$nature = "doodle";
$imageUrl = $upload_dir.$url.'.png';

Catch values of parameters in Php sent from angularJs

I am working first time on php. I want to pass my parameters from angularJs to a php file then those parameters are supposed to be used in INSERT query. I have used XmlHttpRequest to call php file (addsubscriber.php?par1=val1&par2=val2) through AngularJs Function (vm.addSub). Now I dont know how to catch those parameters in my php file.
AngularJs
vm.addSub = function(){
var params = "name="+vm.selectedNameAdd+"&number="+vm.selectedPhoneAdd+"&status="+vm.selectedStatusAdd;
var oReq = new XMLHttpRequest();
oReq.onload = function(){
vm.msg = JSON.parse(this.responseText);
};
oReq.open("get", "addSubscriber.php?"+params, true);
console.log("addSubscriber.php?"+params);
oReq.send();
};
});
addSubscriber.php (What have I tried so far is commented in my php file)
<?php
include('connectionString.php');
$dbObj = new connectionString();
$conn = $dbObj->getdbconnect();
// $request = json_decode( file_get_contents('php://input') );
// $name -> name;
// $number -> number;
// $status -> status;
// $name = filter_input( INPUT_GET, 'name', FILTER_SANITIZE_URL ); // $_GET['name'];
// $number = filter_input( INPUT_GET, 'number', FILTER_SANITIZE_URL ); // $_GET['number'];
// $status = filter_input( INPUT_GET, 'status', FILTER_SANITIZE_URL ); // $_GET['status'];
// parse_str($_SERVER['QUERY_STRING']);
$date = date("Y-m-d");
$query = "INSERT INTO SUBSCRIBERS(subscriber_name,subscriber_number,created_on,is_active) VALUES($name,$number,$date,$status)";
if(mysqli_query($GLOBALS['conn'], $query)){
$msg = "Inserted Successfully";
}
else{
$msg = "Insertion Failed";
}
print json_encode($msg);
Actually the problem was with Query
$query = "INSERT INTO SUBSCRIBERS(subscriber_name,subscriber_number,created_on,is_active) VALUES('$name','$number','$date','$status')";
Note the single quotes in VALUES part.
After adding single quotes it worked as desired.

Saving (with JS Request) and reading (with PHP) XML in MySQL

I'm trying to save some xml content (that I receive as plain text) into my site's database. I read about saving XML content and someone suggested it is not a good idea to save XML in a text field (database), so I decided to do it in a blob. The thing is I'm doing it via CORS, through javascript this way:
var formData = new FormData();
formData.append("name", 'myNewFile');
// THE XML CONTENT
var content = '<a id="a"><b id="b">hey!</b></a>';
var blob = new Blob([content], { type: "text/xml"});
formData.append("file", blob);
var request = new XMLHttpRequest();
request.open("POST", url);
request.onreadystatechange = function() {
if(request.readyState == 4 && request.status == 200) {
resultsContainer.innerHTML = (request.responseText );
}
}
request.send(formData);
On the server, I store it with:
$name = $_POST['name'];
$file = $_POST['file'];
$sql = "INSERT INTO ProfileFiles (name, file)
VALUES ('$name', '$file')";
It seemed to work, the entry was created in the database but I can't see what's inside the BLOB field. So, I tried to read that from server, using PHP, but I'm retrieving just "0" in the file field.
$sql = "SELECT datetime, name, file FROM ProfileFiles";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "Timestamp: " . $row["datetime"]."<br>";
echo "Name: " . $row["name"]. "<br>";
echo "Content: " + $row["file"];
echo "<br>----------<br>";
}
}
else
{
echo "Nothing";
}
What am I missing? Thanks in advance! I never worked with PHP.
The reason why you don't get anything in $_POST['file'], is that you are sending it as a file. Files that are posted are in the superglobal variable $_FILES not $_POST. $_FILES['file'] will contain an array
array('name' => '...', 'tmp_name' => '...', 'type' => '...', 'size' => '...');
The content will be saved to a temporary file whose name is stored in $_FILES['file']['tmp_name']
You see, you really go astray here... What you have to do is to send the XML data as a POST variable and not a file. When doing this, you can save the data to the database like you tried it, but with prepared statements, it will be something like (assuming you are using mysqli
$name = $_POST['name'];
$file = $_POST['file'];
$sql = "INSERT INTO ProfileFiles (name, file)
VALUES (?, ?)";
$stmt = $mysqli->stmt_init();
$stmt->prepare($sql);
$stmt->bind_param("ss", $name, $file);
$stmt->execute();
$stmt->bind_result($result);
$stmt->fetch();
The point of using a prepared statement is this :
If the file contains a ', you get an error in the query. Also your code is vulnerable to sql injection. You need to escape the strings in the query.
I never used mysqli myself, and the code I gave looks a bit clumsy, so here's an alternative :
$sql = "INSERT INTO ProfileFiles (name, file)
VALUES ('". mysqli_real_escape_string($name)."', '".mysqli_real_escape_string($file) ."')";

Categories