I'm hoping to extract one custom header response from a site using the Javascript code below:
<html>
<head>
<script>
var data = null;
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
//console.log(this.responseText);
}
});
var URL = "http://somesite.xml/records"
xhr.open("GET", URL);
xhr.setRequestHeader("authorization", "Basic itworks");
xhr.send(data);
var xrecords = xhr.getResponseHeader("X-Records");
console.log(xrecords);
</script>
</head>
Two questions:
1. What changes do I need to make to have the response pull the content of that custom header?
2. The content of the header is a number of records. How can ensure that the data type is a number?
EDIT: Turned out the issue I was having was because I wasn't using an async function. A snipped of my resolved code is below:
function selector(x){
function fooO(callback) {
function overdue (x){
return "tasks.json?responsible-party-ids="+x+"&filter=overdue";
}
return $.ajax({
url: 'https://' + company + '.site.com/' + overdue(x),
headers: {
"Authorization": "BASIC " + window.btoa(key)
}
})
}
Related
I am trying to develop a component in Joomla 4. I have a simple button that should fire of a script to update the database.
I can make the call to the JavaScript ok, but the JavaScript does not appear to open the request URL, if anything it opens the current URL or refreshes the page. The script works fine outside of Joomla but not inside.
I have tried both the following, and the same thing happens:
*function buttonLike()
{
var xhr = new XMLHttpRequest();
var parentEl = this.parentElement;
//var url = 'index.php?com_reflect&format=raw;
var url = 'liked.php';
console.log('Get Here OK' + parentEl.id);
xhr.open('GET', 'liked.php', true);
// Form data is sent appropriately as a POST request
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.onreadystatechange = function ()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
var result = xhr.responseText;
console.log('Never Here Result: ' + result);
}
if(xhr.readyState == 4 && xhr.status == 0)
{
console.log('Always Here');
}
};
xhr.send("id=" + parentEl.id);
}*
OR
function buttonLike()
{
//var url = 'index.php?com_reflect&format=raw;
var url = 'liked.php';
var request = new Ajax(url, {
method: 'post',
update: some_div,
data: options,
onComplete: function (){
$('some_field').setHTML('I am finished!');
}
}).request();
Been going round in circles on this one, any help would be appreciated.
I know this question has been asked before, but I have tried just about every way to get this to work, AJAX, JQUERY, trying to use p5.js and none seem to work.
All I want to do is open my api, parse the JSON data, and log the first_name element of the JSON data
I am willing to use other functions to achieve the API result.
var apiURL = 'url';
var request1 = new XMLHttpRequest();
request1.open('GET', apiURL, true);
request1.onload = function()
{
if (this.status === 200)
{
console.log(JSON.parse(request1.responseText));
ting = JSON.stringify(JSON.parse(request1.responseType));
console.log(ting);
console.log(ting.first_name);
console.log(ting.first_name[0]);
}
};
request1.send();
the API url is https://api.hunter.io/v2/email-finder?domain=asana.com&first_name=Dustin&last_name=Moskovitz&api_key={API KEY}
the JSON data is
JSON Gyazo
This logs your first_name to the console using jQuery AJAX.
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>
$.ajax({
url: "https://api.hunter.io/v2/email-finder?domain=asana.com&first_name=Dustin&last_name=Moskovitz&api_key={API_KEY}",
type: 'GET',
}).done(function(dataObj) {
console.log(dataObj.data.first_name);
}).fail(function(xhr, textStatus, errorThrown) {
alert("Error: " + xhr.status + " " + textStatus);
});
</script>
You were almost there, first_name is under obj.data.first_name not obj.first_name
var apiURL = 'https://api.hunter.io/v2/email-finder?domain=asana.com&first_name=Dustin&last_name=Moskovitz&api_key=0409bb7315acf3ed037b22818e10fd51ff7be5e4';
var request1 = new XMLHttpRequest();
request1.open('GET', apiURL, true);
request1.onload = function()
{
if (this.status === 200)
{
var obj = JSON.parse(request1.responseText);
console.log(obj.data.first_name)
}
};
request1.send();
How can I translate this curl script to an AJAX request in JavaScript?
curl -X POST
-d "grant_type=password&username=admin&password=Demo1234"
-u "<ClientID>:<ClientSecret> " http://<host>/url/to/auth
I will show an example in pure JavaScript
function sendData()
{
var formData = new FormData(); //create formData object to send data
formData.append("grant_type, "password"); //via append you add data
formData.append("username", "admin");
formData.append("password", "Demo1234");
var xmlHttp = new XMLHttpRequest(); //create "ajax/xhr" object
xmlHttp.onreadystatechange = function() //monitor status of response
{
if(xmlHttp.readyState === 4 && xmlHttp.status === 200) //if it's ok
{
console.log(xmlHttp.responseText); //then output data
}
}
xmlHttp.open("POST", "http://<host>/url/to/auth");
xmlHttp.setRequestHeader("Authorization", "Basic " + btoa("<ClientID>" + ":" + "<ClientSecret>");
xmlHttp.send(formData);
}
Your curl call uses three things:
Unprocessed data.
HTTP Authentication.
Templating? - Not sure.
This is what I best came up with:
$.ajax({
"url": "http://<host>/url/to/auth",
"data": "grant_type=password&username=admin&password=Demo1234",
"processData": false,
"beforeSend": function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa("<ClientID>" + ":" + "<ClientSecret>"));
}
});
Replace your <ClientID> and <ClientSecret> with the right values.
Here is how you can do it for any curl not just this one:
Get postman (https://www.getpostman.com/)
follow this to import your curl to postman: https://www.getpostman.com/docs/postman/collections/data_formats#importing-postman-data
follow this to generate a code snippet for the curl you just imported: https://www.getpostman.com/docs/postman/sending_api_requests/generate_code_snippets
one of the code snippet exporters is jqueryAjax.
My first post here.
I'm using droidscript and I have to include an header that contains a specific user and a password in order to retrieve a token. I'm having trouble because I don't know where to include those headers.
That's the code I'm using:
function btn_OnTouch(){
var url = "myurl";
SendRequest(url);
}
//Send an http get request.
function SendRequest(url){
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
HandleReply(httpRequest);
};
httpRequest.open("GET", url, true);
httpRequest.send(null);
app.ShowProgress("Loading...");
}
//Handle the servers reply (a json object).
function HandleReply(httpRequest){
if (httpRequest.readyState == 4){
//If we got a valid response.
if (httpRequest.status == 200){
txt.SetText("Response: " + httpRequest.status + httpRequest.responseText);
}
//An error occurred
else
txt.SetText("Error: " + httpRequest.status + httpRequest.responseText);
}
app.HideProgress();
}
The told me I should probably include the headers like this, but I don't know where to put them in my code.
httpRequest.setRequestHeader(“username”, “myuser”);
httpRequest.setRequestHeader(“password”, “mypass”);
You need to do it just after calling the open method like this:-
httpRequest.open("GET", url, true);
httpRequest.setRequestHeader("username", "myuser");
httpRequest.setRequestHeader("password", "mypass");
httpRequest.send(null);
I want to autoupdate page using PHP and Ajax. Right now I have this code on a page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<i class="fa fa-heart-o"></i>
</body>
</html>
When the user clicks on the link it is redirected to another page called "Page-Like.php"
include("config.php");
//get vars
$idSubliminal=$_GET["idSubliminal"];
$idCategoria=$_GET["idCategoria"];
// mysql_query("insert into Rating .... (mysql insert query)
echo "<script>
location.href=\"AudioSubliminal.php?idSubliminal=$idSubliminal&idCategoria=$idCategoria\";
</script>";
What I want is to do this usig Ajax in order to not refresh the page. I know I'm missing the javascript code, but I would like to get some suggestions to complete this script.
Thanks!
All you need is a basic ajax request to achieve your functionality. check the sample request below.
function ajaxpr(){
var URLString="idSub=12&idCat=32";
ajax_request = $.ajax({
type: 'GET',
url: "Page-Like.php",
data: URLString,
dataType : 'html',
context: $(this),
success: function (msg)
{
//perform the required operation after success
});
}
add function onclick on tag . then define that function using :
$.ajax({
type: 'GET',
data: {idSub: "12", idCat: "32"},
url: "Page-Like.php",
dataType: 'JSON',
success: function (response, textStatus, jqXHR) {
//DEFINE FUNCTION HERE
}
});
This is using ajax function without refresh page.
You can use many methods to implement Ajax on you're code.
One of this is jQuery, other is mootools, etc.. Depends of wich library you know or want to learn.
Using ajax to load a page is easy. Follow this link http://www.w3schools.com/ajax/
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Change this to your desired DOM tag
document.body.innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "Page-Like.php?idSub=12&idCat=32", true);
xhttp.send();
}
Now it's just a matter of putting event listener to run loadDoc() function. If the link is dynamic, you can parse the parameter to the function.
However, I notice you have a js script inside your php which will redirect again to AudioSubliminal.php. If this is your desired flow then it's okay. If not, you can create another function
function loadAudioSubliminal(idSub, idCat) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Change this to your desired DOM tag
document.body.innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "AudioSubliminal.php?idSubliminal=" + idSub + "&idCategoria=" + idCat, true);
xhttp.send();
}
and modified loadDoc() to receive a parameter such that idSub and idCat can be passed again. for Example :
function loadDoc(idSub, idCat) {
var xhttp = new XMLHttpRequest();
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Change this to your desired DOM tag
document.body.innerHTML = xhttp.responseText;
// run the function after finished loading Page-like.php
loadAudioSubliminal(idSub, idCat)
}
xhttp.open("GET", "Page-Like.php?idSub=" + idSub + "&idCat=" + idCat, true);
xhttp.send();
}