W3C Validator offline on localhost by ajax - javascript

I use to programming Brackets text editor and I have already installed W3C validator but it working while I'm online but offine not. I try install https://validator.w3.org/docs/install.html and I running to localhost:8888 but brackets's extension connecting only via ajax (javascript). Is possible send ajax like to original W3C website?

Maintainer of the W3C HTML checker (validator) here. Yes it is possible to send an ajax request to a local instance of the current checker. To use Fetch to do it and get JSON-formatted results back:
var checkerUrl = "http://localhost:8888/?out=json"
fetch(document.location.href)
.then(function(currentDoc) { return currentDoc.text(); })
.then(function(htmlSource) {
fetch(
checkerUrl, {
method: "POST",
mode: "cors",
body: htmlSource,
headers: new Headers({ "Content-Type": "text/html;charset=utf-8" })
})
.then(function(checkerResponse) { return checkerResponse.json(); })
.then(function(jsonOutput) {
console.dir(jsonOutput.messages);
})
});
That shows the basic steps to follow to deliver the request in the way the checker expects:
send a document to the checker as the body of a POST (in this example, the current doc)
tell the checker to format its results as JSON (out=json)
make text/html;charset=utf-8 the media type of the POST body you send to the checker
The checker also supports multipart/form-data for giving it the HTML source to be checked, but giving it the source as a POST body instead is the preferred (and better) way for doing it.
If instead of using fetch() you want to use JQuery $.ajax(…), here’s an example:
var checkerUrl = "http://localhost:8888/?out=json"
$.get(document.location.href,
function(htmlSource)
{
$.ajax({
url: checkerUrl,
type: "POST",
crossDomain: true,
data: htmlSource,
contentType: "text/html;charset=utf-8",
dataType: "json",
success: function (jsonOutput) {
console.dir(jsonOutput.messages);
}
});
});
And if instead of either fetch() or JQuery $.ajax(…) you want to use old-school XHR but it’s not clear how to handle the details in that case, let me know and I can post an example of that too.
In all cases, the .messages JSON output is an array of objects that each contain something like:
firstColumn: 1
lastColumn: 6
lastLine: 4
message: "Unclosed element “span”."
type: "error"
The documentation for the checker JSON format gives more details of the JSON the checker emits.

Related

devops-rest APi - $expand not working for "Work Items - Get Work Items Batch"

I want to access some data from selected work items.
Below is my working code.
function postApiData(ApiUrl, responseBody, token) {
var res = '';
$.ajax({
type: 'POST',
async: false,
url: ApiUrl,
contentType: 'application/json',
data: JSON.stringify(responseBody),
cache: false,
dataType: 'json',
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", "Basic " + btoa("" + ":" + _token));
},
}).done(function (data) {
res = data;
});
return res;
};
var d = {
"ids": itemlist,
"fields": ["System.Id", "System.WorkItemType", "System.Title", "System.AssignedTo", "System.State", "System.Tags", "cust.PID", "cust.Product", "cust.ReleasedToProduction"]
};
var itemdata = postApiData('https://dev.azure.com/COMP/products/_apis/wit/workitemsbatch?$expand=relations&api-version=5.1', d, '');
However, $expand is not working here to get relations. query gives the result and always ignores $expand.
I have also tried to pass $expand in request body, but it is also not working. Can anyone please guide here?
That's because the expand parameter can not be used with the fields parameter if the expand value is relations.
You could execute this api with your request body in Postman. You will get the clearly message that why you can not apply it.
To use your API, if you specify the fields in the request body, then expand should not be used any more, and vice versa. This is as designed, and it has been hardcoded into our scripts. We do not allow another $expand value if it is not the None or Links.
For the 5 values of $expand(None, Relations, Fields, Links, All), only None and Links can work with fields successfully in API. This is a universal rule which apply to all APIs, including this one.
Also, please use $expand=Relations in request body instead of in URI which shown as the document described. Here if you use it in URI, it will not be used by server script since the method that this API called does not has this parameter. Another API which can use $expand in the URI (As normal, we would mention and show whether it can be used in URI in document), the corresponding scripts have parameters can access these value which passed by URI.
So, here please use $expand=Relations in request body, then you would get the result with all fields and its all relations.

