I am trying to upload a file into my amazon account using the dojo.io.send.However, it's failing to do so .
This is error which i get to see when i run through the firebug.
<Error>
<Code>InvalidArgument</Code>
<Message>Bucket POST must contain a field named 'key'. If it is specified,
please check the order of the fields.</Message>
<ArgumentValue></ArgumentValue>
<ArgumentName>key</ArgumentName>
I figured out the reason and apparently the "Key" field is below to the
"File" field because of that it is ignoring below ones and throwing up the
error .
In order to rectify this issue, i need to have dojo.io.send() to send the
param's list in the following way:-
key uploads/${filename}
AWSAccessKeyId
policy
signature
Content-Type plain/text
file
I tried my luck by playing with the below code but it always put the file
field on the top.
I would appreciate if anybody can help me out in changing the sequence.
Code Snippet:-
var jsonpArgs =
{
url: "https://s3.amazonaws.com/<Bucketname>",
form : dojo.byId("Myform"),
//MyForm has an attribute
//as file which takes the file name from the user to upload.
handleAs: "json",
content:
{
"key":"*******",
"AWSAccessKeyId":"****",
"policy" :"***********",
"signature":"*******",
"Content-Type":"plain/text"
},
error: function(error)
{
},
};
dojo.io.iframe.send(jsonpArgs);
},
Appreciated,
The cause is that Dojo just iterate all the properties in the JSON object and generate the POST request body from it. Since the order of iteration is undetermined, you can not guarantee that the key property always is the first one.
The solution is to generate the POST body yourself. You can get the POST body string using:
"key=" + encodeURIComponent(key) + "&" + dojo.objectToQuery({AWSAccessKeyId : "", policy :""})
By doing this, the key is always the first one in the post body.
When sending the request, do not use content property, use rawBody instead. If you're using older version of Dojo, maybe you can use dojo.rawXhrPost and using postData property in the request.
Related
I've tried many things and there's no way, always appears this error
I tried to use only one option to see if passed, changed the call of jquery, but not.
I looked in various places on the internet about this error, but could not solve or understand why it is happening.
On my pc using EasyPHP works perfectly, but when I put online does not work.
Syntax Error: unexpected token <
Here's my code:
$(function(){
$('#salvar').click(function(){
var key = 'salvar';
var title = $('#title').val();
var opcao1 = $('#opcao1').val();
var opcao2 = $('#opcao2').val();
var opcao3 = $('#opcao3').val();
var opcao4 = $('#opcao4').val();
var opcao5 = $('#opcao5').val();
var opcao6 = $('#opcao6').val();
if(title.length > 0){
if(opcao2.length > 0){
$('#resposta').removeClass().html('Salvando a enquete...<br clear="all"><br><img src="images/switch-loading.gif" />');
$.ajax({
type : 'POST',
url : 'funcoes/enquete_adm.php',
dataType : 'json',
data: {key:key,title:title,opcao1:opcao1,opcao2:opcao2,opcao3:opcao3,opcao4:opcao4,opcao5:opcao5,opcao6:opcao6},
success : function(data){
if(data.sql == 'ok'){
$('#resposta').addClass('success-box').html('Enquete Salva!').fadeIn(1000);
$('#control').fadeOut();
}else if(data.sql == 'error'){
$('#resposta').addClass('info-box').html('Ops, aconteceu um erro. Por favor, tente novamente').fadeIn(1000);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest " + XMLHttpRequest[0]);alert(" errorThrown: " + errorThrown);alert( " textstatus : " + textStatus);
}
});
}else{
$('#resposta').addClass('warning-box').html('É necessário no mínimo duas opções');
};
}else{
$('#resposta').addClass('warning-box').html('Coloque a pergunta da enquete');
};
return false;
});
}); // End
This usually happens when you're including or posting to a file which doesn't exist.
The server will return a regular html-formatted "404 Not Found" enclosed with
'<html></html>'
tags. That first chevron < isn't valid js nor valid json, therefore it triggers an unexpected token.
What if you try to change 'funcoes/enquete_adm.php' to an absolute url, just to be sure?
EDIT (several years later)
The root cause might not always come from 404 errors. Sometimes you can make a request to an API and receive HTML formatted errors. I've stumbled to a couple of cases in which the API endpoint should have returned
{
error: "you must be authenticated to make this request"
}
With header 401. And instead I got
<html>You must be authenticated to make this request</html>
With header 200.
Given the header is 200 you can't tell the request has failed beforehand, and you're stuck to try and JSON.parse the response to check if it's valid.
You have unnecessary ; (semicolons):
Example here:
}else{
$('#resposta').addClass('warning-box').html('É necessário no mínimo duas opções');
};
The trailing ; after } is incorrect.
Another example here:
}else{
$('#resposta').addClass('warning-box').html('Coloque a pergunta da enquete');
};
I suspect you're getting text/html encoding in response to your request so I believe the issue is:
dataType : 'json',
try changing it to
dataType : 'html',
From http://api.jquery.com/jQuery.get/:
dataType
Type: String
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).
The error SyntaxError: Unexpected token < likely means the API endpoint didn't return JSON in its document body, such as due to a 404.
In this case, it expects to find a { (start of JSON); instead it finds a < (start of a heading element).
Successful response:
<html>
<head></head>
<body>
{"foo": "bar", "baz": "qux"}
</body>
</html>
Not-found response:
<html>
<head></head>
<body>
<h1>Not Found</h1>
<p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>
</body>
</html>
Try visiting the data endpoint's URL in your browser to see what's returned.
I had a similar problem, and my issue was that I was sending javascript to display console messages.
Even when I looked at the file in my browser (not through the application) it showed exactly as I expected it to (eg the extra tags weren't showing), but there were showing in the html/text output and were trying to be parsed.
Hope this helps someone!
I suspect one of your scripts includes a source map URL. (Minified jQuery contains a reference to a source map, for example.)
When you open the Chrome developer tools, Chrome will try to fetch the source map from the URL to aid debugging. However, the source map does not actually exist on your server, but you are instead sent a regular 404 page containing HTML.
This error can also arise from a JSON AJAX call to a PHP script that has an error in its code. Servers are often set up to return PHP error information formatted with html markup. This response is interpreted as invalid JSON, resulting in the "unexpected token <" AJAX error.
To view the PHP error using Chrome, go to the Network panel in the web inspector, click the PHP file listed on the left side, and click on the Response tab.
When posting via ajax, it's always a good idea to first submit normally to ensure the file that's called is always returning valid data (json) and no errors with html tags or other
<form action="path/to/file.php" id="ajaxformx">
By adding x to id value, jquery will not process it.
Once you are sure everything is fine then remove the x from id="ajaxform" and the empty the action attribute value
This is how I sorted the same error for myself just a few minutes ago :)
I was also having syntax error: unexpected token < while posting a form via ajax. Then I used curl to see what it returns:
curl -X POST --data "firstName=a&lastName=a&email=array#f.com&pass=aaaa&mobile=12345678901&nID=123456789123456789&age=22&prof=xfd" http://handymama.co/CustomerRegistration.php
I got something like this as a response:
<br />
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>3</b><br />
<br />
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>4</b><br />
<br />
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>7</b><br />
<br />
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>8</b><br />
So all I had to do is just change the log level to only errors rather than warning.
error_reporting(E_ERROR);
i checked all Included JS Paths
Example
Change this
<script src="js/bootstrap.min.js" type="text/javascript"></script>
TO
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" type="text/javascript"></script>
Removing this line from my code solved my problem.
header("Content-Type: application/json; charset=UTF-8");
Just gonna throw this in here since I encountered the same error but for VERY different reasons.
I'm serving via node/express/jade and had ported an old jade file over. One of the lines was to not bork when Typekit failed:
script(type='text/javascript')
try{Typekit.load();}catch(e){}
It seemed innocuous enough, but I finally realized that for jade script blocks where you're adding content you need a .:
script(type='text/javascript').
try{Typekit.load();}catch(e){}
Simple, but tricky.
Just ignore parameter passing as a false in java script functions
Ex:
function getCities(stateId,locationId=false){
// Avoid writting locationId= false kind of statements
/*your code comes here*/
}
Avoid writting locationId= false kind of statements, As this will give the error in chrome and IE
This happened to me with a page loaded in via an iframe. The iframe src page had a 404 script reference. Obviously I couldn't find the script reference in the parent page, so it took me a while to find the culprit.
make sure you are not including the jquery code between the
< script >
< /script >
If so remove that and code will work fine, It worked in my case.
If you are running the NVM on your system, you must check the node version before starting the server.
I'm trying to load a JSON file by link and then align data (like title, date etc) to variables so I can use them. Right now, I don't care about variables. I just want to alert() them but something seems like I'm doing it wrong, alert returns nothing!
I use JSfidle to run the code. The code is this:
var JSON_unparsed = $.getJSON('http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json') ;
var JSON = JSON.parse(JSON_unparsed) ;
alert(JSON.feed.entry[0].title.$t) ;
The URL I want to parse is: http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json
and here you can see the JSON how is structured if that can help you:
You can use JSONP for this:
Update, for better understanding how to work with returned JSON.
var id, title;
$.ajax({
url: 'http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json',
jsonp: "callback",
dataType: "jsonp"
}).done(function(r){
// r is returned JSON
for(var i in r)
// for ex ID is this
id = r[i].id.$t;
// and title
title = r[i].title.$t;
// and so on, check the json, I mean check the browser console by hitting F12, below code will print the whole JSON
console.log(r[i]);
});
Codepen link: http://codepen.io/m-dehghani/pen/grXrrp?editors=0010
In addition to adeneo's reply, in your code, JSON_unparsed variable is holding something called (differed or promise object), this object might be holding the data inside it,but you are using the wrong way to pull it out. in order for you to get it out, you need to call (.done()) function, see the below:
var JSON_unparsed = $.getJSON('http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json').done(function(json){
console.log(json);
console.log(json.feed.entry[0].title.$t);
});
aside from that, if you got an error with something like this:
XMLHttpRequest cannot load http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json&_=1459788714707. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://stackoverflow.com' is therefore not allowed access.
it means that you are not allowed to call this API/URL from your current domain.
One more thing, if you are using getJSON method, there is no need to parse the returned data, jquery will parse it for you
I've tried many things and there's no way, always appears this error
I tried to use only one option to see if passed, changed the call of jquery, but not.
I looked in various places on the internet about this error, but could not solve or understand why it is happening.
On my pc using EasyPHP works perfectly, but when I put online does not work.
Syntax Error: unexpected token <
Here's my code:
$(function(){
$('#salvar').click(function(){
var key = 'salvar';
var title = $('#title').val();
var opcao1 = $('#opcao1').val();
var opcao2 = $('#opcao2').val();
var opcao3 = $('#opcao3').val();
var opcao4 = $('#opcao4').val();
var opcao5 = $('#opcao5').val();
var opcao6 = $('#opcao6').val();
if(title.length > 0){
if(opcao2.length > 0){
$('#resposta').removeClass().html('Salvando a enquete...<br clear="all"><br><img src="images/switch-loading.gif" />');
$.ajax({
type : 'POST',
url : 'funcoes/enquete_adm.php',
dataType : 'json',
data: {key:key,title:title,opcao1:opcao1,opcao2:opcao2,opcao3:opcao3,opcao4:opcao4,opcao5:opcao5,opcao6:opcao6},
success : function(data){
if(data.sql == 'ok'){
$('#resposta').addClass('success-box').html('Enquete Salva!').fadeIn(1000);
$('#control').fadeOut();
}else if(data.sql == 'error'){
$('#resposta').addClass('info-box').html('Ops, aconteceu um erro. Por favor, tente novamente').fadeIn(1000);
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("XMLHttpRequest " + XMLHttpRequest[0]);alert(" errorThrown: " + errorThrown);alert( " textstatus : " + textStatus);
}
});
}else{
$('#resposta').addClass('warning-box').html('É necessário no mínimo duas opções');
};
}else{
$('#resposta').addClass('warning-box').html('Coloque a pergunta da enquete');
};
return false;
});
}); // End
This usually happens when you're including or posting to a file which doesn't exist.
The server will return a regular html-formatted "404 Not Found" enclosed with
'<html></html>'
tags. That first chevron < isn't valid js nor valid json, therefore it triggers an unexpected token.
What if you try to change 'funcoes/enquete_adm.php' to an absolute url, just to be sure?
EDIT (several years later)
The root cause might not always come from 404 errors. Sometimes you can make a request to an API and receive HTML formatted errors. I've stumbled to a couple of cases in which the API endpoint should have returned
{
error: "you must be authenticated to make this request"
}
With header 401. And instead I got
<html>You must be authenticated to make this request</html>
With header 200.
Given the header is 200 you can't tell the request has failed beforehand, and you're stuck to try and JSON.parse the response to check if it's valid.
You have unnecessary ; (semicolons):
Example here:
}else{
$('#resposta').addClass('warning-box').html('É necessário no mínimo duas opções');
};
The trailing ; after } is incorrect.
Another example here:
}else{
$('#resposta').addClass('warning-box').html('Coloque a pergunta da enquete');
};
I suspect you're getting text/html encoding in response to your request so I believe the issue is:
dataType : 'json',
try changing it to
dataType : 'html',
From http://api.jquery.com/jQuery.get/:
dataType
Type: String
The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).
The error SyntaxError: Unexpected token < likely means the API endpoint didn't return JSON in its document body, such as due to a 404.
In this case, it expects to find a { (start of JSON); instead it finds a < (start of a heading element).
Successful response:
<html>
<head></head>
<body>
{"foo": "bar", "baz": "qux"}
</body>
</html>
Not-found response:
<html>
<head></head>
<body>
<h1>Not Found</h1>
<p>The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.</p>
</body>
</html>
Try visiting the data endpoint's URL in your browser to see what's returned.
I had a similar problem, and my issue was that I was sending javascript to display console messages.
Even when I looked at the file in my browser (not through the application) it showed exactly as I expected it to (eg the extra tags weren't showing), but there were showing in the html/text output and were trying to be parsed.
Hope this helps someone!
I suspect one of your scripts includes a source map URL. (Minified jQuery contains a reference to a source map, for example.)
When you open the Chrome developer tools, Chrome will try to fetch the source map from the URL to aid debugging. However, the source map does not actually exist on your server, but you are instead sent a regular 404 page containing HTML.
This error can also arise from a JSON AJAX call to a PHP script that has an error in its code. Servers are often set up to return PHP error information formatted with html markup. This response is interpreted as invalid JSON, resulting in the "unexpected token <" AJAX error.
To view the PHP error using Chrome, go to the Network panel in the web inspector, click the PHP file listed on the left side, and click on the Response tab.
When posting via ajax, it's always a good idea to first submit normally to ensure the file that's called is always returning valid data (json) and no errors with html tags or other
<form action="path/to/file.php" id="ajaxformx">
By adding x to id value, jquery will not process it.
Once you are sure everything is fine then remove the x from id="ajaxform" and the empty the action attribute value
This is how I sorted the same error for myself just a few minutes ago :)
I was also having syntax error: unexpected token < while posting a form via ajax. Then I used curl to see what it returns:
curl -X POST --data "firstName=a&lastName=a&email=array#f.com&pass=aaaa&mobile=12345678901&nID=123456789123456789&age=22&prof=xfd" http://handymama.co/CustomerRegistration.php
I got something like this as a response:
<br />
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>3</b><br />
<br />
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>4</b><br />
<br />
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>7</b><br />
<br />
<b>Warning</b>: Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>8</b><br />
So all I had to do is just change the log level to only errors rather than warning.
error_reporting(E_ERROR);
i checked all Included JS Paths
Example
Change this
<script src="js/bootstrap.min.js" type="text/javascript"></script>
TO
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" type="text/javascript"></script>
Removing this line from my code solved my problem.
header("Content-Type: application/json; charset=UTF-8");
Just gonna throw this in here since I encountered the same error but for VERY different reasons.
I'm serving via node/express/jade and had ported an old jade file over. One of the lines was to not bork when Typekit failed:
script(type='text/javascript')
try{Typekit.load();}catch(e){}
It seemed innocuous enough, but I finally realized that for jade script blocks where you're adding content you need a .:
script(type='text/javascript').
try{Typekit.load();}catch(e){}
Simple, but tricky.
Just ignore parameter passing as a false in java script functions
Ex:
function getCities(stateId,locationId=false){
// Avoid writting locationId= false kind of statements
/*your code comes here*/
}
Avoid writting locationId= false kind of statements, As this will give the error in chrome and IE
This happened to me with a page loaded in via an iframe. The iframe src page had a 404 script reference. Obviously I couldn't find the script reference in the parent page, so it took me a while to find the culprit.
make sure you are not including the jquery code between the
< script >
< /script >
If so remove that and code will work fine, It worked in my case.
If you are running the NVM on your system, you must check the node version before starting the server.
I encountered the strangest thing today while I was trying to filter image data from a string of html that I download through an AJAX request (I use https://github.com/padolsey/jQuery-Plugins/blob/master/cross-domain-ajax/jquery.xdomainajax.js to do so).
I noticed that I was getting a 404 on an image that it was trying to download. After looking at the initialiser stack, it appears that the image is inside the html that my AJAX pulls back. Here is the relevant stack:
b.extend.buildFragment # jquery-1.9.1.min.js:4
b.extend.parseHTML # jquery-1.9.1.min.js:3
b.fn.b.init # jquery-1.9.1.min.js:3
b # jquery-1.9.1.min.js:3
$.ajax.success # main.js:86
My code in main.js looks like this:
function generateAlbumHTML(album)
{
$.ajax({
url: album.data.url,
type: 'GET',
success: function(data)
{
var albumHtmlStr = "";
var images = $(data.responseText).find('#image-container .zoom');
$.each(images, function(i, item)
{
album.data.url = $(item).attr('href');
albumHtmlStr += generateHTML(album);
});
return albumHtmlStr;
}
});
}
It appears that the culprit is line 86 where I do:
var images = $(data.responseText).find('#image-container .zoom');
This causes JQuery to parse the HTML and start loading unwanted images and data from the HTML.
Here is a link to the html that gets pulled back by the ajax request as data.responseText: http://pastebin.com/hn4jEgAA
Anyway, am I doing something wrong here? How can I filter and find the data I want from this string without loading things such as unwanted images and other data?
What causes the "parsing" is this:
$(data.responseText)
This is actually you, telling jQuery to create HTML structure using the string you provided in data.responseText.
If you want to find things in this string, which is the HTML in response to your GET request, then you have to use one of the corresponding String methods:
String instances methods
It should be noted, however, that what you are trying to do is quite unorthodox, since parsing HTML on the client to retrieve information is not the best of approaches.
The better way would be to either use the receieved HTML as is (provided it is from a trusted source or you sanitize it properly), or to receive raw data in JSON form and process that data (while creating corresponding HTML by yourself) in your code.
UPDATE
Additional ways are presented in jQuery ajax method
For instance, you can use dataFilter setting or some such to sanitize your response.
I am new to the web development world and I would like to be able to connect an HTML page to a web api through . and I was really not successful in this.
I followed this tutorial to be able to make this connection : http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
All I need is to send some inputs from an HTML page to a web api that takes these parameters and returns an object
I am using this code
$.getJSON("api/GeneratorController/setparameters/"+firstparameter+"/"+secondparameter+"/"+thirdparameter+"/"+fourthparameter+"/"+fifthparameter+"/"+sixthparameter,
function (data) {
alert(data); //never comes here
}).fail(function (jqXHR, textStatus, err) {
alert("All checks are correct, image was not generated. jqXHR = " + jqXHR.valueOf() + " textStatus=" + textStatus + " Error" + err);
});
it always goes into the fail portion , I attached the alert message that comes out of it
Any Reason why it is doing this ?
#smartmeta (I changed the typo , thanks) I followed your advice and here is the output of the alert (as expected , values that I have inserted are displayed):
Your url needs to start with your domain, not 'api/generatorcontroller/...'. If you are developing locally, something like http://localhost:[port]/api/generatorController/....
Also, webApi maps to url verbs, (get, post, put, delete..), not functions like setparameters, unless you have a [name=setparameters] above your get() function.
Also, I am pretty sure you don't have a route setup to handle the url with all those parameters. What you want to look at, as it seems your using jQuery, is jQuery.get documentation. The second example near the bottom shows where to place parameters. WebAPI will check for them in the body if they are not in the query string. so it would end up looking like:
$.getJSON("http://"+window.location.host+"/api/GeneratorController/setparameters", {parameter1: parameter1, parameter2:parameter2 ...});
Well, the first thing to check is to make sure that your server-side function is returning the values you expect. You can do this with Chrome's developer tools or with the Firebug Firefox extension, and I think IE10 has something equivalent, too. Go to the "net" tab, find the request corresponding to your API call, and take a look at what the server responded with.
Please add the line
alert("api/GeneratorController/setparameters/"+firstparemeter+"/"+secondparameter+"/"+thirdparameter+"/"+fourthparameter+"/"+fifthparameter+"/"+sixthparameter)
Then call your script and take the output of the alert into a browser. Then check if your application Handels that route.
By the way I think you have a typo. I guess it should be firstparameter.
I assume you would like to do
"api/GeneratorController?foo=Bar
But when you are new to this, I would suggest that you first try the example like it is. And After that you can start changing setails.
So I found what was the problem with my code
Two things :
1- I shouldn't use the word "Controller" when I call my API ,it should be api/Generator/...
2- the function name needs to start with "get" and not "set" since it "gets" the return value from the api
Thanks everyone!