Accessing JSON.stringify variable in PHP - javascript

I have trouble in accessing the JSON string being sent from my client side Javascript code to my PHP code. This is what I have done until now.
var formatted;
fr.onload = function(e) {
var result = JSON.parse(e.target.result);
formatted = JSON.stringify(result, null, 2);
console.log(formatted);
//send formatted as post to write2share.php and write that in a file in share folder
xhr = new XMLHttpRequest();
var url = "write2share.php";
var nametime = gettime();
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", 'application/json; charset=UTF-8');
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var json = JSON.parse(xhr.responseText);
console.log(json.content);
}
}
var data = JSON.stringify({"content":formatted, "name": nametime});
xhr.send(data);
//GenerateShare(nametime);
}
Here formatted is a JSON string and nametime is an integer
The below is my php script
$decoded = json_decode(file_get_contents("php://input"),true);
$error = json_last_error();
var_dump($decoded);
echo $error;
The output of my $error is 0 and var_dump of $decoded is Null. Why?
Help is appreciated! Thanks

Related

AJAX send a thing and PHP receive another thing?

I am using Fabric.js canvas library, and I want to save the canvas on the server.
Converted it into data URL:
var canvasData = canvas.toDataURL();
and sent it to the server using Ajax:
let xhr = new XMLHttpRequest();
xhr.open("POST", "php/saveImg.php", true);
xhr.onload = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
let data = xhr.response;
window.open(data);
}}};
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send("canvasData=" + canvasData);
decoded the data and saved it in saveImg.php:
if(isset($_POST['canvasData'])){
$imageData = $_POST['canvasData'];
echo $imageData;
$filteredData = substr($imageData, strpos($imageData, ",") + 1);
$a = file_put_contents( "images/image1.png", base64_decode($filteredData));
}
When I look into image1.png, it is transparent with nothing in it (yet it has the right dimensions and a size of 40 KB).
When I check the value that is received in $_POST, I can see that the value of the data is deformed: some + characters have been removed and some other chars have been added.
Your POST data is not encoded properly, you can use encodeURIComponent to do this
xhr.send("canvasData=" + encodeURIComponent(canvasData));

How to save value from a "upload.js" to request it in other .js

I've tried a lot of things to save the data from "request.responseText" to my var "pdf" that is a url with any file type and then call that variable containing the url into other .js that sends a string containing the rest of the form.
Here is the upload script
let pdf;
const uploadFile = (file) => {
console.log("Uploading file...");
const API_ENDPOINT = "https://file.io";
const request = new XMLHttpRequest();
const formData = new FormData();
request.open("POST", API_ENDPOINT, true);
request.onreadystatechange = () => {
if (request.readyState === 4 && request.status === 200) {
console.log("onreadystatechange request", request.responseText);
pdf = request.responseText;
console.log("pdf", pdf);
}
};
formData.append("file", file);
request.send(formData);
};
fileInput.addEventListener("change", (event) => {
var files = event.target.files;
uploadFile(files[0]);
});
and here is the "general form" which have to recieve the data from the form and send it as a string:
let result = document.querySelector(".result");
let name = document.querySelector("#form-name1");
let email = document.querySelector("#form-email1");
let phone = document.querySelector("#form-phone1");
// Creating a XHR object
let xhr = new XMLHttpRequest();
let url ="yourapiurl";
// open a connection
xhr.open("POST", url, true);
// Set the request header i.e. which type of content you are sending
xhr.setRequestHeader("Content-Type", "application/json");
// Create a state change callback
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
// Print received data from server
result.innerHTML = this.responseText;
}
};
//Converting JSON data to string
var data = JSON.stringify({
name: name.value,
email: email.value,
phone: phone.value,
pdf,
});
console.log(data);
// Sending data with the request - not using it rn only console logs
// xhr.send(data); - not using it rn only console logs
//Clearing fields
document.getElementById("form-name1").value = "";
document.getElementById("form-email1").value = "";
document.getElementById("form-phone1").value = "";
document.getElementById("fileInput").value = "";
}
Sorry for any typo not native speaker of English and thanks if read.

