JavaScript POST request being sent as GET - javascript

I contacted GoDaddy about this, in case it is something on their end, but they couldn't really help.
I'm trying to send a contact form via JSON in a xmlhttprequest, and I'm sending it via a POST request. Unfortunately, and this is something that wasn't happening on another hosting service, it is being received as a get request.
Here is my js code, and what Chrome is displaying after sending it:
code:
function SendJson(values, type){
var xhr = new XMLHttpRequest();
var url = 'http://www.klemequestrianestates.com/processes/mail_form.php';
var data = JSON.stringify(values);
console.log(data);
xhr.open('POST', url);
xhr.setRequestHeader('Form-Type', type);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(data);
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
//success confirmation
}
};
}
Where Values is a js object, and type is either 'sell' or 'buy' (the form has 2 different types of clients that might use it, and sellers and buyers have different fields.
Chrome Debugger:
Here is the PHP file:
<?php
header('Access-Control-Allow-Headers: *');
header("Access-Control-Allow-Methods: POST, GET");
$data_type = $_SERVER['HTTP_FORM_TYPE'];
$raw_JSON = file_get_contents('php://input');
$converted_JSON = json_decode($raw_JSON);
echo var_dump($converted_JSON);
$type = $_SERVER['REQUEST_METHOD'];
echo var_dump($type);
if($data_type === 'sell'){
$first_name = $converted_JSON->div_00;
$last_name = $converted_JSON->div_01;
$phone_num = $converted_JSON->div_02;
$email = $converted_JSON->div_03;
$street = $converted_JSON->div_04;
$city = $converted_JSON->div_05;
$state = $converted_JSON->div_06;
$zip = $converted_JSON->div_07;
$option = $converted_JSON->div_08;
$message = $converted_JSON->div_09;
$to = 'contact#joshualyness.com';
$subject = $first_name.' '.$last_name.', '.$option;
$body = 'From: '.$email.PHP_EOL.PHP_EOL.'Phone Number: '.$phone_num.PHP_EOL.PHP_EOL.'Address: '. $street.PHP_EOL.$city.PHP_EOL.$state.PHP_EOL.$zip.PHP_EOL.PHP_EOL.'Message: '.$details;
mail($to, $subject, $body);
}
Here is the var dump contents:
Any ideas why this is happening? If you need any more details, drop a comment and I'll see what I can do. I know it's a bit of a weird question, I wouldn't be bothering the community if I didn't have any other ideas.
Thanks.

Related

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.

XMLHttpRequest action after success

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

Ajax. Sending data to php file

Good day, I'm trying to use Ajax in my web application. But I have a little problem with it. I try to control a form if some username has already been registered or not. But my JavaScript seem does not send $_POST value to PHP. And responses that user in not defined on the line where I have $_POST['user'].
Here what I have.
PHP:
<?php
$opt = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8');
$dsn ='mysql:dbname=someone;host=127.0.0.1;charset=utf8';
$user='someone';
$pswd='aaa';
$dbh = new PDO($dsn, $user, $pswd, $opt);
$query="SELECT 1 FROM users WHERE username = :username";
$query_p=array(':username' => $_POST['user']);
try
{
$statment = $dbh->prepare($query);
$result = $statment->execute($query_p);
}catch(PDOException $e)
{
echo "Can't run query: " . $e->getMessage();
}
$row = $statment->fetch();
if($row){
return 0;
}else {
return 1;
}
?>
So it opens a connection to database and runs a query
JavaScript:
function checkUser(e){
var state1 = document.getElementById("alert_text");
var u = document.getElementById("user").value;
if(u != ""){
state1.innerHTML = 'processing...';
var request = new XMLHttpRequest();
request.open("POST", "validation.php", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var result=request.responseText;
alert(result);
if(result==1){
state1.innerHTML="OK";
}else{
state1.innerHTML="Alredy exists!";
}
}
};
request.send(u);
var slova = request.responseText;
}
}
document.getElementById("user").addEventListener("blur",checkUser,false );
So technically it is ajax.
HTML:
<form id="check" name="signUp" method="post">
<p class="alert_text"></p>
<label for="user">Username:</label><br />
<input id="user" name="user" type="text" ><br />
</form>
I don't really see what's the problem...
You're not passing the username into the PHP script. Your PHP is looking for a POST variable, $_POST['user'] – in your JavaScript you make a GET request, so the PHP script has nothing to look up.
Based on the edited question: You are not sending any key-value pairs to the server, just a single value.
You need to change:
var u = document.getElementById("user").value;
to:
var u = 'user=' + encodeURIComponent(document.getElementById("user").value);
And then later on the pair will be sent correctly:
request.send(u); // sends a single key-value pair
Note that I have just added the encodeURIComponent function to make sure the value gets encoded correctly.

