Send JSON file from jQuery to PHP without AJAX - javascript

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

Related

Issue accessing fileData

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!

POST request alerts that it was successful, but data is not sent

I have a JavaScript code that is supposed to send some data to a php file on the server. The JavaScript code gives an alert that the post was successful, but no data is on the php file. No errors show up in the console. What is the problem here?
Here is the code:
var data = "It works";
var url = "data.php";
var http = new XMLHttpRequest();
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
alert("It worked");
}
}
http.send(data);
Here is the site for the code:
http://mikeyrichards.freeiz.com/run.html
EDIT: A clarification, I only want the data to show up like a text file on the PHP. For some reason, my server cannot open text files, so I have to use PHP
You need to send data in key value format something like this
var data = "lorem=ipsum&name=test";
Try changing to:
var data = 'data=It+works';
Then you can access it in the PHP script as $_POST['data'].
Don't forget to encode the space as + or %20. If you're generating the data dynamically, use encodeURIComponent to encode it properly:
var data = 'data=' + encodeURIComponent(value);

Initiate a Post request from a form with paylod in the Body request

I have the following problem. I have a webservice, which accepts a post request with some json data in the request body and which also returns Json data.
Now I want to build a user friendly HTML page to test this service. I have a form to fill in data, when the user clicks the button, the JSON should be build from the form data and POSTed to my webservice, the response should be displayed to the user. How do I achieve that?
jQuery is your friend, the have a look at ajax part...there a bunch of function that forge a request and grab directly the data from your form.
http://api.jquery.com/jquery.ajax/
This is one example doing this, but it requires a MySQL database and PHP support by your provider.
jQuery
$('#form').on('submit', function(e) {
e.preventDefault();
var data = $(this).serialize();
$.POST('path_to_php_file.php', data, function(response) {
$('#container').append(response);
});
}
PHP
<?php
$db = new PDO('mysql:host=localhost;dbname=DATABASENAME;charset=utf8', USERNAME, PASSWORD);
//the post variables equal the name attribute on your input element in html: <input name="THIS">
$text = $_POST['text'];
$name = $_POST['name'];
if(isset($text) && isset($name)) {
$stmt = $db->prepare("INSERT INTO table_name (text, name) VALUES (?, ?)");
$stmt->execute(array($text, $name));
echo "Successfully saved.";
} else echo "There was an error.";
$db = null;
Another option, if you just want to test your webservice, is to use postman, a friendly chrome extension for testing web APIs.
Otherwise, you really don't even need jQuery. A synchronous post is easy enough to write:
var button = document.getElementById("submit");
button.onclick = function() {
var xhr = new XMLHttpRequest();
xhr.open("POST", "yourwebservice.com/your-web-service", false);
xhr.send("{'json_string':['goes'],['here']}");
alert(xhr.response);
}

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