Ajax request succeeds but result is empty - javascript

I am building a Google Chrome browser extension that uses $.ajax requests to send data from webpages to my server (currently hosted using localhost). The content_script.js file that is being executed in the context of the webpages (more on content scripts) that the extension has access to runs this code:
//note: encode64String is assigned earlier in the script...
$.ajax({
type: "POST",
url: "http://localhost:8888/quartzsite/uploadendpoint.php",
type: "jsonp",
data: {img: encode64String},
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(data){
console.log("The ajax request succeeded!");
console.log("The result is: ");
console.log(data);
},
error: function(){
console.log("The request failed");
}
});
The problem is that the Ajax request is succeeding but the data argument that it returns is empty...
The console looks like this after the code is run:
Currently the contents of the uploadedendpoint.php file are:
<?php
header("Access-Control-Allow-Origin: *");
echo 'This comes from php file'; die();
?>
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
</head>
<body>
The content of the document......
</body>
</html>
This means there should be at least something being returned in the data variable.
I have further confirmed that the request is succeeding because when I send the request to a broken url (i.e. uploaddddddendpoint.php) the code inside the $.ajax's error parameter is executed.
I have read similar questions like jQuery $.ajax response empty, but only in Chrome but to no avail...
UPDATE:
I have removed the invalid second type: "jsonp" parameter entirely and have added dataType: "text/html". I am now getting a failed ajax request each time the code is run.
UPDATE: Strangely changing dataType : "text/html" to dataType : "html" causes the ajax request to succeed but again with a blank data variable.
UPDATE: When using the dev toolkit to monitor the Network XHR these are the sent/response messages:
With regards to the flag of possible duplication to
Impossible to cross site ajax api calls in a chrome extension? I suggest otherwise! I have investigated that question and the problem does NOT seem to be the same.

Why do you have two type fields in your AJAX request? jsonp and POST.
$.ajax({
type: "POST", // OK
url: "http://localhost:8888/quartzsite/uploadendpoint.php",
type: "jsonp", // ???
// ...
});
UPDATE:
I think you should be using the relative path for the URL. Try changing your request to the following:
$.ajax({
type: "POST",
url: "/quartzsite/uploadendpoint.php",
dataType: "text/html",
data: {img: encode64String},
success: function(data){
console.log("The ajax request succeeded!");
console.log("The result is: ");
console.dir(data);
},
error: function(){
console.log("The request failed");
}
});
You can see I replaced the URL with /quartzsite/uploadendpoint.php. This may solve the problem... the absolute URL might signal a cross-domain request which is not what you're after.
Also, as a side note, it's unnecessary to set the contentType, since what you're setting it to is already the default value. If you were sending a JSON or XML, then you'd want to set the contentType.

Use "echo" instead of "return" while sending the response data to ajax.

Related

Why is res.sendfile() doesn't work when I call from jQuery ajax?

