Cross site HTTP authentication in JQuery - javascript

I want to see if it is possible to log into a third site that uses HTTP authentication. Ideally, the browser will store the credentials. Unfortunately this fails every time. Any help would be much appreciated, I'm using the base64 Jquery plugin, which I've tested to work.
So, two questions:
How can I view the HTTP status code?
Will this ultimately work, in principle?
<script>
$("#login_button").click(function() {
var username = 'myFunUsername';
var password = 'myFunPassword';
$.ajax({
url: 'http://remote-site-with-http-auth.com/member_site',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + $.base64.encode(username + ":" + password));
},
success: function(data) { $("#label").text("Logged in, yay!"); }
}).fail(function(){ $("#label").text("It didn't work"); });
});
Thanks!!

var user= 'myFunUsername';
var pwd= 'myFunPassword';
$.ajax({
url: 'http://remote-site-with-http-auth.com/member_site',
crossDomain:true,
username :user,// Keep the variable name different from parameter name to avoid confusion
password:pwd,
xhrFields: { /* YOUR XHR PARAMETERS HERE */}
beforeSend: function(xhr) {
// Set your headers
},
success: function(data, textStatus, xhr) {
alert(xhr.status);// The status code
//Code for success
}
}).fail(function(){
//Fail code here
});
For more details on parameters refer to http://api.jquery.com/jQuery.ajax/

Related

Getting 403 error while making ajax request in jQuery

I'm getting a 403 error while making an AJAX request to a php page of my own website.
This is the error:
"jq.js:663 POST https://playonlineloto.com/backend/cstatus.php 403"
I'm using jQuery to make the request. The code is:
function status() {
var table = document.getElementById("table").value;
var name=document.getElementById("username").innerHTML;
var card=document.getElementById("card").innerHTML;
var dataString = "table=" + table+"&name="+name+"&card="+card;
$.ajax({
type: "POST",
url: "cstatus.php",
data: dataString,
cache: false,
success: function(html) {
if(html=="no"){
}else{
console.log("kicked out");
console.log(html);
var kick = document.getElementById("kick");
kick.style.display="block";
}
}
});
};
and I'm requesting from this url
https://playonlineloto.com/backend/custom-game.php?val=1&table=U7Gh8c7f6&admin=yes
My files have enough permission. Please help me!!

is that possible to make ajax call to external web page?

is it possible to call a page of another website from an ajax call ?
my guess is that is possible since connection is not denied , but i can't figure out how to make my ajax call works , I am calling a list of TV Channels of a website , but I am getting no results , would you please see if my script contains any errors
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl+"&callback=?",
data: "channelType="+all,
type: 'POST',
success: function(data) {
$('#showdata').html(data);
},
error: function(e) {
alert('Error: '+data);
}
});
}
showValues();
html div for results
<div id="showdata" name ="showdata">
</div>
Ajax calls are not valid across different domains.you can use JSONP. JQuery-ajax-cross-domain is a similar question that may give you some insight. Also, you need to ensure thatJSONP has to also be implemented in the domain that you are getting the data from.
Here is an example for jquery ajax(), but you may want to look into $.getJSON():
$.ajax({
url: 'http://yourUrl?callback=?',
dataType: 'jsonp',
success: processJSON
});
Another option is CORS (Cross Origin Resource Sharing), however, this requires that the other server to enable CORS which most likely will not happen in this case.
You can try this :
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl,
data: channelType="+all,
type: 'POST',
success: function (data) {
//do something
},
error: function(e) {
alert('Error: '+e);
}
});
}

Using pushState inside success function of ajax

I want to append one more param at the end of the current url if the ajax call returns successfully. In this context, we can get back the identifier of the object has been persisted into the database, then append this identifier to the url.
The problem is curationNotes of data was lost if the line window.history.pushState({}, null, newHref); is uncommented. It means we cannot get 'params.curationNotes' in controller. The params.curationNotes, which is a map of user provided values on the form, is null when we try to parse it inside the controller.
Below is the snippet I am working on.
$('#btnSave').on("click", function(event) {
if ($('#curationNotesForm')[0].checkValidity()) {
var curationNotes = buildCurationNotesTC();
"use strict";
event.preventDefault();
$.ajax({
dataType: "text",
type: "POST",
url: $.jummp.createLink("curationNotes", "doAddOrUpdate"),
cache: true,
data: {
curationNotes: curationNotes,
model: "${id}"
},
processData: true,
async: true,
beforeSend: function() {
$('#txtStatus').text("The curation notes are being saved. Please wait...");
},
success: function(response) {
var response = JSON.parse(response);
var href = window.location.href;
if (href.indexOf("&cnId=") < 0) {
var newHref = href + "&cnId=" + response['cnId'];
//window.history.pushState({}, null, newHref);
}
$('#txtStatus').text(response['message']);
},
error: function(jqXHR, textStatus, errorThrown) {
// TODO: the error message doesn't show properly
$('#txtStatus').text("Error: ", jqXHR.responseText + textStatus + errorThrown + JSON.stringify(jqXHR));
}
});
} else {
$('#txtStatus').text("Please check required fields and click Save button again...");
}
});
If I comment this line window.history.pushState({}, null, newHref);, the code is working properly.
Notes: this snippet works fine in any web browsers on Linux but cannot work in any web browser of Windows 10. That's actually ridiculous to me.
Have you ever had any experience with this problem?