ajax json send an image and other data to a remote server

I have a problem that I can not solve (it is probably also your case if you read this).
I would like to send JSON data to a remote server via AJAX. This data contains an image and a string:
{
"question": "Your SquareOff Question",
"photo" : "Your photo" // optional
}
I need to send this JSON to "www.so-staging.herokuapp.com/api/v1/squareoffs?auth_token=qSJPySVk5yMsaAVE6mSu" where "qSJPySVk5yMsaAVE6mSu" is a token that I had previously ask for it and store in the $_SESSION, in a php side.
So I need to send this information to my php page before send it to the remote server. And here is my problem. I can receive the image in my php page, but not re-send it to the remote server.
I show you my code.
On the Html side, nothing special:
On the javascript page:
I don't know and to send the image and the string in the same time so. (if you have a hint, it would be with pleasure but it is not my mane problem).
function upload_photo(){
var photo = document.getElementById('photo');
/* Create a FormData instance */
var formData = new FormData();
/* Add the file */
formData.append('photo', photo.files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", 'create_square.php');
xhr.send(formData);
/* Check the response status */
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && client.status == 200){
create_square_xhr();
}
}
}
function create_square_xhr(){
var xhr = new XMLHttpRequest();
xhr.open('POST', 'create_square.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && client.status == 200){
// response is a iframe who display my question and my image if I have
// send one. I display it.
}
};
xhr.send('question=' + document.getElementById('question').value;
}
upload_photo();
And on my php page (create_square.php):
if(isset($_SESSION['token']) && isset($_POST['question']) && isset($_FILES['photo'])){
$url = 'https://so-staging.herokuapp.com/api/v1/squareoffs?auth_token=' . $token;
$data = array('question' => $_POST['question'], 'photo' => $_FILES['photo']);
$data = json_encode($data);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-Type: application/json\r\n" .
"Accept: application/json\r\n",
'method' => 'POST',
'content' => $data
)
);
$context = stream_context_create($options);
$result = file_get_contents($url, false, $context);
echo &result;
}
The response is an iframe who dispay my question and my photo if I have send one.
But when I execute this code, there is no image displayed.
I think the probleme is on the php page because I recive the $_FILES['photo'].
If you have any suggestion, I will be grateful. Thank you!
I would suggest adding a check for errors by checking: $_FILES["photo"]["error"], which may tell you if there is an issue with the photo upload.
You also have to remember that when uploading photos with PHP that it is uploaded with a randomly generated name that you typically need to move to the final location before you do anything else with it.
This is typically what you need to do in order to have access to the photo once it has been uploaded.
if (file_exists("upload/" . $_FILES["photo"]["name"])) {
echo $_FILES["photo"]["name"] . " already exists. ";
} else {
move_uploaded_file($_FILES["photo"]["tmp_name"],
"upload/" . $_FILES["photo"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["photo"]["name"];
}

AJAX not passing variable to PHP for MySQL query

I am trying to get the below AJAX script to pass a dropdown ID to PHP to run a query on, however it doesnt appear that the variable is actually being passed. When I hardcode the PHP file the query runs correctly, but when I try to do it dynamically the query returns "undefined" or nothing at all.
AJAX code
function ajax_post(){
var request = new XMLHttpRequest();
var id = document.getElementById("editorginfo").value;
alert (id);
request.open("POST", "parse.php", true);
request.setRequestHeader("Content-Type", "x-www-form-urlencoded");
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200) {
var return_data = request.responseText;
alert (return_data);
document.getElementById("orgeditname").value = return_data;
document.getElementById("orgeditphone").value = return_data;
}
}
request.send("id="+id);
}
PHP Parse Code
<?php
include_once('../php_includes/db_connect.php');
$searchid = $_POST['id'];
//$searchid = 1;
$sql = 'SELECT * FROM orginfo WHERE id = $searchid';
$user_query = mysqli_query($db_connect, $sql) or die("Error: ".mysqli_error($db_connect));
while ($row = mysqli_fetch_array($user_query, MYSQLI_ASSOC)) {
$orgid = $row["id"];
$orgname = $row["orgname"];
$orgphone = $row["orgphone"];
echo $orgname, $orgphone;
}
?>
Not really sure where the information is getting lost. When I alert the id out it is capturing the right information, so I assume the issue is in my send portion, but I can't figure out what I'm doing wrong. Any help would be appreciated.
Thanks in advance.
Your request header is wrong. Change this line -
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
^^^^^^^^^^^^

Categories