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

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

Related

Post to and visit a URL in Javascript

I'm trying to:
Post a JSON object to a URL and visit it at the same time.
Set the content-type and accept headers
I'm working with an old source base (asp classic / vb). Ideally, if I can do this in javascript it would be wonderful!
Constructing the js call with headers and data is simple with XHR:
var xhr = new XMLHttpRequest();
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = JSON.stringify({JSON DATA});
xhr.send(data);
However this is an async call and I can't seem to find a way of making it actually visit the URL in the browser.
The alternative is to create an form and append it to a HTML entity before using javascript to submit it. This time is post the data to and visits to the URL.. however, I don't have control over the headers.
So back to my questions. Can I post to and visit a URL in Javascript?
Given that visiting an URL in the browser is a GET request, and you want to POST at the same time, NO you cannot.
Why do you need to post and visit?
You could post your data and in the callback (once the post request is done) load the the page.
No.
The closest you could come would be to:
Use Ajax to make the request
Use DOM to modify the current page with data from the response
Use the History API to update the URL in the address bar
Changing the server side code to expect regular form encoded data and then submitting a regular form would probably be the simplest approach to solving the problem.
You are using XHR, and if you want to manage it from javascript... Add onreadystatechange property to your xhr (this function will be fired when your server response), and in this function redirect using window.location.href
var xhr = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Here redirect, with params if you need to
window.location.href = "https://stackoverflow.com?name1=value1&name2=value2";
}
};
var url = "url";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
var data = JSON.stringify({JSON DATA});
xhr.send(data);

How to retrieve/access variable from HTML/Javascript in django views to process it?

I am saving the coordinate (generated by click on google map) in the variable ccc. Now I want to process this variable in Django. How to get its value like we get from HTML input element (for eg.
myX = request.POST.get("myInput"))
Here is the curtailed code:
<html>
<script>
google.maps.event.addListener(map, 'click', function(e) {
var ccc = e.latLng.lat(); //I want to retreive this variable
//ccc = 77.6746784
});
</script>
</html>
You can use ajax request to send data to the server like this
var xhr = new XMLHttpRequest()
var params = "ccc=" + ccc;
xhr.open("POST", YOUR_DJANGO_VIEW_URL, true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
xhr.send(params);
Obviously the only way to send values from the browser to your django server is to send an HTTP request (using POST because it's submitting data for processing). Whether you use a form and a plain post request (eventually submiting the form via javascript too), or you post using ajax (well, using a XMLHttpRequest object to be exact).

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

Access parameters in a XMLHttpRequest Google Apps Script

I am currently trying to access the parameters of a POST request using Google Apps Script. I can logger the params object using e.parameter though i cannot seem to access the keys of the object by by using e.parameter.name.
XMLHttpRequest
var http = new XMLHttpRequest();
var url = "myappURL";
var params = JSON.stringify({employeeStatus: "Active", name: "Henry"});
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Call a function when the state changes.
http.onreadystatechange = function() {
// call back function
} // end callback
http.send(params);
Google Apps Script
function doPost(e) {
if (typeof e !== 'undefined') {
Logger.log(e.parameter.name); // does not work (undefined)
} // end if
} // end doPost
There are subtle quirks with the different ways data is posed via http. For instance I notice that you are using Content-type "application/x-www-form-urlencoded" when the usual header for json data is Content-Type: application/json.
I added a line that just returns the contents of the e variable so you can see what is returned.
I used curl to debug it with the following command.
curl -H "Content-Type: application/json" ---data "{status:123}" https://script.google.com/macros/s/AKfycbyJ38V-HpG7A-DxIBpik4HJ89fAtnCemCJ7ZXeFEL8KPEuGsR8/exec
The response I received was:
{"parameter":{},"contextPath":"","contentLength":12,"queryString":null,"parameters":{},"postData":{"length":12,"type":"application/json","contents":"{status:123}","name":"postData"}}
You can see that in my case the json was returned in the contents field rather than the parameters.
You could try this with your script to see what you get. You could also try changing the Content-Type.
After Further testing I think you would be better submitting your fields a form data rather than json. I have been able to get the paramer back by amending your javascript to:
var http = new XMLHttpRequest();
var url = "https://script.google.com/macros/s/AKfycbyJ38V-HpG7A-DxIBpik4HJ89fAtnCemCJ7ZXeFEL8KPEuGsR8/exec";
var params = "employeeStatus='Active'&name='Henry'";
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Call a function when the state changes.
http.onreadystatechange = function() {
if (http.readyState==4) {
//alert the user that a response now exists in the responseTest property.
console.log(http.responseText);
// And to view in firebug
// console.log('xhr',xmlhttp)
}
} // end callback
http.send(params);

XMLHttpRequest POST parameter encoding

I want to submit a POST request while passing a url among other parameters.
I have the following script but it is not working.
var params = "param1="+param1_value+"&url="+url_value;
var xhr = new XMLHttpRequest();
xhr.open("POST", action_url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
console.log("Done");
}
}
xhr.send(params);
Assuming that the url_value is something like this:
https://www.domain.com/blah?param=&email=domain%40email%2Ecom&blah=1234
what would be wrong with this script?
Take a look at this question/answer - Should I URL-encode POST data?
Your sample value for url_value is using the HTML Entity Code. Because of the & symbol in the value, it is being sent as multiple values. You probably need to URL encode it so it looks like this
https%3A%2F%2Fwww.domain.com%2Fblah%3Fparam%3D%26email%3Ddomain%40email.com%26blah%3D1234
You may have a problem when trying to access another domain/website. The receiving side must have the Access-Control-Allow-Origin header in its return message.
You can probably find your solution in this answer.
You are missing quotation to the url string value,alert the parameter string as below
var params = "param1='"+param1_value+"'&url='"+url_value+"'";

Categories