Can AJAX read files with custom extension? - javascript

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 );
});

Related

getting the list of files inside a folder using ajax

I have an url that is listing the files inside a folder:
Using javascript I need to obtain that list of files.
My code:
$.ajax({
url: 'http://webtests02/pruebas/',
success: function (data) {
console.log(data);
}
});
The thing is I am getting nothing as the return of the ajax GET call.
I tried other formats like using $.get but the result is the same so I cloncluded that or as it is not a .html, .aspx I can't get the code and scrape the content or the IIS is blocking these requests so I can't get it using jquery...
The website is mine so I can configure whatever needed in the IIS...
EDIT: I created an asp website that lists the files in the folder:
But I am still getting an empty response when I make the ajax call:
EDIT: THREAD CLOSED. It was due to a CORS authorization error.
Newer implementations of jQuery use the .done() method on the Ajax object to deal with completion and data of the AJAX call.
$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
}).done(function( data ) {
if ( console && console.log ) {
console.log( "Sample of data:", data.slice( 0, 100 ) );
}
});
http://api.jquery.com/jQuery.ajax/#jqXHR

Getting php data from jQuery ajax without html forms

My idea is to write single page web application using jQuery and having server side in php, I want to do it without using html forms. So far I have this new.php file:
<?php
echo "Welcome";
?>
And javascript:
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'http://localhost/pmfServer/new.php',
success: function (data) {
alert('success' + data);
},
error: function(jqXHR,error, errorThrown) {
alert("Something went wrong " + errorThrown);
}
});
});
The alert i get is just "success" with nothing else.
I have apache web server running, and when i type same url in web browser it says "welcome".
Is this proper way to do server side since I'm not going to use forms?
Do I have to use some frameworks for that?
Try this:
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'http://localhost/pmfServer/new.php'
}).done(function(response){
var response = $.trim(response);
alert(response);
});
});
If you still get no reply from ajax, please verify your path (url: '....')
Also check your console for any errors...
One last thing: Ajax files should not always be accessible directly from browsers... You may want to consider protecting them (while they will still be reachable by xmlhttprequest:
<?php
//protect the file from un-auth access
define('AJAX_REQUEST', isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
if(!AJAX_REQUEST) {die();}
echo "Welcome";
?>
Of course in your particular "Welcome" case, that might not be necessary... I am just referring to more "sensitive" ajax files ;)
Old functions that I've did allows you to make a AJAX request to an URL also.
function Get(t,e,n){!function(){var s=new XMLHttpRequest;s.onreadystatechange=function(){4==s.readyState&&200==s.status?(e(s.responseText),s=void 0):s.status>=500&&(s=void 0,n(0))},t+=t.indexOf("?")>-1?"&tsmp="+Date.now():"?tsmp="+Date.now(),s.open("GET",t,!0),s.send()}()}
function Post(t,e,n,o){!function(){var s=new XMLHttpRequest;s.onreadystatechange=function(){4==s.readyState&&200==s.status?(n(s.responseText),s=void 0):s.status>=500&&(s=void 0,o(0))},t+=t.indexOf("?")>-1?"&tsmp="+Date.now():"?tsmp="+Date.now(),s.open("POST",t,!0),s.setRequestHeader("Content-type","application/x-www-form-urlencoded"),s.send(e)}()}
This is very simple to use... if you want to across the jQuery:
Get("http://localhost/pmfServer/new.php",function(msg){alert(msg)},function(err){alert("Error")})
This is to post data and after get:
Post("http://example.com/yourtext.php","wow=1",function(msg){alert(msg)},function(err){alert("Error")})
Also see if there are no errors in the console.
And... I recommend you to use encodeURIComponent when sending some string with user data.
encodeURIComponent("ÃÃO.. ! # # $ % Ohh! & %><")
Make sure your .html file beside the .php and change the url in javascript code to "new.php" as the following
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'new.php',
success: function (data) {
alert('success' + data);
},
error: function(jqXHR,error, errorThrown) {
alert("Something went wrong " + errorThrown);
}
});
});
I suggest to use framework for single page application such as http://durandaljs.com/

How to get web service data with javascript?

I have token value in a URL like http://example.com/api.php?action=token
I need to consume this URL data which is a random string, I'm trying with following code:
var jqxhr = $.get("http://example.com/api.php?action=token", function() {
alert( "success" );
})
.done(function() {
alert( "second success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "finished" );
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function() {
alert( "second finished" );
});
Using $.get()
While trying to load, it's showing an error. I'm just stuck with it, how to get the data?
Cross domain calls are restricted by the browser so some solutions are,
1.Cross-Origin Resource Sharing (CORS) or jsonp, but you will require to have access to the server you are calling and configure that (many examples online e.g. How to make cross domain request)
2.server side proxy - create simple server side code e.g. php page that you will call form js and place code in php that calls the targeted cross domain server and return the results to your js. e.g. AJAX cross domain call
try this
$.ajax({
url:"http://example.com/api.php?action=token",
type: "GET",
success: function (data) {
alert(data)
}
});
try this
$.ajax({
url:"http://example.com/api.php?action=token",
type: "POST", //try this
success: function (data) {
alert(data)
}
});

Download JSON file via JavaScript/JQuery - HTTP-Status Ok - JQuery Error

I've got the following problem: I need to download a JSON file from an API via JQuery / JavaScript. In theory this should be quite basic.
I tried $.ajax and all of its siblings like $.get or $.getJSON. I alway get an 200 OK but my Firebug reports an error. Printing the error just says: "error" - so not that helful.
I read that maybe the JSON file is corrupt. So I tried it with a plain text file (*.txt). Same result.
The JSON file is valid, I check it against a validator.
I also tried ContentType and dateType and experimented with json and jsonp...
I basically used something like this (with a million variations for testing purposes):
$.ajax({
url: 'http://www.myurl.com/api/v1/myfile.json',
...
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error.statusText);
}
});
Am I missing something important here? It's really odd that nothing seems to change the behavior of the AJAX-call.
In fact I don't really need AJAX because I need to grab the JSON file when loading the page...
And the JSON file is not on the same domain as the AJAX caller.
Is that URL located on the same server you're trying to get the data from?
If not, you ran into a cross-domain request, which can only be handled using JSONP. So, the JSON file itself must be compatible with JSONP format, otherwise jQuery won't be able to process it (even if you provide a 'jsonp' dataType).
P.S.: Firebug will always show response code 200 but give an empty response body for such requests
Try in this way by disabling security
$.ajax( {
type : 'GET',
contentType : "application/json; charset=utf-8",
url : surl, \\specify your url
async : false,
dataType : 'json',
headers : {
Accept : "application/json",
"Access-Control-Allow-Origin" : "*"
},
crossDomain : true,
success : SucceedFunc,
error : function(data, textStatus, errorThrown) {
console.log("error" + ' ' + JSON.stringify(data) + ' ' + textStatus + ' ' + errorThrown);
}
});
function SucceedFunc(data) {
alert("success");
}
}
Did you try to catch the error the correct way?
$.ajax({
url: 'http://www.myurl.com/api/v1/myfile.json',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error.message);
}
});
If you are using chrome go to cmd prompt and run the chrome by disabling the security. You can disable security using pathwhere_chrome_is_located\chrome.exe --disable-web-security
and run the html page. I think this may help you.

jQuery form Plugin

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.

Categories

Resources