AttributeError: 'NoneType' object has no attribute 'get' //500 (Internal Server Error)

this is not sending any data from crome extension,i am trying to send json string to the server with mentioned url which says none type object has been returned,
var xhr = new XMLHttpRequest();
var ur = "http://127.0.0.1:8080/animal";
var dat = {"subject":"subject"};
xhr.open("POST", ur, true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// do something with response
console.log(xhr.responseText);
}
};
xhr.send(dat);
}
};
xhr.send(dat);
You can't send an object with xhr.send(), you need to serialize it.
var dat = 'subject=subject';

cannot pass a javascript object to php via ajax

I've created a new array in javascript and I'm adding values to it indexes from a function an then passing the array to the ajaxCall function were I try to convert it to json and send it to a php file via ajax, but the variable json is allways empty. I've been reading a lot about how to send javascript objects json_encoded via ajax and looks like this is the way to do it, but obviously I haven't readed enought or there is something I've been missing. Anycase I'm newbie in javascript and any help would be apreciated.
function createArray()
{
var advancedFormVars = new Array();
advancedFormVars['checkbox1'] = document.getElementById('OfferID').value;
advancedFormVars['checkbox2'] =document.getElementById('offerName').value;
AjaxCall(advancedFormVars);
}
function AjaxCall(advancedFormVars){
var json = new Array();
json = JSON.stringify(advancedFormVars); //in debuger it shows me this as content of json variable--> [] but advancedFormVars is not empty
$.ajax({
url : 'AL_loadForm.php',
type : 'POST',
data : {
json : json
},
dataType:'json',
success : function(data) {
alert(data);
}
...
You are trying to use your array as a hash, so the values are not being set..
Instead of setting
var advancedFormVars = new Array();
Try setting
var advancedFormVars = {};
Example
JS:
var advancedFormVars = {};
advancedFormVars['checkbox1'] = 'valueA';
advancedFormVars['checkbox2'] = 'valueB';
var json = JSON.stringify(advancedFormVars);
console.log(json); //{"checkbox1":"valueA","checkbox2":"valueB"}
PHP
<?php
$json = '{"checkbox1":"valueA","checkbox2":"valueB"}';
$obj = json_decode($json);
var_dump($obj);
/*
object(stdClass)#1 (2) {
["checkbox1"]=>
string(6) "valueA"
["checkbox2"]=>
string(6) "valueB"
}
*/
?>
If all you have are two smaller arguments, I'd keep it simple and make an http get request. Encode your arguments if neccessary.
var url = "http://wherever.com/something.php?arg1=";
url += document.getElementById('OfferID').value;
url += "&arg2=" + document.getElementById('offerName').value;
httpGetAsync(url, returnMethod);
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}

Wpf webbrowser load html with javascript

I have this function in my JavaScript function:
var xhr = new XMLHttpRequest();
var url = 'url';
xhr.open('GET', url, false);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
var str = xhr.responseText;
alert(str);
var resp = JSON.parse(str);
alert('12');
if (0 == resp.ErrorCode) {
alert('13');
}
}
}
xhr.send();
The str is always :
{"ErrorCode":0,"ErrorMessage":"OK","Command":"/api/getvideoinfo/","data":[{"VideoID":"ehcVomMexkY","IsInCache":true,"IsDownloading":false,"AvailableFormats":[{"DisplayName":"720","IsHD":true,"VidEncMimeType":"video/H264","AudEndMimeType":"audio/aac","Width":1280,"Height":720,"PlaybackURL":"","IsDefaultStream":false},{"DisplayName":"360","IsHD":false,"VidEncMimeType":"video/H264","AudEndMimeType":"audio/aac","Width":640,"Height":360,"PlaybackURL":"url","IsDefaultStream":true}]}]}
And i noticed that the script never get to :
alert('12');
Any idea what can cause this?Why the json won't parse? did i need to add any library to the html?
The url is the location of the file on the server. So the url variable should be the path from where you get the data which in this case should be
var url = "/api/getvideoinfo/";

Categories