Ajax is correctly returning and displaying data but error message is being activated - ajax

I'm performing AJAX using the following code:
function main() {
// get the name fields
var name1 = document.getElementById("name1").value;
var name2 = document.getElementById("name2").value;
// Encode the user's input as query parameters in a URL
var url = "response.php" +
"?name1=" + encodeURIComponent(name1) +
"&name2=" + encodeURIComponent(name2);
// Fetch the contents of that URL using the XMLHttpRequest object
var req = createXMLHttpRequestObject();
req.open("GET", url);
req.onreadystatechange = function () {
if (req.readyState == 4 && req.status == 200) {
try {
// If we get here, we got a complete valid HTTP response
var response = req.responseText; // HTTP response as a string
var text = JSON.parse(response); // Parse it to a JS array
// Convert the array of text objects to a string of HTML
var list = "";
for (var i = 0; i < text.length; i++) {
list += "<li><p>" + text[i].reply + " " + text[i].name + "</p>";
}
// Display the HTML in the element from above.
var ad = document.getElementById("responseText");
ad.innerHTML = "<ul>" + list + "</ul>";
} catch (e) {
// display error message
alert("Error reading the response: " + e.toString());
}
} else {
// display status message
alert("There was a problem retrieving the data:\n" + req.statusText);
}
}
req.send(null);
}
// creates an XMLHttpRequest instance
function createXMLHttpRequestObject() {
// xmlHttp will store the reference to the XMLHttpRequest object
var xmlHttp;
// try to instantiate the native XMLHttpRequest object
try {
// create an XMLHttpRequest object
xmlHttp = new XMLHttpRequest();
} catch (e) {
// assume IE6 or older
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHttp");
} catch (e) {}
}
// return the created object or display an error message
if (!xmlHttp) alert("Error creating the XMLHttpRequest object.");
else return xmlHttp;
}
This works exactly as planned, the code within the try block is executed perfectly. But the alert "There was a problem retrieving the data: is also activated, with req.statusText displaying "OK".
How can this be possible? How can the code within the if statement activate perfectly but at the same time the else block is activated?
I'm stumped, any ideas?
The servor code is simply:
<?php
if( $_GET["name1"] || $_GET["name2"] ) {
$data = array(
array('name' => $_GET["name1"], 'reply' => 'hello'),
array('name' => $_GET["name2"], 'reply' => 'bye'),
);
echo json_encode($data);
}
?>
And the HTML:
<input id="name1">
<input id="name2">
<div id="responseText"></div>
<button onclick="main();">Do Ajax!</button>

Your conditional is probably being activated when req.readyState == 3 (content has begun to load). The onreadystatechange method may be triggered multiple times on the same request. You only care about what happens when it's 4, so refactor your method to only test when that is true:
var req = createXMLHttpRequestObject();
req.open("GET", url);
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
try {
// If we get here, we got a complete valid HTTP response
var response = req.responseText; // HTTP response as a string
var text = JSON.parse(response); // Parse it to a JS array
// Convert the array of text objects to a string of HTML
var list = "";
for (var i = 0; i < text.length; i++) {
list += "<li><p>" + text[i].reply + " " + text[i].name + "</p>";
}
// Display the HTML in the element from above.
var ad = document.getElementById("responseText");
ad.innerHTML = "<ul>" + list + "</ul>";
} catch(e) {
// display error message
alert("Error reading the response: " + e.toString());
}
} else {
// display status message
alert("There was a problem retrieving the data:\n" + req.statusText);
}
}
};
req.send(null);

Related

How to upload outlook email attachments on my cloud server using Outlook Js Add-in