Issue:
The first ajax is working properly in the main.js, the second one is doing its job at first look but I think there might be a bug somewhere. I can reach the getProducts method after I click to the button.
The product_list.html file should appear on the browser screen, but it doesn't.
I get no error message on the front-end or the back-end.
This is what I noticed: After click to the button -> F12 -> Network -> products -> I can see here a status code: 200 and the product_list.html file content as response.
In case the POST ajax call succeeds and in the case I add: location.href = "/products";, the browser will load product_list.html
I use the get ajax call because i need to pass the jwt token in the req header. (I deleted the jwt authentication parts from the code below because I narrowed down the error to the $.ajax() and res.sendFile() relationship)
//routes.js
routes.get("/products", ProductController.getProducts);
//ProductController.js
var root = path.join(__dirname, '../../views');
module.exports = {
getProducts(req, res){
console.log("getProducts!"); //I can see in the console
res.sendFile("product_list.html", {root}) //It doesn't render the html
},
}
//main.js
$("#btn-login").click(function(){
$.ajax({
type: 'POST',
url: "http://localhost:8000/login",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({
"username": $("#login-user").val(),
"password": $("#login-pwd").val(),
}),
success: function(data){
if ($("#login-chkbx").is(':checked')){
$.ajax({
url: "http://localhost:8000/products",
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader("user", localStorage.getItem("user"));
},
});
}
}else{
console.log("Checkbox is not checked");
}
}
});
});
What causes the issue and how to solve it?
Thanks!
file should appear on the browser screen
No it does not and it should not. The file should be returned to the ajax function call in the success callback:
$.ajax({
url: "http://localhost:8000/products",
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader("user", localStorage.getItem("user"));
},
success: function (file) {
// The file is in the "file" variable above.
// Do whatever you want with it. For example you can replace
// the current page with the returned file:
document.body.innerHTML = file;
}
});
That is the whole point of AJAX - a mechanism for programmers to override the normal flow of HTTP requests that loads the response to the browser page. If it allows you to not load the response to the browser page it also means it will not automatically load the response to the browser page - because doing so will not allow you to not load the response.
If you want to automatically load the response then don't use ajax:
// Replace $.ajax(... with:
window.location.href = "http://localhost:8000/products";
However, this method does not allow you to set custom request header.
in your frontend code you do nothing with the GET /products response
the backend sendfile as the name says it just sends the file over to the requester. Being an ajax call, it must be rendered by the frontend code.
Add something like success: response => $('body').html(response)

jQuery cross domain ajax call - Interpreted as script but transferred with MIME type text/xml

Trying to make a REST web service call using an ajax call. Whenever I try to run it, I receive the error, Interpreted as script but transferred with MIME type text/xml. Here's my code ("website" is actual website where web service is):
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
function testCall() {
var webMethod = "website";
var un = 'un'
var pw = 'pw'
var parameters = "username=un&password=pw&change_ticket_number=CRQ000000011334&restuser=TEMPESP&restpass=restpw";
$.ajax({
url: webMethod,
type: 'Post',
data: parameters,
crossDomain: true,
username: un,
password: pw,
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
dataType: 'jsonp',
success: function(data) {
alert('Success: ' + data);
},
error: function(errorThrown){
alert('Try again ' + errorThrown);
}
});
}
I have been searching all over the web and this website for something like this but I haven't had any success.
I have initially had my dataType as "xml" as that's what the web services provdies but changed it to "jsonp" when I read about cross domain calls.
The parameters are what the web service is looking for. If I was to open an internet browser and put the url + parameters, it does show me the xml message.
I'm not sure how much control I have over the web service itself so my hope would be to figure out a way on how to translate this back to xml after jsonp successfully brings it over.
So the question remains, am I able to change my code in order to make this work, leaving the web service as is? If it's truly not possible, what needs to be done to the web service? Keeping in mind xml is being used.
Thank you for any help you can provide.
The JSONP data format is a JavaScript program consisting of a function call (to a function defined in the URL) with the requested data as the argument.
You are getting the error because you are making a JSONP request and getting XML.
Change the server so it returns JSONP or change the JavaScript so it expects XML (and also change the server so it gives your site permission to read the XML using CORS).

$.ajax Not Reporting Success Over SSL

I'm passing form data to a php script using jQuery's $.ajax call (CentOS 6.4) and the data is being successfully passed to the script and processed. The only issue is that the success message is not coming back. The connection eventually times out and is listed as 'canceled' in the console. I'm using SSL and both the source and destination are using https. The server error logs aren't showing anything I recognize as related.
Here's the AJAX:
$.ajax({
type: "POST",
url: "https://theurl.com/form.php",
data: dataString,
success: function() {
$('#form').html("<div id='message'></div>");
$('#message').html("<h1>Thanks!</h1>")
.append("<h2>We will be in touch.</h2>")
.hide()
.fadeIn(1500, function() {
$('#message').append("<img id='received' src='https://theurl/processed.png' />");
});
setTimeout(function(){
$('div#form').slideDown();
},5000);
}
});
return false;
});
And here's the only error that I think could hold meaning (though I doubt it, as I've heard this is indicative of illicit pings, but I thought the SSL may be causing it...):
client sent HTTP/1.1 request without hostname (see RFC2616 section 14.23): /w00tw00t.at.ISC.SANS.test0:)

