I'm building a little web-app where I'd like the users to be able to upload files, I'm using FormData to do so, /
<input id="fileInput" type="file">
var formData = new FormData()
var request = new XMLHttpRequest();
request.onreadystatechange = function () {window.resp = this}
request.open("POST", "upload.php");
request.send(formData);
But I have no idea how to get the data using PHP.
I know you can normally do
$_POST["KEY"]
But in this case I'm not using a key because the data isn't a string.
I've searched for quite some time now and came across the following things
print_r($_POST) // returned an empty array
var_dump($_POST) // returned an empty array
I don't know what I'm doing wrong and it's probably just some thing you have to know, but I can't seem to figure it out. Thanks in advance.
EDIT
Turns out you can just get the file using the
$_FILES
global, huge thanks to #tobias K!
SOURCES:
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
If you are posting raw data, you can get it in PHP by
$rawData = file_get_contents("php://input");
Related
I am fairly new to working with APIs in Javascript and I am working on a quiz app project that makes use of a quiz question generator API. I have figured out how to display the API response in the console to view the Javascript object? string? (I have used typeof on the response which tells me it is a string), and now I am trying to figure out how to extrapolate information such as questions, correct answer, and incorrect answer(also an array) from the value for result that seems to be an array of objects. Any help regarding this issue would be greatly appreciated!
var request = new XMLHttpRequest();
request.open('Get', 'MyAPIKey', true);
request.onload = function() {
console.log(request.status);
console.log(request.response);
};
Blockquote
Blockquote
request.onload = function() {
let res = JSON.parse(request.response);
console.log(typeof res);
console.log(res);
};
first you need to convert this to a JSON Object so that you can be able to work with it in your data, the very first line on this function is doing that for you. if you log the type of this on the console you will see object not string. I hope this help. thanks for asking this question, i like it because it gave me a lot of trouble while learning how to code.
I am new to both php and javascript and having trouble understanding how to communicate between the two. I have a php array and I used json_encode() to turn it into json and now I just don't know what to do from there. I have just been looking around and haven't been able to find an answer of what to do from there. Do I print it? If I do print it... how do I used javascript to grab it. I can't use the php variable name since javascript doesn't understand it. I am just not grasping this concept.
The most popular way to make a Javascript script communicate with a PHP script is via Asynchronous Javascript And XML (AJAX) requests.
In AJAX requests, your javascript code calls the PHP script needed, sending to it any required parameters. Then, your PHP script should print (echo) the result (the JSON encoded array in your case), and when it does, an event gets fired in your javascript code, which you can handle accordingly.
In Javascript, there are two main ways of performing AJAX requests:
1- Using the XMLHTTPRequest object:
In this method, we are using a Javascript XMLHTTPRequest object to send the request to our PHP script, and we handle its onload event to get the response and do something with it :
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "some_url.php?param1=123");
xmlhttp.send();
xmlhttp.onload = function() {
//here the response from the PHP script is saved in the this.responseText variable
//parsing the JSON string we got into an actual array
var myArray = JSON.parse(this.responseText);
//do something with the array
}
(note that we can also handle the object's onreadystatechange, but onload is a bit simpler to handle)
2- Using a promise (fetch):
fetch("some_url.php?param1=123")
.then(function(response) {
return response.text();
})
.then(function(data)) {
var myArray = JSON.parse(data);
//do something with the array
});
I am trying to post to a local son file which is saved within the same folder as all my code. I have done the following:
function test(){
var xmlhttp = new XMLHttpRequest(); // new HttpRequest instance
xmlhttp.open("POST", "data/people.json");
xmlhttp.setRequestHeader("Content-Type", "application/json;");
xmlhttp.send(JSON.stringify({name:"John Rambo"}));
}
The above function is run when I click on a button in my html:
<input type="button" onclick="test()">
And my son file looks like this:
{
"People": [
{"name": "tony stark"},
{"name": "iron man"}
]
}
but I keep getting a 404 not found error. is there anything that I am doing wrong?
Apologies if I missed something out if you require more information to answer the question please let me know.
Thanks in advance.
Since I can't comment because I don't have enough reputation, if you want to enter data into your json file, the best thing you can do is:
Get the file and turn the JSON into an Object.
Once you have the object, push more data into it.
Afterwards, save the file / replace it with the object containing the new and the old information.
This is just a simple work around, but as other said in comments, you can't "POST" data into the file unless you do what I've just said.
Hope it helps!
Double check the URL end point.
Should be server script file which is made to accept the request.
And try sending is Key=Value pair.
xmlhttp.send("name=John Rambo");
Hi I'm trying to use Javascript to write a chrome application that will show your last number of tweets but I'm having trouble getting the tweets. I'm a newbie to javascript but I have searched quite a bit and can't find an understandable answer to this.
From chrome and twitter I have the following code.
<script type="text/javascript">
var req = new XMLHttpRequest();
req.open(
"GET",
"https://api.twitter.com/1/statuses/user_timeline.json?
include_entities=true&include_rts=true&screen_name=twitterapi&count=3")
</script>
This GET request works but how do I use the data it returns with javascript?
The result is in the req.responseText. You can append it o your document, to see what the response is. It actually depends on what is the response. I mean maybe you need to alert the response, or show it somewhere, or put it in a condition operator and compare with something... Some basoc use:
alert(req.responseText);
document.body.innerHTML+=req.responseText;
It is somewhere in req.responseText. That is, you need to set req.onreadystatechange and once it's ready you'll have it in there.
I'm trying to POST JSON formatted data from Javascript (using Prototype) to Grails. My Javascript code is:
var JSONObject = new Object;
JSONObject.id = "23";
JSONObject.name = "Test 1";
JSONstring = JSON.stringify(JSONObject);
var url = "${createLink(controller:'testController', action:'receiveJson')}";
new Ajax.Request(url, {
method:'post',
contentType:'application/json',
parameters:JSONstring,
asynchronous:true,
onSuccess: function (req) {
sendInfoResponse(req.responseText);
}
});
and the code in my Grails controller is:
def receiveJson = {
def json = request.JSON;
}
However, the 'json' variable appears to be empty in my tests. I'd be so grateful if someone could explain what I'm doing wrong. Many thanks.
In your Ajax.Request options change
parameters:JSONstring,
to
postBody:JSONstring,
The problem with using parameters is that it URL encodes the data so that the request body ends up looking like this:
%7B%22id%22%3A%2223%22%2C%22name%22%3A%22Test%201%22%7D&_=
Instead of the desired (which is what you get with postBody):
{"id":"23","name":"Test 1"}
Good question mfloryan - I was doing the testing manually, i.e. not as part of a unit or integration test.
Thanks very much for the help hvgotcodes. I made the changes to my code as you have suggested, but unfortunately to no avail. Interestingly, if I print request.JSON I get {}, whereas if I print request.json I get null.
EDIT: By 'printing' I mean using: request.JSON.toString()
EDIT: Thank you all so much for the help. Once I'd made the final change John Wagenleitne suggested the code began working properly. I'm very grateful indeed for all your help.
I don't think you are invoking the Ajax.Request correctly. From the documentation, the parameters option:
"The parameters for the request, which will be encoded into the URL for a 'get' method, or into the request body for the other methods. This can be provided either as a URL-encoded string or as any Hash-compatible object (basically anything), with properties representing parameters."
I think you need to do something like
...
parameters: {json: JSONString}
...
and then in your controller
request.json
note the form of the parameters object literal - it tells the Prototype library to make the request key 'json' and the request value be the json string. You access the key off the request object in the controller.
EDIT -- I just realized you're javascript block is jacked up.
This:
var JSONObject = new Object;
should be something like
var JSONObject = new Object();
...
you might also be able to do just an object literal, so
var jsonObject = {};
....