jQuery form Plugin - javascript

I am trying to upload and submit through AJAX a form and I found jQuery.form plugin http://jquery.malsup.com/form/, here is my code :
$("#submitSlide").click(function(){
var options = {
success: function(data) {
console.log(data);
},
error : function( jqXHR , textStatus , errorThrown ){
console.log( ' broked ' , jqXHR , textStatus , errorThrown );
} ,
dataType: 'html',
type: 'POST',
url: 'http://www.slideshare.net/api/1/upload_slideshow'
};
$('#ssuploadform').ajaxSubmit(options);
return false;
});
But I am getting an error like this :
>>[jquery.form] Server abort: Error: Permission denied to access property 'document' (Error)
>>[jquery.form] cannot access response document: Error: Permission denied to access property 'document'
>>[jquery.form] aborting upload... aborted
DO you have any idea how to fix this ?
Thanks, I appreciate any help !

From $.ajax()
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
You cannot make a cross-origin XHR. See How do I send a cross-domain POST request via JavaScript? for ideas.

Related

Ajax detect "Cross-Origin Request Blocked" error

We are using third party API on our code to get data.
$.ajax({
url: API,
success: function(html, textStatus, xhr){
//IF OKAY
},
error: function(html, textStatus, xhr){
console.log( "!!!!!!!!! ERROR !!!!!!!!!!!!" );
console.log( "----", html );
console.log( "----", xhr.status );
},
});
How can detect on error if the error is
Cross-Origin Request Blocked
Any help would be appreciated.
Unfortunately, it's not possible to definitively access this type of error in browsers for security reasons. Please see this similar thread Is it possible to trap CORS errors?

Can AJAX read files with custom extension?

I have files with extensions .cst in my localhost server. I was thinking if AJAX can load them. So my question is can AJAX load files with custom extension ? If yes, how ? If no, any alternative such that we shall get the content of the file on page load ?
My ajax call for loading the file load.cst :
$.get("load.cst", function(data) {
console.log(data)
});
If the file is plain text then you can easily fetch it with jQuery. Setting data type to text will ensure jQuery does not try to process it as something else. Adding an error handler will help catch errors.
var request = $.ajax({
url: "load.cst",
method: "GET",
dataType: "text"
});
request.done(function( msg ) {
console.log(msg);
});
request.fail(function( jqXHR, textStatus ) {
console.error( "Request failed: ", textStatus );
});

Unable to handle scenario: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access

