I am using the following code to determine if an m3u8 URL is broken or not. I test with two different URLs, one that is online and one that is offline. For both cases, my javascript function doesn't alert me that file is found or not and firefox debugs doesn't give me any error but status variable always shows 0. Could anyone tell me what I am doing wrong here?
Edit:
for offline url i get this header response(in httpfox developer tool) :HTTP/1.1 404 Not Found
for online url i get this header response(in httpfox developer tool) :HTTP/1.1 200 OK
Code:
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
function testFunction() {
//m="http://someothersite.com/offline.m3u8";
m="http://somesite.com/workingfile.m3u8";
//now we checking if the file exist
UrlExists(m, function(status){
alert('status:'+status);
if(status === 200){
// file was found
alert('file found'+m);
}
else if(status === 404){
// 404 not found
alert('file not found'+m);
}
});
function UrlExists(url, cb){
jQuery.ajax({
url: url,
dataType: 'text',
type: 'GET',
complete: function(xhr){
alert(+xhr.status);
if(typeof cb === 'function')
cb.apply(this, [xhr.status]);
}
});
}
}// end of main
</script>
</head>
<body>
<button onclick="testFunction()">Click me</button>
</html>
This will not work if you are using external URL's as CORS (Cross-origin resource sharing) will kick in and will stop you as you are not on the same domain.
Working version: local files only
UrlExists('/path/file.php', function(status){
if(status === 200){
alert('file found');
}
else if(status === 404){
alert('file not found');
}
});
Unfortunately, there isnt a valid way of doing this through Javascript. However, you can conduct this through backend functionality e.g. PHP
$file = 'http://www.othername.com/somefile.jpg';
$file_headers = #get_headers($file);
if($file_headers[0] == 'HTTP/1.1 404 Not Found') {
$exists = false;
}
else {
$exists = true;
}
If you build this into a php function and then use your Ajax functionality to pass the URL through to the PHP for validation, and then return back a response - it should work.
Edit: Curl Example
$mainUrl = curl_init($url);
curl_setopt($mainUrl, CURLOPT_RETURNTRANSFER, TRUE);
$response = curl_exec($mainUrl);
$httpCode = curl_getinfo($mainUrl, CURLINFO_HTTP_CODE);
if($httpCode == 404) {
echo "404 Error";
}else if($httpCode == 200){
echo "200 Error";
}else{
echo "all good - sort off...";
}
curl_close($mainUrl);
Here is the Curl option - Now the way i would do it (and i really had to do it...) is looping through each and every single URL on the page (in js) and sending it as an object to PHP (through Ajax). With PHP, i would use the above CURL functionality to confirm which ones are broken (either with a 1 or 0) and then send a response back.
Related
Im trying to help a friend out with a program but my coding experience is somewhat dated (10 years give or take). Where trying to pull data from a database via their API. Im making this request via a XMLhttpRequest but im having issues even getting to the Server.
The error that occurs:
Failed to load resource: the server responded with a status of 404 (Not Found)
http://localhost/jasper/api.shiftbase.com/api/rosters?min_date=2020-07-13&max_date=2020-12-31&department_id=24477
Its trying to search for the url on my own domain. But I need it to search cross domain.
The entire function:
function getRequest(){
var _request = new XMLHttpRequest();
var key = myKeyHere;
var url = "api.shiftbase.com/api/rosters?min_date=2020-07-13&max_date=2020-12-31&department_id=24477";
_request.onreadystatechange = function(event){
console.log(_request.readyState + " + " + _request.status);
if (_request.readyState == 4){
if ((_request.status >= 200 && _request.status < 300) || _request.status == 304){
alert(_request.responseText);
} else {
alert('Request was unsucceful: ' + _request.status);
}
}
};
_request.open("get", url, true);
_request.setRequestHeader("Accept", "application/JSON", false);
_request.setRequestHeader("Content-Type", "application/JSON", false);
_request.setRequestHeader("Authorization", key, false);
_request.send(null);
};
I've also read a lot about CORS and how this affects these kinds of requests cross domain, but i don't quite understand how it works and how i can work arround it.
Any help is appreciated.
First of all you need to prefix your URL with https://. This way you make a request to the external server instead of localhost. The second thing is that in your headers the application/JSON should be application/json.
Also dont forget that your key needs to be prefixed with "API". Example API [some_random_key]
I've tested the following code and it worked. You just have to add your own API KEY.
function getRequest(){
var _request = new XMLHttpRequest();
var key = "API [replace_this_with_your_key]"; // Example: "API a1b2c3d4e5f6g7h8i9"
var url = "https://api.shiftbase.com/api/rosters?min_date=2020-07-13&max_date=2020-12-31&department_id=24477";
_request.onreadystatechange = function(event){
console.log(_request.readyState + " + " + _request.status);
if (_request.readyState == 4){
if ((_request.status >= 200 && _request.status < 300) || _request.status == 304){
alert(_request.responseText);
} else {
alert('Request was unsucceful: ' + _request.status);
}
}
};
_request.open("get", url, true);
_request.setRequestHeader("Accept", "application/json", false);
_request.setRequestHeader("Content-Type", "application/json", false);
_request.setRequestHeader("Authorization", key, false);
_request.send(null);
};
Try to add // at the start of the line in url variable declaration (line 4), if you want to make a request to the external server.
Your request was made to the local webserver http://localhost/jasper/... and you've received a 404 (not found) error.
<?php
session_start();
define("HOST","localhost");
define("USER","root");
define("PASS","");
define("DB","project_inv");
define("DOMAIN","http://localhost/
inv_project/public_html/dont");
?>
Database:
<?php
class Database
{
private $con;
public function connect(){
include_once("constants.php");
$this->con = new Mysqli(HOST,USER,PASS,DB);
if ($this->con) {
return $this->con;
}
return "DATABASE_CONNECTION_FAIL";
}
}
//$db = new Database();
//$db->connect();
?>
JavaScript Validation Part: It comes here and keeps on loading when am trying to take from ip, e.g. http://xx.xx.xx.xx/inv_project/public_html/dont/
//For Login Part
$("#form_login").on("submit",function(){
var email = $("#log_email");
var pass = $("#log_password");
var status = false;
if (email.val() == "") {
email.addClass("border-danger");
$("#e_error").html("<span class='text-danger'>Please Enter Email Address</span>");
status = false;
}else{
email.removeClass("border-danger");
$("#e_error").html("");
status = true;
}
if (pass.val() == "") {
pass.addClass("border-danger");
$("#p_error").html("<span class='text-danger'>Please Enter Password</span>");
status = false;
}else{
pass.removeClass("border-danger");
$("#p_error").html("");
status = true;
}
if (status) {
$(".overlay").show();
$.ajax({
url : DOMAIN+"/includes/process.php",
method : "POST",
data : $("#form_login").serialize(),
success : function(data){
if (data == "NOT_REGISTERD") {
$(".overlay").hide();
email.addClass("border-danger");
$("#e_error").html("<span class='text-danger'>It seems like you are not registered</span>");
}else if(data == "PASSWORD_NOT_MATCHED"){
$(".overlay").hide();
pass.addClass("border-danger");
$("#p_error").html("<span class='text-danger'>Please Enter Correct Password</span>");
status = false;
}else{
$(".overlay").hide();
console.log(data);
window.location.href = DOMAIN+"/dashboard.php";
}
}
})
}
})
While am trying to run from other computer it displays the design and content of the page but it is not validating but when am trying locally it works fine.
Don't define DOMAIN as "localhost". This will cause errors, while calling the page from other computers.
Localhost means always the computer the script is running on. Using this in a JavaScript the reference to the server is lost and it tries to connect/forward to the client-computer - with no success. This works on the first computer, because this might be the server.
i cant trace out the problem am new to remote server with php
here is the part of my program where problem occurs
function handleLogin(email, password, callback){
var jsonToReturn = "";
$.ajax(appRoot+'access/login', {
method: "POST",
data: {email:email, password:password}
}).done(function(returnedData){
if(returnedData.status === 1){
jsonToReturn = {status:1, msg:"Authenticated..."};
}
else{
//display error messages
jsonToReturn = {status:0, msg:"Invalid email/password combination"};
}
typeof(callback) === "function" ? callback(jsonToReturn) : "";
}).fail(function(){
//set error message based on the internet connectivity of the user
var msg = "Log in failed. Please check your internet connection and try again later.";
//display error messages
jsonToReturn = {status:0, msg:msg};
typeof(callback) === "function" ? callback(jsonToReturn) : "";
});
}
In local server it works fine but in remote server it call fails function and displays message "Log in failed. Please check your internet connection and try again later.";
thanks in advance
I am trying to make a ajax call and validate a input html field. But, instead of getting simple echo message. I am getting complete source code in responseText.
JavaScript
function checkUsername() {
document.getElementById("username").className = "thinking";
usernameRequest = createRequest();
if (usernameRequest == null)
alert("Unable to create request");
else {
var theName = document.getElementById("username").value;
var username = escape(theName);
var url= "checkName.php?username=" + username;
usernameRequest.onreadystatechange = showUsernameStatus;
usernameRequest.open("GET", url, true);
usernameRequest.send(null);
}
}
function showUsernameStatus() {
alert(usernameRequest.responseText);
if (usernameRequest.readyState == 4)
{
if (usernameRequest.status == 200) {
if (usernameRequest.responseText == "okay") {
document.getElementById("username").className = "approved";
document.getElementById("register").disabled = false;
}
else {
document.getElementById("username").className = "denied";
document.getElementById("username").focus();
document.getElementById("username").select();
document.getElementById("register").disabled = true;
}
}
}
}
checkName.php
<?php
$takenUsernames = array('bill', 'ted');
sleep(2);
if (!in_array($_REQUEST['username'],$takenUsernames )) {
echo 'okay';
} else {
echo 'denied';
?>
Previously, I tried to integrate PHP into tomcat, but I was advice it was not a good practice. TRIAL TO INTEGRATE PHP
What I can make out of this situation is that Tomcat is not parsing PHP file and instead it is returning the source code. I believe there should be a means for me to let tomcat parse php files and send the right response.
I have also tried with simple php code, with one statment <?php echo 'HELLO'; ?> and I still get the source code.
Thanks in advance.
NOTE : I do not know php, I am working an example from HEAD FIRST AJAX
you need to install PHP for Tomcat & set its path to compile it.see the below link for php configuration settings.
http://php-java-bridge.sourceforge.net/doc/tomcat6.php
http://www.studytrails.com/blog/php-on-a-java-app-server-apache-tomcat-using-quercus/
My question is NOT about how to solve the Access-Control-Allow-Origin issues. This errors will happen sometimes when performing requests, and other times the url's might be outdated. But I want to print different messages for the user depending on the different errors.
Currently I have the following code:
$.ajax(
{
url: link,
type:'HEAD',
timeout: 2000,
error: function(request, status, message)
{
console.log('ajax error');
console.log(request);
console.log(status);
console.log(message);
openPopUp("There was an error accessing the image. It can be because the address is invalid, "+
"or because the server where the image is stored is not allowing direct access to the images.");
},
success: function()
{
// More stuff here
}
});
Looking at the console it's easy to see if the file was actually missing, or if it was an Access-Control problem. But i'd like to print out two different messages to the user saying exactly what the problem was. Looking at the variables in error: function(request, status, message) they do not change, both cases result in a 404 error. Is there some other was to do this so that I can know what the problem was?
Thank you in advance for the attention.
Your browser console shows you
XMLHttpRequest cannot load http://www.google.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mysite.com' is therefore not allowed access.
but you cannot access this information yourself with JavaScript alone. When a browser detects a CORS violation, it will discard the header information as a matter of protocol.
One solution that works is to inspect the response headers using server-side code and pass the results back to your client page. For example, if the ajax request fails, you could call this script (let's call it cors.php) and know for certain if it contains "Access-Control-Allow-Origin" or not.
Example:
cors.php?url=http://ip.jsontest.com
cors.php?url=http://www.google.com
returns
Access-Control-Allow-Origin: *
None
Thus, you can do the following in your JavaScript code:
$.ajax({
url: "http://www.google.com",
timeout: 4000,
statusCode: {
404: function() {
// Simple not found page, but not CORS violation
console.log(this.url + " not found" );
}
}
})
.fail(function(jqXHR, textStatus) {
// Empty status is a sign that this may be a CORS violation
// but also check if the request timed out, or that the domain exists
if(jqXHR.status > 0 || jqXHR.statusText == "timeout") {
console.log("Failure because: "+jqXHR.status+" "+jqXHR.statusText+" error");
return;
}
// Determine if this was a CORS violation or not
console.log("Checking if this is a CORS violation at - " + this.url);
$.ajax({
url: "http://myserver.net/cors.php?url=" + escape(this.url),
})
.done(function(msg) {
// Check for the Access-Control-Allow-Origin header
if(msg.indexOf("Access-Control-Allow-Origin") >= 0) {
console.log("Failed bacause '" + msg + "'");
} else {
console.log("Failed bacause of CORS violation");
}
});
})
.done(function(msg) {
// Successful ajax request
console.log(msg);
}); /* Drakes, 2015 */
Customize this PHP script for your own needs:
<?php
/* cors.php */
$url = $_GET["url"];
if(isset($url)) {
$headers = getHeaders($url, "Access-Control-Allow-Origin");
header("Access-Control-Allow-Origin: *"); // Allow your own cross-site requests
echo count($headers) > 0 ? $headers[0] : "None";
}
// Get the response headers, only specific ones
function getHeaders($url, $needle = false) {
$headers = array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'HEAD'); // Only get the headers
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($curl, $header_line) use(&$headers, $needle) {
if(!$needle || strpos($header_line, $needle) !== false) {
array_push($headers, $header_line);
}
return strlen($header_line);
});
curl_setopt($ch, CURLOPT_URL, $url);
curl_exec($ch);
return $headers;
} /* Drakes, 2015 */
You should be able to read the response header from the request object:
var acao = request.getResponseHeader('Access-Control-Allow-Origin');
then output the appropriate error based on whether the header exists and whether your url is in the value.