Writing JSON to a file - javascript

I wont create a JSON file and save this with a php script. I got this error message (Firefox)
NS_ERROR_XPC_JSOBJECT_HAS_NO_FUNCTION_NAMED: JavaScript component does not have a method named: "available"'JavaScript component does not have a method named: "available"' when calling method: [nsIInputStream::available]
When i use Chrome I didn't get the error message but it doesn't work too.
JavaScript:
var jsonString = '{ "foo": 1, "bar": { "baz" : 1 } }';
var data = JSON.parse( jsonString );
var xhr = new XMLHttpRequest();
xhr.open('POST', './php/upload.php', true);
xhr.send(data);
PHP:
$dateiname = "test12345.json";
if (isset($_POST) && count($_GET)==0) {
$jsonObj = $_POST;
$fh = fopen($dateiname, 'w');
$input = json_encode($jsonObj);
fwrite($fh, $input);
fclose($fh);
}

The Javascript should use:
xhr.send(jsonString);
because the data being sent must be a string, not an object.
In PHP, to read the raw post data, you should use:
$rawjson = file_get_contents("php://stdin");
$jsonObj = json_decode($rawjson);
$_POST can only be used for form data that's formatted using URL-encoding or multipart/form-data encoding.

Related

Output PHP already encode to json, and send to javascript to be json, not working

I'm do output with json_encode to sending to javascript, with this code.
<?php
include "Connection.php";
$syntax_query = "select * from product";
$thisExecuter = mysqli_query($conn, $syntax_query);
$result = array();
while($row = mysqli_fetch_assoc($thisExecuter)){
array_push(
$result,
array(
"id" => $row["product_id"],
"name" => $row["product_name"]
)
);
}
echo json_encode($result);
?>
so output show like this,
[{"id":"121353568","name":"Baju Casual - Black"},{"id":"556903232","name":"Tas LV - Red"},{"id":"795953280","name":"Sword - Wood"},{"id":"834032960","name":"Scooter - Iron Plate"}]
and code javascript like this
function showHint() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
var obj = this.responseText;
document.getElementById("txtHint").innerHTML = obj.id;
}
xmlhttp.open("GET", "Download.php");
xmlhttp.send();
}
so obj.id its not working, output show undifined.
I use ajax calls when I want to call a Php file and get a response from the same as below to try once that as I have shown. Before moving with Ajax you must need jquery to be imported into the calling file.
If Jquery is imported then ignore the steps
Here are steps,
Go to the link https://code.jquery.com/jquery-3.6.0.min.js copy whole content (use ctl+A to select whole content and ctl+C to copy)
Open a new file in the current project folder and paste the copied content (use ctl+V to paste) save it as 'jquery-3.6.0.min.js'
Import the js file in the HTML file in script tag as shown '
Now, this is the ajax example to call the PHP file and to get a response
function showHint() {
//since you have used GET method I have used here GET but You can use POST also here
$.ajax({
url: 'Download.php',
type: 'get',
//if any value you want to pass then uncomment below line
// data: {'name_to_pass':'value'},
//the variable can be accessed in the php file by 'name to pass' under $_GET['name_to_pass'] or $_POST['name_to_pass'] based on type
success: function(res)
{
// open DevTool console to see results
console.log(JSON.parse(res));
}
});
}
Hope this will help you out, thank you
Maybe you need a JSON.parse in the response, something like JSON.parse(this.responseText).
And also I can see the result is an Array so you will need to iterate obj
obj.forEach(item => {
document.getElement("txtHint").innerHTML = item.id;
});
you should define the response type as json
header('Content-Type: application/json; charset=utf-8');
echo json_encode($result);
function showHint() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
**var obj = this.responseText;**
document.getElementById("txtHint").innerHTML = obj.id;
}
xmlhttp.open("GET", "Download.php");
xmlhttp.send();
}
When you get the responseText it's text, not an object.
var obj = this.responseText; should be let obj = JSON.parse(this.responseText);
Then you can access obj.id as a property.

XMLHttpRequest Posting empty body

When I try to post some data to my backend API service I use the XMLHttpRequest object, but when I try to send the data with ajax.send it sent nothing to the server
Code snipper:
ajax = new XMLHttpRequest();
ajax.open("POST", "https://someapi.com",true);
ajax.send({
name: "Name",
phone: "123468375698563897569575863"
});
ajax.onreadystatechange = function(){
if(ajax.readyState==4){
JSONback = JSON.parse(ajax.response);
console.log(JSONback);
}
};
You need to:
Say you are sending JSON
Convert your JavaScript data structure into JSON
Such:
var data = {
name: "Name",
phone: "123468375698563897569575863"
};
var json = JSON.stringify(data);
var ajax = new XMLHttpRequest();
ajax.open("POST", "https://balbalbal.com", true);
ajax.setRequestHeader("Content-Type", "application/json");
ajax.send(json);
You cannot directly send a JS object over the wire.
You need to convert it to a string first, just like you need to parse it when you're getting it back.
ajax = new XMLHttpRequest();
ajax.open("POST", "https://balbalbal.com", true);
ajax.send(
JSON.stringify({
name: "Name",
phone: "123468375698563897569575863"
})
);
ajax.onreadystatechange = function(){
if(ajax.readyState==4){
JSONback = JSON.parse(ajax.response);
console.log(JSONback);
}
};
The simplest PHP test code on the server side would be:
<?php
echo file_get_contents('php://input');
?>
And here is a slightly more advanced example that will decode it, add a new field and send it back:
<?php
$json = file_get_contents('php://input');
$object = json_decode($json);
$object->id = 123;
echo json_encode($object);
?>