I am developing outlook javascript add-in using vs2017. I have created a sample application to find attachments from outlook mail item. Here, While getting attachments from Exchange Server, It returns 200 OK.
I have my own cloud application looks like google drive. I want to upload outlook mail attachments on my cloud server using POST API call. API call was running successfully. But I am not able to get file content from the exchange server.
I have added some sample code over here.
Creating a service request
/// <reference path="../App.js" />
var xhr;
var serviceRequest;
(function () {
"use strict";
// The Office initialize function must be run each time a new page is loaded
Office.initialize = function (reason) {
$(document).ready(function () {
app.initialize();
initApp();
});
};
function initApp() {
$("#footer").hide();
if (Office.context.mailbox.item.attachments == undefined) {
var testButton = document.getElementById("testButton");
testButton.onclick = "";
showToast("Not supported", "Attachments are not supported by your Exchange server.");
} else if (Office.context.mailbox.item.attachments.length == 0) {
var testButton = document.getElementById("testButton");
testButton.onclick = "";
showToast("No attachments", "There are no attachments on this item.");
} else {
// Initalize a context object for the app.
// Set the fields that are used on the request
// object to default values.
serviceRequest = new Object();
serviceRequest.attachmentToken = "";
serviceRequest.ewsUrl = Office.context.mailbox.ewsUrl;
serviceRequest.attachments = new Array();
}
};
})();
function testAttachments() {
Office.context.mailbox.getCallbackTokenAsync(attachmentTokenCallback);
};
function attachmentTokenCallback(asyncResult, userContext) {
if (asyncResult.status == "succeeded") {
serviceRequest.attachmentToken = asyncResult.value;
makeServiceRequest();
}
else {
showToast("Error", "Could not get callback token: " + asyncResult.error.message);
}
}
function makeServiceRequest() {
var attachment;
xhr = new XMLHttpRequest();
// Update the URL to point to your service location.
xhr.open("POST", "https://localhost:8080/GetOutlookAttachments/AttachmentExampleService/api/AttachmentService", true);
xhr.setRequestHeader("Content-Type", "application/json; charset=utf-8");
xhr.onreadystatechange = requestReadyStateChange;
// Translate the attachment details into a form easily understood by WCF.
for (i = 0; i < Office.context.mailbox.item.attachments.length; i++) {
attachment = Office.context.mailbox.item.attachments[i];
attachment = attachment._data$p$0 || attachment.$0_0;
if (attachment !== undefined) {
serviceRequest.attachments[i] = JSON.parse(JSON.stringify(attachment));
}
}
// Send the request. The response is handled in the
// requestReadyStateChange function.
xhr.send(JSON.stringify(serviceRequest));
};
// Handles the response from the JSON web service.
function requestReadyStateChange() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
if (!response.isError) {
// The response indicates that the server recognized
// the client identity and processed the request.
// Show the response.
var names = "<h2>Attachments processed: " + response.attachmentsProcessed + "</h2>";
document.getElementById("names").innerHTML = names;
} else {
showToast("Runtime error", response.message);
}
} else {
if (xhr.status == 404) {
showToast("Service not found", "The app server could not be found.");
} else {
showToast("Unknown error", "There was an unexpected error: " + xhr.status + " -- " + xhr.statusText);
}
}
}
};
// Shows the service response.
function showResponse(response) {
showToast("Service Response", "Attachments processed: " + response.attachmentsProcessed);
}
// Displays a message for 10 seconds.
function showToast(title, message) {
var notice = document.getElementById("notice");
var output = document.getElementById('output');
notice.innerHTML = title;
output.innerHTML = message;
$("#footer").show("slow");
window.setTimeout(function () { $("#footer").hide("slow") }, 10000);
};
Please help me to get attachments from outlook mail and upload on my cloud server.
attachment._data$p$0 gives to attachment metadata. Get id from there and use getAttachmentContentAsync API to get the attachment content Documentation

AJAX Dynamic Buttons

