Issue accessing fileData - javascript

I'm trying to upload an image file and store it on my server with the path to the location of the file stored on a Mysql data base. I am using an ajax request to send the data but am having serious issues accessing any parts of the file:
PHP
<input type="file" id="upload_file" name='upload_file' style="width: 0px;height: 0px;">
Calls this javascript
function upload_photo(user_id) {
var file = document.getElementById('upload_file')
/* Create a FormData instance */
var formData = new FormData(form);
formData.append('user_id', user_id)
formData.append('file', file)
request = new ajaxRequest()
request.open("POST", "edit_details.php", true)
request.setRequestHeader("Content-type", "multipart/form-data")
request.onreadystatechange = function () {
if (this.readyState == 4)
if (this.status == 200)
if (this.responseText != null)
O('page').innerHTML = this.responseText
}
request.send(formData)
}
The request payload looks like this:
------WebKitFormBoundaryFA8fI4XH99ES61F6
Content-Disposition: form-data; name="file"
[object HTMLInputElement]
------WebKitFormBoundaryFA8fI4XH99ES61F6
Content-Disposition: form-data; name="user_id"
1001
------WebKitFormBoundaryFA8fI4XH99ES61F6--
But when I call a var_dump($_REQUEST) it prints
Any ideas? I've looked at loads but can't work my way through this issue.
I was talking to a professor at my university and he said that "multipart/form-data" can be a pain to work with, and said I may be better using a PUT?

There are 2 things to mention here with this issue.
First, you will need to make some extra work on the client side, in javascript, to pass multi-part data - I suspect this is what your teacher might have been talking about. For that, I'd refer you to this SO answer.
Second, on the server side, unlike all the other form data, files are not in the $_GET, $_POST or $_REQUEST array but in their own $_FILES array instead. I encourage you to read-up on this, but basically, PHP will upload in a temporary location, and you should copy the file to it's final location - then save that path into your database.
Hope this helps!

Related

How to attach form data in url which is used by Ajax?

So, I came across this problem whereby I want to access the data of a website, but it works only after the user interacts with the website. So, after selecting the date, it sends the ajax request to its site with a url, but also the form data. Here is the screenshot taken in Google Chrome.
And the problem is, the url doesn't work without specifying the cdate parameter as highlighted in the picture. Is there any way, I can send the form data (cdate in our case) to the specified url, so that it doesn't lead me to the error? Any way to do that?
In order to send form data progmatically, you can use the FormData object like so:
var formData = new FormData();
formData.append("cdate", "09/14/2019");
var request = new XMLHttpRequest();
request.open("POST", "http://example.com");
request.send(formData);
request.onLoad => (e) {
// Do something with request.response
};
Adapted from https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects

Send JSON file from jQuery to PHP without AJAX

