I'm trying to send a long string through ajax to php page that will process it and return what I need, I think that It exceeds GET capacity or something like that!
but for some reason it doesn't work
var string = document.getElementById('text').innerHTML; // so long text
var xhr = new XMLHttpRequest();
xhr.open('GET', 'read.php?string=' + string, true);
xhr.send();
xhr.onreadystatechange = function () {
if (xhr.status == 200 && xhr.readyState == 4) {
content.innerHTML = xhr.responseText;
} else {
content.innerHTML = 'loading';
}
}
how can I make it works!
Just replace:
xhr.open('GET', 'read.php?string=' + string, true);
xhr.send();
with
var body = "string=" + encodeURIComponent(string);
xhr.open("POST", "read.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-Length", body.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(body);
To solve the URL-encoding problem, do:
xhr.open('GET', 'read.php?string=' + encodeURIComponent(string), true);
Related
I formulated this XHR request by converting it from curl.
the curl request works but can't get this one working. plz help.
var url = "https://networkappers.com/api/port.php?ip=172.217.13.238&port=80";
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Referer", "https://www.networkappers.com/tools/open-port-checker");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}
};
xhr.send();
I have wrote a script that send some data to an external php file without jquery.
<script type="text/javascript">
var statsPage = 'http://www.my-url.com/response.php';
function ca(c,o,n,t,e,t,u){return p={type:c,userid:o,gender:n}}
ca("pageview", "1", "male");
var params = Object.keys(p).map(function(k) {
return encodeURIComponent(k) + '=' + encodeURIComponent(p[k])
}).join('&')
const req = new XMLHttpRequest();
//req.addEventListener('load' /*callback after req is complete*/);
req.open('GET', statsPage + '?' + params);
req.send();
req.onreadystatechange = function() {
if (req.readyState == XMLHttpRequest.DONE) {
alert(req.responseText);
}
}
</script>
What i also want to do is to send data when the browser tab is closed, so i wrote a script like below but it is not working. I don't get a response from the php file here.
navigator.sendBeacon = navigator.sendBeacon || function () {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.my-url.com/response.php?pag_title=1');
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
};
I found also this script but it gives me also no response from the response.php file as an alert:
window.onbeforeunload = function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.my-url.com/response.php?pag_titel=1', true);
// If specified, responseType must be empty string or "text"
xhr.responseType = 'test';
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
//console.log(xhr.response);
//console.log(xhr.responseText);
alert(xhr.responseText);
}
}
};
xhr.send(null);
}
EDIT
I did also the following test but now it gives me an alertbox with the value 1 first and then an alert with the response of the function ca (see first part of the code on top for the function). So i think the onbeforeunload is not working here. If i close browser tab i get nothing in response.
window.onbeforeunload = function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.digital-productions.be/dev/analytics/response.php?pag_titel=1', true);
// If specified, responseType must be empty string or "text"
xhr.responseType = 'test';
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
alert(xhr.responseText);
}
}
xhr.send(null);
}
You can use the beforeunload event to execute code before the user leaves the page, or you could warn them that there is unsaved changes. You can return a message by using e.returnValue = "Message";.
window.addEventListener("beforeunload", function(e) {
//code
});
Here is a link from the mozilla documentation: https://developer.mozilla.org/en/docs/Web/Events/beforeunload
I am sending parameters using XMLHttpRequest() javascript function to another php page in Json formate, but $_POST['appoverGUID'] not getting post values.
Here is my Javascript code.
function loadPage(href){
var http = new XMLHttpRequest();
var url = json.php;
var approverGUID = "Test";
var params = JSON.stringify({ appoverGUID: approverGUID });
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/json; charset=utf-8");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
document.getElementById('bottom').innerHTML = http.responseText;
}
}
http.send(params);
}
And here is my json.php file code.
if(isset($_POST['appoverGUID'])){
echo $_POST['appoverGUID'];
}
First of all remove these headers since they will be send automatically by the browser and it's the right way to do it.
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
This code is a cross browser solution and it's tested.
// IE 5.5+ and every other browser
var xhr = new(window.XMLHttpRequest || ActiveXObject)('MSXML2.XMLHTTP.3.0');
var params = "appoverGUID="+approverGUID;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
xhr.setRequestHeader("Accept", "application/json");
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
console.log(JSON.parse(this.responseText));
}
}
}
xhr.send(params);
xhr = null;
You need use json_decode. Some like this:
if ("application/json" === getallheaders())
$_JSON = json_decode(file_get_contents("php://input"), true) ?: [];
Fill params this way (did no escaping/encoding of approverGUID content, here..):
params = "appoverGUID="+approverGUID;
Also see:
http://www.openjs.com/articles/ajax_xmlhttp_using_post.php
Retrieving the data with PHP, I cannot use $_POST; but $_GET. Why? Am I sending my form data incorrectly?
I'd have thought request.open("POST" would process the form as a POST and not GET? How may I sent it as a POST?
var request = new XMLHttpRequest();
request.open("POST","email.php?text=" + textarea.value + "&email=" + email.value, true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
var resp = request.responseText;
console.log(resp);
}
};
request.send();
Because you're adding data inside the URL.
Change your request to:
request.open("POST","email.php", true);
request.setRequestHeader("Content-length", 2); // 2 here is the no. of params to send
....
request.send("text=" + textarea.value + "&email=" + email.value);
Docs: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
The reason is you are sending the variables in the url that is why you are getting in get. See this example post
var http = new XMLHttpRequest();
var url = "get_data.php";
var params = "lorem=ipsum&name=binny"; // all prams variable here
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
I've written this code using various online sources but I cannot seem to figure out the last part.
function loadajax (event) {
event.preventDefault();
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
if(xhr.status == 200)
document.ajax.dyn="Received:" + xhr.responseText;
else
document.ajax.dyn="Error code " + xhr.status;
}
};
xhr.open('GET', this.href, true);
var content = document.getElementsByTagName('article')[0];
content.innerHTML = xhr.responseText;
}
It seems to work until I need to add content to my page. Indeed content.innerHTML = xhr.responseText; returns nothing. I am getting a simple HTML file, how can I post it in my page? what am I doing wrong?
Thanks for your help!
ajax calls are asynchronous. it will work if you'll move the content.innerHTML = xhr.responseText; line into the onreadystatechange function like this:
function loadajax (event) {
event.preventDefault();
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
document.ajax.dyn="Received:" + xhr.responseText;
content.innerHTML = xhr.responseText;
else
document.ajax.dyn="Error code " + xhr.status;
}
};
xhr.open('GET', this.href, true);
var content = document.getElementsByTagName('article')[0];
}
Put your contet.innerHTML inside status 200 condition.
You are just assigning the value to content before it really exists. Before the ajax got it from server.