jQuery AJAX Cross Domain with BASIC Authentication

I'm attempting to make use of the Beanstalk (beanstalkapp.com) API by pulling data into a webpage so people can view it without accessing my SVN.
What I'm doing to try and access it is by using an AJAX request through jQuery. The code is below, but I get an error each time, and can't return the data.
<script type="text/javascript">
$(document).ready(function() {
var tok = 'username' + ':' + 'password123';
hash = btoa(tok);
authInfo = "Basic " + hash;
$.ajax({
url: "http://username.beanstalkapp.com/api/changesets.json",
beforeSend: function (xhr) { xhr.setRequestHeader ("Authorization", authInfo); },
type: "GET",
async: false,
crossDomain: true,
dataType: "json",
success: function(html){
console.log(html);
},
error: function(html){
console.log('error');
}
});
});
</script>
If I access the URL straight through my browser (http://username.beanstalkapp.com/api/changesets.json) it works just fine and returns the json. However, I cannot get the AJAX to return it. Any help is appreciated. Thanks!
You will need to make proxy for cross-domain ajax requests.
Usual scenario looks like this:
Client send ajax request to server
Your server forwards request to external/remote server
Waiting on response from remote server
Parse and process response from remote server
Send response back to client
If you are using php you can send requests with curl, and it is pretty easy to implement. I have wrote article on this topic recently http://www.svlada.com/proxy-ajax-requests-curl-and-symfony-2/.
you cant get a json from other domain than yours. this is a security issue called same origin policy to get over it use JSONP not JSON.
Check this jsfiddle. The username and password is incorrect. Give the correct username and password and check it once again.

HTTP Error 414. The request URL is too long

I am using ckeditor to format some data inside my textarea
<textarea id="editorAbout" rows="70" cols="80" name="editorAbout"></textarea>
Now when i try to post this data using jQuery.ajax like this,
var about=escape( $("#editorAbout").text());
$.ajax({
type: "POST",
url: "../Allcammand.aspx?cmd=EditAboutCompany&about="+about,
type:"post",
async: false ,
success: function(response){
},
error:function(xhr, ajaxOptions, thrownError){alert(xhr.responseText); }
});
I get the error
HTTP Error 414. The request URL is too long.
I am getting the error here: http://iranfairco.com/example/errorLongUrl.aspx
Try clicking on the Edit Text button at the bottom left of that page.
Why is this happening? How can I solve it?
According to this question the maximum practical length of a URL is 2000 characters. This isn't going to be able to hold a massive Wikipedia article like you're trying to send.
Instead of putting the data on the URL you should be putting it in the body of a POST request. You need to add a data value to the object you're passing to the ajax function call. Like this:
function editAbout(){
var about=escape( $("#editorAbout").text());
$.ajax({
url: "Allcammand.aspx?cmd=EditAboutCompany&idCompany="+getParam("idCompany"),
type:"post",
async: false,
data: {
about: about
},
success: function(response){
},
error:function(xhr, ajaxOptions, thrownError){alert(xhr.responseText); ShowMessage("??? ?? ?????? ??????? ????","fail");}
});
}
For me, changing type:"get" to type:"post" worked, as get reveals all queries and hence make it bigger url.
Just change type from get to post.
This should help. :)
In my case, there was a run-time error just before the post call. Fixing it resolved the problem.
The run-time error was trying to read $('#example').val() where $('#example') element does not exist (i.e. undefined).
I'm sure this will, certainly, help someone.
In my case, the error was raised even though I was using 'POST' and the call to the server was successful. It turned to be that I was missing the dataType attribute...strange but now it works
return $.ajax({
url: url,
type: 'POST',
dataType: 'json',
data: JSON.stringify(data)
})
A bit late to the party, but I got this 414, while using POST. It turned out is was a max path length in windows causing this error. I was uploading a file, and the actual request length was just fine (using post). But when trying to save the file, it exceeded the default 260 char limit in windows. This then resulted in the 414, which seems odd. I would just expect a 501. I would think 414 is about the request, and not the server handling.

Categories