So, I'm new to javascript/jquery, but I have played around long enough with PHP. I know how to get data from an input with PHP, which is really easy, but when trying to do the same with jQuery, how to do it just flies over my head.
Right now I have this script:
<script type="text/javascript">
function onSubmit( form ){
var data = JSON.stringify( $(form).serializeArray() );
console.log( data );
}
</script>
And this form:
<form onsubmit='return onSubmit(this)'>
<input type="date"/><br/>
<input type="date"/><br/>
<input type="submit" name=""/>
</form>
I see it logs the .json file just fine ([{"name":"from","value":"1994-01-01"},{"name":"to","value":"1994-02-02"}]) . My guess is it's pretty much sending the .json to the .php file, and then doing a $_POST, but I don't know how to proceed from here or do it. I don't know if ajax IS necessary or not, and if not, how to do it without it (everything I found around here is using ajax).
You can send form data as text string in standard URL-encoded notation or as JSON like string with jQuery.serialize().
<form id="set-date-form">
<input name="from" type="date"/><br/>
<input name="to" type="date"/><br/>
<input type="submit" id="set-date"/>
</form>
with jQuery
<script>
$('#set-date').on('click', function (e) {
e.preventDefault();
var data = $('#set-date-form').serialize();
$.post('somephpfile.php', data, function (response) {
// response is the data echoed from php
var result = JSON.parse(response) // assuming that php echoed ['success' => true/false];
if (result.success == true) {
alert("the values were sent to db successfully");
}else {
alert("the values were not sent to db successfully");
}
})
})
</script>
Then in your PHP file
<?php
$from = $_POST['from'];
$to = $_POST['to'];
// here you can update the database with this values
// after updating db or insert
// check if the query was successful
// if query was successful [echo json_encode(['success' => true]);] this value will be sent to javascript as a response
// if query was not successful [echo json_encode(['success' => false]);] this value will be sent to javascript as a response
PHP is treated Server-side.
If you want to send data to "PHP" you need to request the server (either via Ajax if you don't want to change your current page or calling a new URL with the data).
I know how to get data from an input with PHP
That's a pretty wrong statement as PHP can't get data from input since it's server side.
The browser send data to PHP calling the server.
Instead , define a route to post your input data in your php file and then through the form you can simply method='POST' rather than using ajax to send your data.
You could also use an XML HTTP Request.
Here is an example.
var http = new XMLHttpRequest();
var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type ", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
This is taken from an answer here.
Send POST data using XMLHttpRequest

Sending localStorage data to PHP

I've done some research and even have a book that explains Ajax calls to php and sending data to and from browser and server. I found this to be pretty close to what I need since I am using local storage How can I pass saved localStorage web data to a php script?, this link seems pretty coherent but I am not sure what to do on the PHP side How to pass data from Javascript to PHP and vice versa?,
though I have a bigger problem, the amount of data I have in local storage is pretty large, there are several different arrays that are stored there and are JSON encoded, when I get the array I use JSON.parse and to set the array in storage I stringify it. How could this be done to send that kind of data over? Not all the data in localStorage is an array either, there are hundreds of variables in local storage that need to be saved.
EDIT:
Here is my code since it was brought to my attention that it is needed.
I am trying to get all the data from localstorage to be sent to the server to be saved in a database.
function postData(){
var storage = JSON.stringify(localStorage);
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200 && xhr.status < 300) {
document.getElementById('div1').innerHTML = xhr.responseText;
}
}
};
xhr.open('POST', 'Membership.php');
xhr.setRequestHeader("Content-Type: text/json", "application/x-www-form-urlencoded");
xhr.send("data=" + storage);
}
On the PHP side of things I have
if ($_POST){
$data = json_decode($_POST['data']);
echo "The data" .$data;
}
I don't know if this is correct, I can't find anything on how to pass all localstorage data, this is basically what I was trying to ask before but obviously failed to convey that.
Basically what you need to do is:
Retrieve all the data from localStorage
Stringify everything (Now you have JSON representation of all the data)
Prepare the AJAX request using jQuery or other_framework_of_choice and set the payload to the stringified data and send it:
Send Content-type: text/json ti send a hint to the service that you are sending JSON data (Optional, but recommended)
Process the data within the PHP side (I.e json_decodethe payload and process it using your own logic satisfying your needs.
NOTE:
You didn't provided any code, so I would just skip the coding part (I can't guess your codes, mate)
EDIT
You can refer to Send data from localStorage via AJAX to PHP and save it in an HTML file
just skip the saving part and replace with your desired processing

Need help sending data and accessing it in the server. I want to do this using JavaScript(nodejs)

