XMLhttprequest not posting (new to it) - javascript

I am trying to send data from javascript to a php page using xmlhttprequests.
It is just like sending form data, eventhough I have copied the examples exactly, it doesnt work.
I know the problem lays with the xmlhttprequest since I have tried sending the same data using an html form with POST and that works fine. So the PHP works.
the errors I get using my code are:
POST http://localhost/thissite/post 404 (Not Found)
Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
The current file structure I am using equals:
index.php and store.php in the root and than a folder called js with init.js
function sendData() {
var xmlhttp,
url = "http://localhost/thissite/store.php";
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
} else {
// code for old IE browsers
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("post", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("sitetarget=/thissite/&buttontarget=firstbutton&amount=2");
}
This function is in my init.js file which is linked on my index.php page.
I have tried changing the used URL to:
store.php
/store.php
./store.php
../store.php
http://localhost/store.php
But I think the URL I use should be correct since that is the url I get send to when I post the form. It is also the same as multiple examples I found in questions posted on here and those users didn't have the same errors as me. This is probably me misunderstanding but I am eager to find out what the problem is with my code before I throw my computer out of the window or pull my last hair out.
Thank you for answering if you do!

Related

Request plain text file in javascript from URL?

I started a blog recently and coded it by hand. It is a static, CSS/HTML5 website. Upon sharing it with friends, I realized that when I would update it via FTP, it would be cached already by their browsers. I decided that I would keep all of my blog posts on new pages and then create a landing page that would somehow determine the newest post and forward users there after they clicked an enter button or something like that.
I was able to create a button that could forward them to a specific link, but I want to create a script that will always forward them to the newest page. So I created a file called 'getLatest.json' and uploaded it to an 'api' subfolder of my site. I then tried to use an XMLHttpRequest to load it:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
window.location = "http://latestBlogPost.com" +
xhttp.responseText.today;
//Today is a parent in the object returned.
}
};
xhttp.open("POST", "http://myWebsite.com/api/getLatest.json", true);
xhttp.send();
}
But that didn't work. The response was a null string. I tried using jquery to no avail.
I tried uploading a file called getLatest.html which contained the url in plaintext. That didn't work either.
tl;dr: Is there some way that I can get plaintext from a URL's html content?
edit: getLatest.json and getLatest.html contain a link to the newest blog post.
There are couple of ways to do this.
First your code is not working because you are using a "POST" it should be "GET", if you do that it will work.
Second easiest way is to create a java script file with variable declared and reference that file to your website
<script type="text/javascript" src="http://your javascript file"> </script>
This file contains your variable like this
var latestBlog = "http://....";
in your code use this variable. No more code required. but as i mentioned earlier if you change your HTTP Verb to get your code will work

How to add header data in XMLHttpRequest when using formdata?

I'm trying to implement a file upload API, given here :
Mediafire file Upload
I am successfully able to upload the Post data & Get data, but have no clue how to send the x-filename attribute, which is meant to be Header data as given in API guide.
My Code :
xmlhttp=new XMLHttpRequest();
var formData = new FormData();
formData.append("Filedata", document.getElementById("myFile").files[0]);
var photoId = getCookie("user");
// formData.append("x-filename", photoId); //tried this but doesn't work
// xmlhttp.setRequestHeader("x-filename", photoId); //tried this too (gives error) [edited after diodeous' answer]
xmlhttp.onreadystatechange=function()
{
alert("xhr status : "+xmlhttp.readyState);
}
var url = "http://www.mediafire.com/api/upload/upload.php?"+"session_token="+getCookie("mSession")+"&action_on_duplicate=keep";
xmlhttp.open("POST", url);
// xmlhttp.setRequestHeader("x-filename", photoId); //tried this too, doesnt work. Infact nothing gets uploaded on mediafire. [edited after apsillers' answer]
// cant get response due to same origin policy
xmlhttp.send(formData);
Your error
InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable
appears because you must call setRequestHeader after calling open. Simply move your setRequestHeader line below your open line (but before send):
xmlhttp.open("POST", url);
xmlhttp.setRequestHeader("x-filename", photoId);
xmlhttp.send(formData);
Use: xmlhttp.setRequestHeader(key, value);
Check to see if the key-value pair is actually showing up in the request:
In Chrome, found somewhere like: F12: Developer Tools > Network Tab > Whatever request you have sent > "view source" under Response Headers
Depending on your testing workflow, if whatever pair you added isn't there, you may just need to clear your browser cache. To verify that your browser is using your most up-to-date code, you can check the page's sources, in Chrome this is found somewhere like:
F12: Developer Tools > Sources Tab > YourJavascriptSrc.js and check your code.
But as other answers have said:
xhttp.setRequestHeader(key, value);
should add a key-value pair to your request header, just make sure to place it after your open() and before your send()