Getting a parseerror from jQuery $.ajax post return using jsonp from Trakt.tv api

Working with the Trakt.tv API. It looks like I'm sending valid json as I'm able to authenticate but the return I receive is a parse error.
Resource interpreted as Script but transferred with MIME type text/html:
http://api.trakt.tv/recommendations/shows/myApiKeyCompleteNumbers?callback=jQuery111000155555475132972_1397674204444&{%22username%22:%22userName%22,%22password%22:%22mySha1PassComplete%22}&_=1397674207093
Uncaught SyntaxError: Unexpected identifier
The return says:
Disallowed Key Characters.
I'm using:
jQuery 1.11.0
Thanks in advance for any help or guidance
$(document).ready(function () {
function success(data) {
alert('data: ' + data);
}
var traktUser = 'myUserName';
var traktHash = 'mySha1Password';
var traktApi = 'myApiKey';
var data = {
'username': traktUser,
'password': traktHash
};
var postData = JSON.stringify(data);
var apiUrl = 'http://api.trakt.tv/recommendations/shows/' + traktApi;
$.ajax({
type: 'POST',
url: apiUrl,
data: postData,
contentType: 'application/json',
dataType: 'jsonp',
}).
done(success);
}); //document ready
You can't make a POST request using JSONP, jQuery is ignoring the POST instruction and making a GET request.
Your data is being placed in the query string and is not properly URL Encoded.
The server is responding with an HTML document containing an error message instead of a JavaScript script formatted according to JSONP rules.
It looks like the API you are trying to use does not support JSONP at all. Since you are passing your own user credentials in the request, this makes sense. JSONP is a hack to work around the Same Origin Policy that is implemented by browsers (these days we can use CORS instead) and there is no point in using it unless you want end user browsers to access the API directly. Since end user browsers couldn't access it without being given your username and password, it doesn't seem likely to be intended to be used that way.
Process the data from the API on your server instead.

Submit a form to DJANGO from Phonegap Application using JAVAScript