I have a form on a webpage which I'm using to capture data and post to a Google Form. The code I've used I saw on this answer. Now, as expected, I'm receiving an error like the following:
XMLHttpRequest cannot load
https://docs.google.com/forms/d/.../formResponse.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.
My script making the request is as follows:
function postToGoogle() {
$.ajax({
url: "https://docs.google.com/forms/d/.../formResponse",
data: {"entry.1691469052": "test message"},
type: "POST",
dataType: "xml",
success: function() {
alert("Success");
},
error: function() {
alert("Error");
}
});
}
$(document).ready(function(){
$('#form').submit(function() {
postToGoogle();
return false;
});
});
Now even though I get the error, my data still persists to the form which is the outcome I want.
The issue I'm facing is that in the event that data is passed, I want to display a message to the user saying the data was received. What I'm trying to do is either:
fix the error through using CORS or similar (methods I'm not familiar with and can't find an answer for on SO)
somehow check within my 'error' function that the only issue is the No 'Access-Control-Allow-Origin' one and then produce a 'success' message in that scenario. If there are other issues I'll just throw an 'error' message back to the user
So far I've not been able to find something that works. Any thoughts?
See the $.ajax doc:
error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest)
object, a string describing the type of error that occurred and an
optional exception object, if one occurred. Possible values for the
second argument (besides null) are "timeout", "error", "abort", and
"parsererror". When an HTTP error occurs, errorThrown receives the
textual portion of the HTTP status, such as "Not Found" or "Internal
Server Error."
So you can write something like:
error: function( jqXHR, textStatus, errorThrown ) {
if( errorThrown.indexOf("Access-Control-Allow-Origin") > 0 ) {
// success...
}
The error text can also be inside jqXHR.responseText.

Facebook connector fail gracefully

I'm using the Javascript connector from facebook and I have implemented things as per their instructions and all is well, until facebook is blocked by a corporate policy. Then you get a failure doing this:
ref.parentNode.insertBefore(js, ref);
I added try/catch around it and it still fails.
I have also tried just adding the <script id=... No good.
I have tried it a different way and I can see the problem, I wrote this function :
jQuery.cachedFacebookScript = function(url, options) {
// Allow user to set any option except for dataType, cache, and url
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax({
dataType : "script",
//cache : true,
url : url,
error : function(XMLHttpRequest, textStatus, exception) {
logger("Ajax failure: " + exception);
}});
};
and then added
$.cachedFacebookScript('//connect.facebook.net/en_UK/all.js')
.done(function() {console.log("Done");})
.error(function() {console.log("Error");})
;
None of the callbacks get called so I can't trap the error.
If I remove the dataType : "script", line, both of the error callbacks get called.
So it smells like a JQuery bug to me, so one way round might be to eval() the javascript that I get back in the success callback... but I don't get that far with the above, when I do have access to facebook I get this error:
XMLHttpRequest cannot load http://connect.facebook.net/en_UK/all.js. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9080' is therefore not allowed access.
Which from other question on here seems to be a server thing... so how does $.getScript() get the javascript? the doco says its a wrapper round $.ajax, so I wrote a new wrapper:
jQuery.myGetScript = function(url, success, error) {
$.ajax({
url: url,
success: function(response) {
eval(response);
success();
},
error: function (response) {
error();
}
});
}
I get the same Origin error.
The JQuery documentation says that as of JQuery 1.5 you can add a fail()... no you can't this does not work:
jQuery.myGetScript = function(url, success, error) {
logger("Calling getScript()");
ret = $.getScript(url)
.done(function( script, textStatus ) {
console.log("Successfully loaded script");
success();
})
.fail(function( jqxhr, settings, exception ) {
console.log("Failed to load script");
error();
});
};
Is there a way to make this fail gracefully, or at least throw something I can trap and handle/ignore?

Ajax post always results in error, even though everything seems correct

I'm trying to process captcha in form validation using google's reCaptcha. Basically, my validation function is called using onSubmit in the form tag, and then calls a second function to work with the recaptcha api.
Here's the code:
var returnValue;
var myData = {
privatekey : "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
remoteip : ip,
challenge : challenge,
response : response
};
$.ajax({
url: "http://www.google.com/recaptcha/api/verify",
type: "POST",
data: JSON.stringify(myData),
dataType: "text",
success: function(data) {
var result = data.split("\n");
if (result[0] == "true") {
returnValue = true;
}
else {
returnValue = false;
}
},
error: function(jqXHR, textStatus, errorThrown) {
alert("There was an error submitting the captcha. Please contact an administrator. \n\nError:\n" + textStatus, errorThrown);
returnValue = false;
},
complete: function(jqXHR, textStatus) {
return returnValue;
}
});
Using LiveHTTPHeaders in firefox, I can see the request go out to the service, and it looks like everything is being sent correctly. I get an HTTP/1.1 200 OK response back, and yet every single time the code goes to the error function. When the error function runs, jqXHR is:
Object { readyState=0, status=0, statusText="error"}
textStatus is "error", and errorThrown is ""
I've tried doing this a number of ways, including $.POST, and using .done(), .fail(), .always(), and it always behaves the same.
I've seen some other postings here having to do with problems with cross-domain requests, but none of those situations really seem to be relevant, because I actually am doing a cross-domain request, and those seemed to be issues where they were making requests to a file on the same domain, and it was being handled incorrectly as a cross-domain request.
I'm at my wits end here.. any help would be greatly appreciated.
I've seen some other postings here having to do with problems with cross-domain requests, but none of those situations really seem to be relevant, because I actually am doing a cross-domain request
When I run that code I get the error:
XMLHttpRequest cannot load http://www.google.com/recaptcha/api/verify.
Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.
So it is a cross-domain issue. You might want to make a cross domain request, but Google isn't set up to allow it.
I'm pretty sure that recaptcha needs to be implemented with server side code. If you do it entirely on the client with JS then the client can lie and say it has passed the captcha when it hasn't.
function check(){
$.post('check.php',{
'check':1,
'challenge':$('#recaptcha_challenge_field').val(),
'response':$('#recaptcha_response_field').val()},
function(a){
console.log(a);
});
}
check.php:
if($_POST){
if(isset($_POST['check'])){
$url = 'http://www.google.com/recaptcha/api/verify';
$data = array(
'privatekey'=> "**********************************",
'remoteip' => $_SERVER['REMOTE_ADDR'],
'challenge' => $_POST['challenge'],
'response' => $_POST['response'],
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data),
),
);
echo print_r($data,true);
die(file_get_contents($url, false, stream_context_create($options)));
}
}
Warning: You have only one choice to check! (Ref.)

Categories

Resources