Not sending XmlHttpRequest with only one parameter called "id" - javascript

I'm new to javascript. If I try to run this piece of code, the request doesn't gets sent.
function getObjectData(objectId)
{
var url = "FMDiag/getObjectData?id=" + objectId;
var xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.open("GET", url, true);
xmlHttpRequest.onload = function(e)
{
...
};
xmlHttpRequest.send();
}
If I change ?id= to something else, e.g. ?objectId=, the function works as expected.
Or if I add additional parameters to the request, it works again.
Strange though, ?id= works from form data sending.
Any ideas?

Related

convert LoadVars & sendAndLoad from actionscript to javascript

I am a beginning programmer and trying to convert a program in Actionscript to javascript.
So far I could do all the conversions I needed, but I am stuck on the following code below.
I understand that the variables fileName & test ID are sent to the script which is located at the url interfaceUrl + "operation=" + Test and the answer is stored back in lvReply.
Which code/function I would need in JavaScript to do the same.
I am looking at XMLHttpRequest but do not know if this is the right way to move forward. Any help in pointing me to the right direction would be appreciated.
var lv:LoadVars = new LoadVars();
lv.fileName = fileName;
lv.lpTestId = testId;
var lvReply:LoadVars = new LoadVars();
lv.sendAndLoad(interfaceUrl + "operation=" + Test, lvReply, "POST");
LoadVars just loads name / value pairs from the server, in the form of:
someText=testing&myVariable=123
For JavaScript, you can use:
XHR:
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
to load the data, and then:
URLSearchParams to parse them:
https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams
Here is some pseudo code to demonstrate:
let xhr = new XMLHttpRequest();
//load data, sending params to server via query string
xhr.open('GET', 'http://example.com/data?args1=boof&arg2=banana');
xhr.onload = function() {
if (xhr.status != 200) {
//check status code to see what happened
} else {
//data sent from server in the form of foo=bar&biff=bam
let data = xhr.response;
let params = URLSearchParams(data);
let foo = params.get(foo);
console.log(foo); // prints bar
}
};
xhr.onerror = function(err) {
//something went wrong
};
xhr.send();
A better solution would be just to send JSON from the server and parse it with JSON.parse()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
Note, in the example above, it is also sending data to the server. You can also do that using XHR (either via GET or POST).

XMLHttpRequest not calling controller

I was using this post to help me upload files to my MVC controller. jQuery ajax upload file in asp.net mvc For some reason the controller is never getting called. I would comment on the link but I don't have enough points for stackoverflow to let me comment on stuff. My javascript code is below, besides for changing a few things to use jquery is should have the same functionality. Any ideas? If more information is needed, just comment and I'll add whatever else I can. Thanks!
Javascript:
$("#btnSubmit").click(function () {
var formdata = new FormData();
var fileInput = document.getElementById('fileInput');
formdata.append(fileInput.files[0].name, fileInput.files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Index/Upload');
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText);
}
}
return false;
});
Edit: When looking at the console output on my browser I saw the it wasn't recognizing the action(Index) that I was putting in. It would recognize the controller(Upload) but I think that is because the current view was already in the controller. Any ideas how to fix the path input for the XMLHttpRequest?

Getting started with calling APIs via XMLHttpRequest

I've just started to learn how to use APIs, but I'm having a little bit of trouble understanding exactly how to utilize them.
I was able to write the following code thanks to some online documentation, but I have some questions about how to add to it:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London&mode=xml", false); xhr.send();
console.log(xhr);
Now, when I run this code in my browser and I open the console, I get a dropdown with a whole bunch of stuff under it. First of all, how can I get the code to display JUST the response? I want the console to display just the XML to show when I run my code. Second of all, how do I parse the XML? Is there any way to get a value from an XML element and assign it to a JavaScript variable?
Thanks!
What you are printing is the XMLHttpRequest object itself, while what you actually want is the response from the request you've made. To get the response, you use
xhr.responseXML;
Which is a object of the type document. (See the MDN docs).
To exhibit the code, you can just
console.log(xhr.responseXML);
But to actually work with the response, you'll probably want to do as Josh suggested, and request from the API a JSON-formatted response (instead of a XML-formatted one).
You will probably want to do that asyncronously, too (see this). The page has a more robust example. Let's adapt it to show London's temperature:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London&mode=json", true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText);
var response = JSON.parse(xhr.responseText);
console.log("Temperature(K): " + response.main.temp);
} else {
console.error(xhr.statusText);
}
}
};
xhr.onerror = function (e) {
console.error(xhr.statusText);
};
xhr.send(null);
Being async means that the xhr.onLoad function will be executed as soon as the response is received. Thus all of your code will be executed sequentially, and only when the response is received the onLoad will be executed.
You can get the response as a Document object.
Using your code above, you can reference xhr.responseXML and use the Document documentation to learn how to grab what data you need.
That dropdown is probably your browser formatting the response object in an interactive way for you.
xmlDoc=xhr.responseXML; will give you the actual resulting text
Alternatively: you could request a JSON object to make working with the data much easier.
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=London&mode=json", false); xhr.send();
var data= JSON.parse(xhr.responseText); //data is now a javascript object full of the API data
Note how the url now reads mode=json now.

Load page within javascript

Is there a method in javascript to load a page without actually show that page?
I want to load a php page which will handle the database insertion tasks.
Use AJAX to get/send data to the serverside?
Yes there is, you can use the XMLHttpRequest for this.
here is a example
function done() {
console.log(this.responseText); // The response from the server
};
var XHR = new XMLHttpRequest();
XHR.onload = done; // Set the onload function
XHR.open("get", "something.php", true); // Type & File
XHR.send(); // Send the request
Here is some documentation on that MDN XMLHttpRequest

Use XPCOM to upload file/image on webpage

I am using an example found here. Mozilla developers
I am interested in this example.
function upload(postUrl, fieldName, filePath)
{
var formData = new FormData();
formData.append(fieldName, new File(filePath));
var req = new XMLHttpRequest();
req.open("POST", postUrl);
req.onload = function(event) { alert(event.target.responseText); };
req.send(formData);
}
But I can't understand what goes where on this example. filePath is understandable but postUrl , fieldName I can find. I am working on image uploading on the page that has Drag and Drop zone for image uploading. How can I use this function to upload the image on my website?
Check out the FormData documentation and XMLHttpRequest documentation.
fieldName The name of the (form) field whose data is contained in value.
postUrl The URL to which to send the request.
You should have a server-side endpoint that responds to the upload request.
For example:
upload('http://mysite.com/uploader.php', 'fileField', 'path/to/my/file.jpg');
Then if you are using PHP on the server-side; you can access that field value on the server-side like this:
$my_files = $_FILES['fileField'];

Categories

Resources