I have written a Phonegap application and I would like to know how can I submit a form to Django using Javascript or Jquery. I have already implemented a JSON API using Tastypie.
Can anybody provide me with some ideas, or any guidance on how to implement such a function?
You just have to do ajax call to tastypie api url in the below format.
$.ajax({
type: 'POST',
url: site_url+'api/v2/user/login/',
data: '{"username": "developer", "password":"imagine2"}',
processData: false,
crossDomain: true,
success: function (response, textStatus, xhr) {
console.log('jquery worked');
//results=JSON.stringify(response);
setCookie( "sessionid", response.sessionid);
setCookie( "app_version", response.app_version);
window.location.href = 'home/';
$('#overlay').hide();
},
error: function (res) {
msg = (res.responseText) ? res.responseText : res.statusText;
console.log(msg+",res.status="+res.status);
alert(msg);
},
dataType: "json",
contentType: "application/json; charset=utf-8"
});
Also you need to enable cross domain.
There are multiple ways to do this. Since you are using an API with tastypie I would suggest not submitting the form itself, but extracting the form data before submitting the form with JavaScript. On submit you pass the data you want to submit in the request body to your API endpoint.
As an example you could have an api endpoint for blog entries, lets say its http://example.com/api/v1/entry. Considering your API allows cross-domain requests (e.g. via CORS) you could do something simple as this to "submit" your form (e.g. creating a new entry):
$('#myForm #mySubmitButton').click(function() {
$.post('http://example.com/api/v1/entry', $('#myForm').serialize(), function(data) {
// deal with the response data
}
});
I am not sure tastypie supports this kind of data structure. A little longer version of this could be to do something like this (here I am sure tastypie does support it), which submits the data as a JSON:
$('#myForm #mySubmitButton').click(function() {
var data = {'title': $('#myForm #titleInput').val(), 'description': $('#myForm #descriptionInput').val()};
$.post('http://example.com/api/v1/entry', data, function(data) {
// deal with the response data
}
});
This examples do not deal with form validation, error handling etc.. You could have look into tastypie validation for more details and potentially also add frontend specific validation with HTML5. I would also suggest you to use a more sophisticated JavaScript framework like AngularJS for single page apps like a PhoneGap app. JQuery will bloat your app soon, when it grows.

jQuery $.ajax done callback not firing

I have the following code :
$("#loginSubmitButton").on("click",function(){
var loginUserDetails = {
email: $("#email").val(),
password: $("#password").val()
};
//Send the AJAX request to authenticate the user
$.ajax({
type: "POST",
url: "/somewebservice/v1/users/authenticate",
data: JSON.stringify(loginUserDetails),
contentType: "application/json;charset=UTF-8",
dataType: "json",
}).done(function() {
$("#loginResult").text("Login successful");
})
.fail(function() {
$("#loginResult").text("Login failed");
});
});
As per the jquery documentation (unless I am understanding something incorrectly) I expect the done to be fired if I receive a 200 OK from my web server. However, in chrome console I can see a 200 OK response but jquery seems to fire the fail handler.
Does anyone have any idea what I might be doing wrong here?
You need to remove:
dataType: "json"
There are lots of suggestions to remove
dataType: "json"
While I grant that this works it's probably ignoring the underlying issue. It's most likely caused by a parser error (the browser parsing the json response). Firstly examine the XHR parameter in either .always() or .fail().
Assuming it is a parser fail then why? Perhaps the return string isn't JSON. Or it could be errant whitespace at the start of the response. Consider having a look at it in fiddler. Mine looked like this:
Connection: Keep-Alive
Content-Type: application/json; charset=utf-8
{"type":"scan","data":{"image":".\/output\/ou...
In my case this was a problem with PHP spewing out unwanted characters (in this case UTF file BOMs). Once I removed these it fixed the problem while also keeping
dataType: json
If your server returns empty string for a json response (even if with a 200 OK), jQuery treats it as failed. Since v1.9, an empty string is considered invalid json.
Whatever is the cause, a good place to look at is the 'data' parameter passed to the callbacks:
$.ajax( .. ).always(function(data) {
console.log(JSON.stringify(data));
});
Its contents will give you an understanding of what's wrong.
Need to remove , from dataType: "json",
dataType: "json"
The ajax URL must be the same domain. You can't use AJAX to access cross-domain scripts. This is because of the Same Origin Policy.
add "dataType:JSONP" to achieve cross domain communication
use below code
$.ajax({
URL: cross domain
dataType: 'jsonp'
// must use dataType:JSONP to achieve cross domain communication, otherwise done function would not called.
// jquery ajax will return "statustext error" at }).always(function(data){}
}).always(function(data){
alert(JSON.stringify(data));
}
A few things that should clear up your issue and a couple hints in general.
Don't listen for a click on a submit button. You should wait for the submit event on the form.
The data option for $.ajax isn't expecting a JSON string. It wants a serialized string or an array with name and value objects. You can create either of those easily with .serialize() or .serializeArray().
Here is what I was thinking for your script.
$('#form-with-loginSubmitButton').on('submit', function(e){
e.preventDefault():
var $form = $(this),
data = $form.serializeArray();
$.ajax({
type: "POST",
url: "/somewebservice/v1/users/authenticate",
data: data
}).done(function(result){
console.log(result);
});
});

How can I send a http delete request from browser?

Is there a way to send a DELETE request from a website, using xmlhttprequest or something similar?
As someone mentioned above, jQuery will do this for you, via the following syntax:
$.ajax({
type: "DELETE",
url: "delete_script.php",
data: "name=someValue",
success: function(msg){
alert("Data Deleted: " + msg);
}
});
You can test if your browse has DELETE implemented here
Supposing req is a XMLHttpRequest object, the code would be req.open("DELETE", uri, false);
I use fetch API on one of the projects:
fetch(deleteEndpoint, {
method: 'delete',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({id: id, token: token})
})
I have deleteEndpoint, id and token previously defined.
This can be done with jQuery, if you don't mind the dependence on a framework. I believe jQuery uses XmlHttpRequest to perform this action. You'd use the $.ajax function with the type parameter set to DELETE.
Please note that not all browsers support HTTP DELETE requests.
I believe that both PUT and DELETE are not implemented (in the case of Prototype) due to flaky browser support.
You can use php to do this:
setup your XMLHTTPRequst to call a phpscript that deletes a named file, and then pass the filename that you intend to be removed to the php script and let it do its business.

Categories

Resources