AngularJS: Receiving posted data while file uploading

My current scenario is: I've doing nesting repetition like follow:
$scope.uploadPic = function(file)
{
alert($scope.taskdetails.id); //task_id e.g 21
alert($rootScope.job_id); //job_id e.g 12
file.upload = Upload.upload(
{
url: 'http://localhost/mobile-data/upload_file.php',
data: {
file: file,
task_id: $scope.taskdetails.id,
job_id: $rootScope.job_id
},
});
file.upload.then(function (response) {
$timeout(function () {
file.result = response.data;
});
}, function (response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
// Math.min is to fix IE which reports 200% sometimes
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
}
but on my upload_file.php i can't receive the values for:
task_id: $scope.taskdetails.id,
job_id: $rootScope.job_id
in console.log they are working fine. but on server side it is not receiving.
here is code of my upload_file.php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('content-type: application/json; charset=utf-8');
$_POST = json_decode(file_get_contents('php://input'), true);
$task_id = $_POST["task_id"];
$file = $_FILES["file"];
$job_id = $_POST["job_id"];
var_dump($task_id);
var_dump($job_id);
but on var_dump it only print null. Help me to receive the values correctly..
Can you verify what is actually being sent towards the server? (You can do this using the F12 development tools in most browsers.)
What is the type of data.file? When looking at your php code, I assume you're sending a json object to the server, so I would guess the browser fails to serialize file into a json object, and ends up sending an empty request to the server.
To fix this, you could read the file as base64 data so that you can send it along as a string in the json data object:
var data = {
file: '',
task_id: $scope.taskdetails.id,
job_id: $rootScope.job_id
};
if($window.FileReader) {
var reader = new FileReader();
reader.onloadend = function() {
data.file = reader.result;
$http.post('http://localhost/mobile-data/upload_file.php', data);
}
reader.readAsDataURL(file);
}
The file will then be sent as a string formatted as data:image/png;base64,... to the server (you can see this in the F12 tools).
Arrived in php, this base64 string needs to be decoded to get back the file:
$_POST = json_decode(file_get_contents('php://input'), true);
$task_id = $_POST['task_id'];
$job_id = $_POST['job_id'];
if(isset($_POST['file']) && ($_POST['file'] != NULL)
&& preg_match('/data:([^;]*);base64,(.*)/', $_POST['file'], $matches)) {
if($matches && (count($matches) > 2)) {
$datatype = $matches[1];
$file = base64_decode($matches[2]);
}
}
Note, $_FILES won't work when you're sending your data as a json object to the server.
EDIT: just noticed you're using ng-file-upload? Then the data does not get sent as a json object, but as the usual form urlencoded data. In that case you shouldn't have this line in your php code:
$_POST = json_decode(file_get_contents('php://input'), true);
And to send the data in javascript:
Upload.upload({
url: 'http://localhost/mobile-data/upload_file.php',
method: 'POST',
file: file,
sendFieldsAs: 'form',
fields: {
task_id: $scope.taskdetails.id,
job_id: $rootScope.job_id
}
})

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);
}

how do I access the object the object i sent to the server file

//Sent an ajax http post request to a php file on the server, the post //request is a simple object.
var xhr = new XMLHttpRequest();
var person = {
"firstName" : "Adebowale",
"lastName" : "Johnson",
"ago" : 43
}
xhr.open("POST","phfile.php",true);
xhr.setRequestHeader("Content-type","application/x-www-form- urlencoded");
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
var status = xhr.status;
if((status >= 200) && (status < 300) || (status === 304)) {
alert(xhr.responseText);
}
}
};
xhr.send(JSON.stringify(person));
//if I do alert(xhr.responseText);
//I get object{} from the browser.
//On the server, using php, how do I access the object, if I do echo or //print_r, I get the empty object --- object{} with none of the properties.
//As you can tell from the tone of my question, am still very new to all //these, am just trying to learn please.
//on my phfile.php, I set up the following php code...
<?php
print_r
//How do I access the object I sent to this file please
?>
I dont see the need for JSON.stringify(person) in your AJAX request, since all the keys of the Object are already in strings.
Since you are using POST method, you can directly access the object like
print_r ($_POST['person']);
You can read raw POST data using STDIN:
$post_data = fopen("php://input", "r");
$json = fgets($post_data);
$object = json_decode($json);
$firstName = $object->firstName;
$lastName = $object->lastName;
$age = $object->age;
You could simplify all of this by just passing the data as URL-encoded form fields:
xhr.send('firstName=' + encodeURIComponent(person.firstName) + '&lastName=' + encodeURIComponent(person.lastName) + '&ago=' + encodeURIComponent(person.ago);
Then you can just access them as $_POST['firstName'], etc. in PHP.

Categories