I've been having trouble with front-end back-end interactions. I'm relatively sure I'm sending the data but I cannot access the data afterwards. Most recently I have used this code template (from mozilla's help pages a link ) to send the data.
JavaScript:
function sendData(data) {
var XHR = new XMLHttpRequest();
var urlEncodedData = "";
// We turn the data object into a URL encoded string
for(name in data) {
urlEncodedData += name + "=" + data[name] + "&";
}
// We remove the last "&" character
urlEncodedData = urlEncodedData.slice(0, -1);
// We URLEncode the string
urlEncodedData = encodeURIComponent(urlEncodedData);
// encodeURIComponent encode a little to much things
// to properly handle HTTP POST requests.
urlEncodedData = urlEncodedData.replace('%20','+').replace('%3D','=');
// We define what will happen if the data are successfully sent
XHR.addEventListener('load', function(event) {
alert('Yeah! Data sent and response loaded.');
});
// We define what will happen in case of error
XHR.addEventListener('error', function(event) {
alert('Oups! Something goes wrong.');
});
// We setup our request
XHR.open('POST', 'http://ucommbieber.unl.edu/CORS/cors.php');
// We add the required HTTP header to handle a form data POST request
XHR.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
XHR.setRequestHeader('Content-Length', urlEncodedData.length);
// And finally, We send our data.
XHR.send(urlEncodedData);
}
HTML:
<button type="button" onclick="sendData({test:'ok'})">Click Me!</button>
My questions are: is there a better way of sending data (more suited to node)? and how can I access the data on the server side?
is there a better way of sending data?
This is rather subjective question, but here is an alternative: you can create form with hidden elements and send them to the server using FormData(). This allows you also comfortable files processing:
<form onsubmit="xhrsend(event,this)" method="POST" enctype="multipart/form-data" action="http://ucommbieber.unl.edu/CORS/cors.php">
<input type="hidden" name="myName" value="myValue"/>
<input type="file" name="myFile"/>
<input type="submit" value="Send"/>
...
</form>
use universal JS to XHR send any form
function xhrsend(ev,frm) {
ev.preventDefault(); // prevent submiting form
var XHR = new XMLHttpRequest();
XHR.addEventListener(...); // whatever
XHR.open('POST', frm.action, true);
XHR.send(new FormData(frm)); // send form data
this.reset(); // optional: reset form values
}
how can I access the data on the server side?
This question will guide you how to handle POST data on node.js server.
Note: if you play with node.js, I recommend to have a look at websockets - it can do more than XHR (like sending message from server to client).

XHR in Chrome Extension with CI

I'm sending a POST from a chrome extension content script to a server I control. I setup the permissions in the manifest ok. Here is my XHR code. (I want to avoid jQuery for this). Its sending an empty responseText
var xhr = new XMLHttpRequest();
xhr.open("POST",'http://mysite.com/make',true);
xhr.onreadystatechange=function() {
if (xhr.readyState == 4) {
var res = JSON.parse(xhr.responseText);
console.log(res);
}
}
xhr.send({'textbox':data[0].user,'from':'extension'});
data[0].user is an object I got directly from the Twitter API
in my CI controller I have
$user = $this->input->get_post('textbox', TRUE);
$from = $this->input->get_post('from', TRUE);
$fullURL = 'http://www.google.com'; //example of a URL from code.
$json = $this->output->set_content_type('application/json');
$json->set_output(json_encode(array('URL' => $fullURL)));
The response text is empty
a jquery call on the other hand works fine
$.post("http://mysite.com/make", { 'textbox': data[0].user, 'from':'jquery' },
function(data) {
console.log(data);
});
Reason is simple, JQuery post method can accept JSON and then convert it to string and send to the server.
What you are trying to do is to directly send JSON here :
xhr.send({'textbox':data[0].user,'from':'extension'}) // Incorrect way
send method should either accept NULL or a string which is generally made up of QueryString Parameters like.
xhr.send("textbox="+ data[0].user + "&from=extension"); // Correct way
This will ensure that your data goes to the appropriate URL with textbox and from as post request parameters.
and queryString will be generated like textbox=username1234&from=extension in the packet's body unlike one goes in Get with the headers along side the URL.
jQuery's post method makes it simpler for you to format data you send using JSON and then internally it converts that to a queryString to send parameters.
You can't directly send Javascript object like that with an XHR object!
Also checkout this example:
http://beradrian.wordpress.com/2007/07/19/passing-post-parameters-with-ajax/

Categories