how to send data with ajax GET request - javascript

just using vanilla javascript is it possible to send data to a php server without appending it to the url?
here's what I have so far:
function getAjax(url, success) {
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('GET', url);
xhr.onreadystatechange = function() {
if (xhr.readyState>3 && xhr.status==200) success(xhr.responseText);
};
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send();
return xhr;
}
getAjax('http://localhost/login/public/login.php?email=someone#gmail.com',
function(data){ console.log(data); });
can I add $_GET parameters in xhr.send()? or is there another way to send this object along with the request:
data = {email:'someone#gmail.com',
password:'compas'}

Related

Need help getting a response from API

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

JS - open PDF in new Tab via XHR - with filename and auth header

Thank you for reading!
I want to open a PDF from a REST backend that gets loaded via XHR in a new tab with specified filename and Authorization header.
So far I managed to download it with this (incl. auth headers and filename):
// saves XHR stream as file with configurable filename
downloadXHRFile:function(endpoint,data,method,filename,errorcallback,mimetype){
bsLoadingOverlayService.start();
var def = $q.defer();
var token = localStorageService.get('token');
var xhr = new XMLHttpRequest();
xhr.open(method, CONFIG.URL+endpoint, true);
xhr.setRequestHeader('Authorization', 'Bearer '+token);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) {
var blob=new Blob([this.response], {type:mimetype});
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download=filename;
link.click();
bsLoadingOverlayService.stop();
}else{
bsLoadingOverlayService.stop();
errorcallback(xhr.statusText);
}
def.resolve();
};
xhr.send(
JSON.stringify(data)
);
return def;
},
Further I managed to open it in a new tab with the following code (incl. auth headers).
Unfortunately the URL (and by that the filename) looks like this:
blob:http://localhost:3000/0857f080-d152-48c6-b5fb-6e56292db651
Probably it can be solved somehow like above but I cant find the solution.
Does someone have a clever idea how I could set the filename in the new Tab?
// opens XHR filestream in tab
openXHRFile: function(endpoint,filename,errorcallback){
var token = localStorageService.get('token');
var our_url = CONFIG.URL+endpoint;
var win = window.open('_blank');
downloadFile(our_url, function(blob) {
var url = URL.createObjectURL(blob);
win.location = url;
});
function downloadFile(url, success) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.setRequestHeader("Authorization", 'Bearer '+token);
// xhr.setRequestHeader('Content-Type', 'application/json');
xhr.responseType = "blob";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (success) success(xhr.response);
}else{
}
};
xhr.send(null);
}
},

Ajax Jquery CORS not working

Hi everyone i'am fighting and searching solutions about this from 3 days. I have a problem getting data from sharethis.com RESTapi. I am working with jQuery and Laravel 5.2. I want to get values from this json: http://rest.sharethis.com/v1/count/urlinfo?url=http://www.sharethis.com but i'am very frustated trying a lot of methods and functions. My actual code is this:
function setHeader(xhr) {
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Headers', 'Content-Type');
xhr.setRequestHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
}
$.ajax({
url: 'http://rest.sharethis.com/v1/count/urlinfo?url=http://www.sharethis.com',
type: 'GET',
beforeSend: setHeader,
contentType: 'application/json; charset=utf-8',
success: function() { alert("Success"); },
error: function() { alert('Failed!'); }
});
This request always return "Failed!". I understand a little what CORS means but on practice i can't make it work. Any ideas? Thanks..
Maybe you actually don't understand CORS :)
These headers have to be present in the response, not in the request.
The server has to provide them.
The server has to agree.
The URL you provided doesn't have CORS headers so you can't fetch it via AJAX unless you modify the backend.
Run this code with XMLHttpRequest to get data
var url = "http://rest.sharethis.com/v1/count/urlinfo?url=http://www.sharethis.com";
var xhr = createCORSRequest('GET', url);
xhr.setRequestHeader(
'X-Custom-Header', 'value');
xhr.withCredentials = true;
xhr.onload = function () {
if (this.status === 200) {
console.log(xhr);
}
};
xhr.send();
And there is the function to check if the url support CORS
function createCORSRequest(method, url)
{
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
console.log("for chrome/fir");
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
console.log("ie");
} else {
// CORS not supported.
xhr = null;
console.log("not supported");
}
return xhr;
}
hope it helps, regards

load array saved in text file into javascript

I would like to load a text file with an array like the one below so it is accessible within javascript, how can I do that via an ajax call to access the text file? This is the text file artists.txt:
["Fally ipupa","Radio & Weasel","P-Square feat. Don Jazzy","Mose Fanfan","Fally ipupa","Mercy Masika","Madilu System","Koffi Olomidé","DaVido","Luciano","Kanda Bongo Man","Franco","Franco","DJ Afrobeat","Oliver Mtukudzi","Sauti Sol","Alikiba","Aryon","Gramps Morgan","Buju Banton","Wailing Souls","Bob Marley & The Wailers","Don Carlos and Gold","Burning Spear","Peter Tosh","George Nooks","Richie Spice","Culture","Sanchez","Terry Linen","Archie Wonder","Jah Cure","Busy Signal","Romain Virgo","Junior Reid","Shaggy","Glen Washington","Ginjah","Lucky Dube","Bushman","Chronixx","Turbulence","Protoje","UB40","Franco","Rich Mavoko","Rose Muhando","Kanda Bongo Man","Diamond"," Davido","Tekno","Daddy Owen","Pépé Kallé","Busy Signal","Franco Et Le T.P. O.K. Jazz","Alice Kamande","Koffi Olomidé","Culture","Alikiba","Papa Wemba","Korede Bello","Madilu System","Reuben Kigame","Gloria Muliro"]
Just call it via ajax directly using GET request.
/**************************************************************************************************
Ajax
*/
// Set all of these parameters.
// type
// url
// callback
// data
Pub.ajax = function (config_ajax) {
var xhr = new win.XMLHttpRequest();
// post_json
if (config_ajax.type === 'post_json') {
xhr.open("POST", config_ajax.url, true);
xhr.setRequestHeader("Content-type", "application/json");
}
// post
if (config_ajax.type === 'post') {
xhr.open("POST", config_ajax.url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
// get
if (config_ajax.type === 'get') {
xhr.open('GET', config_ajax.url, true);
}
// post for form_data
if (config_ajax.type === 'multi') {
xhr.open("POST", config_ajax.url, true);
}
xhr.onload = completed;
xhr.send(config_ajax.data);
function completed () {
if (this.status === 200) {
config_ajax.callback(xhr.responseText);
} else {
throw new Error("xhr.status is " + this.status);
}
}
xhr.app_url = config_ajax.url;
Priv.createStatusBar(xhr);
return xhr;
};
In order to make it work through Ajax call,
Rename your file as artists.json
Set MIME type in your web server, as application/json for .Json extension. This would be already set in most of the webservers.
Then do an Ajax call, if you use library like jquery then it is pretty straight as follows
url=my site.com/artists.json;
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
This should automatically allow you to fetch and read the JSON file in your success method.

How to display POST values which are coming from javascript XMLHttpRequest() in php

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

Categories

Resources