jquery ajax function with json

Hi i am using this code to get contents from a json file but i am not able to show results
my code is
$(document).ready(function(){
$.ajax({
url: 'http://50.116.19.49/rest/user.json',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 50000,
success: function(data, status){
alert(data);
},
error: function(){
output.text('There was an error loading the data.');
}
});
});
In google chrome i can see that the request status is 200 and data is loaded. here is the link from which i am copying code The Link.... Any help!!!!
Thanks
Your code doesn't work because the http://50.116.19.49/rest/user.json resource return a JSON response instead of JSONP (difference).
So you can't make cross-domain calls via ajax BUT you can create a some proxy script ON YOUR SERVER which will make it for you. Example:
cross-domain-call.php
<?php echo file_get_contents('http://50.116.19.49/rest/user.json');?>
And change your script to
$(document).ready(function(){
$.ajax({
url: 'http://127.0.0.1/cross-domain-call.php',
dataType: 'json',
timeout: 50000,
success: function(data, status){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
});
Since you don't seem to have access to remote webservice to convert it to JSONP, here is a solution using Yahoo's YQL as a proxy. YQL will retrieve file contents from any remote site and return as xml or jsonp.
Working DEmo http://jsfiddle.net/Uh8cz/2/
You will notice the response object has additional properties created by YQL
var yqlBaseUrl = 'http://query.yahooapis.com/v1/public/yql?q=';
var restUrl = 'http://50.116.19.49/rest/user.json';
var yqlQuery = 'select * from json where url="' + restUrl + '" ';
var yqlFormat = 'format=json'
var jQueryCallback = '?'
var fullQueryUrl = yqlBaseUrl + yqlQuery + '&' + yqlFormat + '&' + jQueryCallback;
$.getJSON(fullQueryUrl, function(json) {
var jsonString = JSON.stringify(json.query.results.json.json, null, ' ')
$('body').append('<h1>Response</h1><pre>' + jsonString)
}) ​
If you can control the content of "user.json", wrap it around a function:
user.json content:
execute_jsonp({you_json)
your javascript:
$(document).ready(function(){
$.ajax({
url: 'http://50.116.19.49/rest/user.json',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 50000,
success: function(data, status){
data(); //execute the function that is sent
},
error: function(){
output.text('There was an error loading the data.');
}
});
function execute_jsonp(json){ //recreate the function so you may access the json as a parameter
alert(json);
}
});
Hope this helps ;)

jquery $ajax not working as expected

I Have to do a cross-domain request and fetch content from a url using $.ajax function.
But the below code only displays the first alert i.e alert(myUrl),
After that the execution stops.The second alert is not displayed. I don't know what is wrong with the code i have written.
Can somebody tell me what i am doing wrong here?Thanks in advance.
function getContentFromUrl(){
var myUrl="http://icant.co.uk";
alert(myUrl);
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" +
"q=select%20*%20from%20html%20where%20url%3D%22" +
encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: data,
success: function () {
alert("***********"+data.results[0]);
if (data.results[0]) {
var htmlText = data.results[0];
var jsonObject = parseAndConvertToJsonObj(htmlText);
} else {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
},
error: function() {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
});
}
Same Origin Policy:
The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.
You can't use regular JSON for cross-domain requests because of the same-origin policy. Instead, you'll need to use JSONP. In jQuery, you can do so like this:
$.ajax({
dataType: 'jsonp',
crossDomain: true
// other info
});
Note that there are security issues involved with JSONP. Only use JSONP if you trust the host domain.
I assume this is jQuery?
Try the following:
url = "http://query.yahooapis.com/v1/public/yql?" +"q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?";
getContentFromURL(url);
function getContentFromURL(url)
{
$.get(url, function (data) {
console.log(data);
});
}
If it dumps out to the console a response, you can build from there.
The data here is not defined
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" + "q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: data,
and you forget to add a param for the callback function
success: function (data) {
....
}
The finally code should like this
function getContentFromUrl() {
var myUrl = "http://icant.co.uk";
alert(myUrl);
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" + "q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: {},
success: function (data) {
alert("***********" + data.results[0]);
if (data.results[0]) {
var htmlText = data.results[0];
var jsonObject = parseAndConvertToJsonObj(htmlText);
} else {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
},
error: function () { document.getElementById("displayerrors").innerHTML = "Could not load the page."; }
});
}

Categories