Does anyone have suggestions on how to complete the following assignment? I've listed the instructions from the teacher below along with my JavaScript code. Thanks in advance!
Instructions:
The primary task is to dynamically generate the "genre" buttons that are currently hardcoded into the correlating HTML file.
The genre buttons should work the same way the hardcoded buttons currently work meaning they should have an event listener attached to them that should display podcasts from the ajax response that match the genre that was clicked.
JavaScript Code:
/**
* Ajax GET requester
*
*/
function get(url){
// Return a new promise.
return new Promise(function (resolve, reject){
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', 'js/data.json');
req.onload = function(){
// This is called even on 404 etc
// so check the status
if(req.status === 200){
// Resolve the promise with the response text
resolve(req.response);
}else{
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Make the request
req.send();
});
}
function get_podcasts(genre){
var url = 'js/data.json';
get(url).then(function (response){
var body = document.getElementById('mainContent');
response = JSON.parse(response);
if(response.results.length > 0){
body.innerHTML = '';
for(var i = 0; i < response.results.length; i++ ){
if(response.results[i].primaryGenreName === genre ){
var image = '<img src="' + response.results[i].artworkUrl100 + '">';
var image = document.createElement('img');
image.src = response.results[i].artworkUrl100;
body.appendChild(image);
body.innerHTML += '<div>' + response.results[i].trackName + '</div>' ;
}
}
}else{
body.innerHTML = 'No results found.';
}
console.log(response);
}, function (error){
console.log('No hits Found');
});
}
window.onload = function(){
//create an array with all button names
var genreNames = ['TV & Film', 'News & Politics', 'Society & Culture', 'Music', 'Hobbies'];
//loop through the array
for(var i = 0; i < genreNames.length; i++){
//create button element called "TV and Film" or whatever
var dynamicButtons = document.createElement('BUTTON');
var buttonText = document.createTextNode(genreNames);
//add it to the DOM (document)
dynamicButtons.appendChild(buttonText);
document.body.appendChild(dynamicButtons);
}
/*
for(i =0; i <= response.results.length; i++) {
for (key in response.results[i].primaryGenreName) {
if(response.results[i].primaryGenreName.hasOwnProperty(key)) {
output += '<li><button type="button">' + response.results[i].primaryGenreName + '</button></li>';
var update = document.getElementById('genres');
update.innerHTML = output;
}
}
}
*/
};

AJAX to submit to page using POST method

I have this piece of AJAX that validates the login credentials by sending the username and password via GET method. I want to update this code to use POST method, but I don't know where to start or what to change.
The reason I'm doing this is the data that will be sent to another page will be big and GET doesn't send it all.
This is the code I have:
function createObject()
{
var request_type;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer")
{
request_type = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
request_type = new XMLHttpRequest();
}
return request_type;
}
var http = createObject();
var usr;
var psw;
function login()
{
usr = encodeURI(document.getElementById('username').value);
psw = encodeURI(document.getElementById('password').value);
http.open('get', 'login.php?user='+usr+'&psw='+psw);
http.onreadystatechange = loginReply;
http.send(null);
}
function loginReply()
{
if(http.readyState == 4)
{
var response = http.responseText;
if(response == 0)
{
alert('Login failed! Verify user and password');
}
else
{
alert('Welcome ' + usr);
document.forms["doSubmit"].elements["usr"].name = "usr";
document.forms["doSubmit"].elements["usr"].value = usr;
document.forms["doSubmit"].elements["pwd"].name = "pwd";
document.forms["doSubmit"].elements["pwd"].value = psw;
document.forms["doSubmit"].action = location.pathname + "user/";
document.forms["doSubmit"].submit();
}
}
}
This code uses GET and send the parameters in the URL and waits for the reply. I want to send the parameters via POST due to size.
The data that will be sent is for a <textarea name='taData' id='taData'></textarea>
Change the line of code as described below:
From:
http.open('get', 'login.php?user='+usr+'&psw='+psw);
To:
http.open('post', 'login.php');
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
http.send('user=' + usr + '&psw=' + psw + '&tboxName=' + yourTextBoxValue);
More on the topic:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms757849(v=vs.85).aspx

ajax JSON dump as array

I have a simple ajax script which returns a json dump from the server:
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
function getIslandName() {
var islandGroup = document.getElementById("id_island_group").value;
var url = ".../find_island?island_group=" + escape(islandGroup);
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
function updatePage() {
if (request.readyState == 4)
if (request.status == 200)
var data = JSON.decode(request.responseText);
update(data);
//document.getElementById("ajax_response").innerHTML = request.responseText;
else if (request.status == 404)
alert("Request URL does not exist");
else
alert("Error: status code is " + request.status);
}
function update(data) {
for (var key in data) {
alert(data[key]);
}
}
The problem seems to be in the updatePage() function. If I uncomment this line:
//document.getElementById("ajax_response").innerHTML = request.responseText;
the responseText json dump is displayed as expected. e.g.:
["Foo Island", "Bar Island", "Darwin Island"]
Also if I construct a fresh data array within the updatePage() function like so:
function updatePage() {
var string = "Something something ajax";
if (request.readyState == 4)
if (request.status == 200)
var data=new Array();
data[0]="Foo Island";
data[1]="Bar Island";
data[2]="Darwin Island";
update(data);
}
The update() function works as expected and gives the expected alert output.
Any suggestions as to what I'm doing wrong will be much appreciated.

Control flow with XmlHttpRequest?

XmlHttpRequest works through callbacks. So how can I return a value? I tried to set a global variable, but that doesn't seem to be working.
var response = null; // contains the most recent XmlHttpRequest response
// loads the info for this username on the page
function loadUsernameInfo(username) {
getUserInfo(username);
var profile = response;
if (profile) {
// do stuff
}
else {
indicateInvalidUsername(username);
}
}
getUserInfo() can't return a result, because of the callback:
function getUserInfo(username) {
var request = createRequest();
request.onreadystatechange = userObjFromJSON;
var twitterURL = "http://twitter.com/users/show/" + escape(username) + ".json";
var url = "url.php?url=" + twitterURL;
request.open("GET", url, true);
request.send(null);
}
The callback:
function userObjFromJSON() {
if (this.readyState == 4) {
alert(this.responseText);
response = this.responseText;
}
}
How can I get the response back to loadUsernameInfo()?
You can do synchronous requests, though it is not recommended - the A is for Asynchronous... But the general idea to implement this correctly would be:
var response = null; // contains the most recent XmlHttpRequest response
// loads the info for this username on the page
function loadUsernameInfo(username) {
getUserInfo(username, onLoadUsernameComplete);
}
function getUserInfo(username, oncomplete) {
var request = createRequest();
request.__username = username;
request.onreadystatechange = oncomplete;
var twitterURL = "http://twitter.com/users/show/" + escape(username) + ".json";
var url = "url.php?url=" + twitterURL;
request.open("GET", url, true);
request.send(null);
}
function onLoadUsernameComplete(req) {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var profile = req.responseXML;
if (profile) {
// do stuff
}
else {
indicateInvalidUsername(req.__username);
}
}
}
}

Resources