How to receive response on client side?

I have this form to upload an xml file to server, I am using fiddler to monitor each req and resp. So the server sends me a small xml and i would like to receive it in my javascript as XMLHttpRequest makes it happen
Note: I am uploading a file so enctype="multipart/form-data"
var client;
var url_action = "/csm/create.action";
var dataString;
if (window.XMLHttpRequest) {
client = new XMLHttpRequest();
} else {
client = new ActiveXObject("Microsoft.XMLHTTP");
}
if (client.readyState == 4 && client.status == 200) {
alert(client.responseTest);
}
client.open("POST", url_action, true);
client.setRequestHeader("enctype", "multipart/form-data");
client.send();
My question is how can i receive the response from server side to JS variable. In the above code XMLHttpRequest i don't think i can send a multipart request (file upload). So any alternative is welcome. Whichever solution provides me a response is good.
Here is what i am doing, to submit the form. Thanks :)
var url_action="/csm/create.action";
$('#mainForm').attr('action', url_action);
$('#mainForm').submit();
Updated with solution
$(data).find('com\\.abc\\.db\\.ConfigInfo').each(function(){
cfgid=$(this).find('cfgId').text();
cfgname=$(this).find('cfgName').text();
filename=$(this).find('fileName').text();
timestamp=$(this).find('updateDate').text();
alert(cfgid+", "+cfgname+", "+filename+", "+timestamp);
});
You have jQuery available so don't ever create XHR objects manually.
Besides that, you cannot use AJAX for file uploads unless you don't care about compatibility with certain browsers.
Last but not least, you want to use the jQuery form plugin which will automatically fallback to a hidden iframe and a regular form if there is a file input in the form.
Note that you need to wrap your JSON response in <textarea></textarea> for it to work properly though. See http://jquery.malsup.com/form/#file-upload for details. If you want to return XML you don't need to wrap it though - it should work fine without any server-side changes.

Can't figure out how to do XMLHttpRequest to google app engine

I'm trying to do a simple POST from a javascript (google chrome extension) to my google app
I can see that the HTTP POST is indeed sent to the GAE server, but I can't figure how to transfer a simple text string, and use it in the google app.
The goal: send a string from the javascript with xmlhttpRequest, show this string on google-app webpage.
Here's the code of the javascript:
function onRequest(request, sender, sendResponse) {
var url = request;
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://myapp.appspot.com");
xhr.send(url);
// Return nothing to let the connection be cleaned up.
sendResponse({});
};
Here's how I deal with the post in the server side:
def post(self):
url1 = str(self.request.get('url1'))
self.response.headers['Content-Type'] = 'text/html'
self.response.out.write('<p>URL is: %s</p>' % url1)
When I look at the POST response I see
<p>URL is: </p>
where is the var url that was sent?
I got it to work, in a different way. Instead of XMLHttpRequest, I used jquery:
$.post("http://myapp.appspot.com", { url1: request});
and it worked :)
BTW, I also discovered that if you want the chrome extension's html to use jquery, you need to do
<script src="jquery-1.5.1.js"></script>
<script> your code here </script>
(I'm sure it's basic for you guys but fresh for me :)
The content you include with xhr.send() will be in self.request.body, if it's not specified in CGI format. For your simple test, you might also try xhr.send("url1=" + request).

How to load local JSON files in Javascript

I'm writing a web app (well, actually it will eventually be an OS X Dashboard widget, but I decided to prototype it first as a simple web page) that needs to load some initializing data from a local JSON file. My code looks like this:
function loadDatos() {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'datos.json', true);
xobj.onReadyStateChange = function () {
if (xobj.readyState == 4) {
var jsonTexto = xobj.responseText;
ProcessTheData(jsonTexto);
}
}
xobj.send(null);
}
The function get called from an onLoad() event in the HTML file's BODY tag. Now, from what I see when debugging, the function gets executed, but the onReadytStateChange event handler never gets called.
What should I do? I thought it was a bit odd to use a XMLHttpRequest to access a local file, but the new tutorials I've seen that deal with this issue seem to say that it should work (the 99% of docs I've seen talk about how to load JSON from a remote server, not from a local file).
I'm testing using Firefox 3.6.10, but I've also tried with Safari 4.
onreadystatechange property has no capital letters. See: MDC XMLHttpRequest
Unless we add extension .json and MIMETYPE application\json, IIS will throw an error.
See here: http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/cd72c0dc-c5b8-42e4-96c2-b3c656f99ead.mspx?mfr=true

Categories

Resources