I need to find out if a page is returning a 404 or 301 status code. I know I can write a php script to use cURL to return a value for javascript to read, but I am trying to simplify the process and kinda new. Right now I have an onBlur function that makes sure the webpage is at least in the correct format before they leave the field. But I would like it to also check the status of the page and I can't seem to find a solution for using cUrl directly with javascript or any examples of how this would be done. Anybody care to help me out please? Here is my validate.js that I am calling on the page...
function loadXMLDoc() {
var url = document.getElementById("webpage_url").value;
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("valid").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "custom/modules/CT221_SEP_test/js/curltest.php/" + url, true);
xmlhttp.send();
}
function isURL() {
var url = document.getElementById("webpage_url");
var urlerr = document.getElementById("url_error");
var reg = /http:\/\/[A-Za-z0-9\.-]{3,}\.[A-Za-z]{3}/;
if (!reg.test(url.value)) {
urlerr.innerHTML = "Invalid WebPage Address";
url.focus();
} else {
loadXMLDoc();
urlerr.innerHTML = //calls success image";
}
}
YAHOO.util.Event.on("webpage_url", "blur", isURL);
then my curltest.php file looks like this...
$url = $_GET['url'];
function validateurl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_NOBODY, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
preg_match("/HTTP\/1\.[1|0]\s(\d{3})/", $data, $matches);
return $matches[1];
}
$code = validateurl($url);
if ($code != "404") {
echo "Webpage is valid";
} else[
echo "Webpage is not live";
}
Sounds like a simple case of creating a PHP proxy script. The function that validates the URL could (on success) call an AJAX function to a PHP scrip, passing the URL so that you can make a cURL request to it. Instead of pinging the website directly, you could opt use some sort of DNS lookup. Upon your PHP script finishing, you can return some sort of value/data to the AJAX function which can act accordingly on the page. Chances are you will need to use callbacks on the client and server side so as not to hang the page, unless that is preferable to them moving on with the rest of the form. Your call.
Related
I am new to ajax. I wanted to create a simple webpage where it contains a button if clicked returns image dynamically.But the responseXML returns null value. Here is part of javascript code:
function process()
{
if(xmlhttp.readyState==4 || xmlhttp.readyState==0)
{
xmlhttp.open("GET","image.php",true);
xmlhttp.onreadystatechange = handleserverresponse;
xmlhttp.send();
}else{
setTimeout('process()',1000);
}
}
function handleserverresponse()
{
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){
xmlResponse = xmlhttp.responseXML;
imag = xmlResponse.documentElement.firstChild.data;
document.getElementById("divimg").innerHTML=imag;
}
else{
alert("something went wrong");
}
}
here is php code:
<?php
header('Content-Type:text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo "<res>";
echo "<img src="a.jpg"/>";
echo "</res>";
?>
Your HTTP request is asynchronous. xmlhttp.responseXML won't have some value until xmlhttp.readyState has the value of 4.
var url = "http://localhost/xml.php?type=xml";
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseXML);
}
};
xmlhttp.send();
}
Additionaly, I don't think you need the setRequestHeader line. XML MIME type is required for response, not for request. Also, please respect good coding practices (don't forget var, DRY, etc.)
The reason responseXML was null because there is a mistake in PHP file.
I guess We cannot send HTML tags when content type is xml. Instead what we can do is echo source of image and modify JavaScript file to take that source and display using img tag.
I am hoping this is a simple issue. I am using the Mailchimp API to submit a simple email signup form from my website. I am trying to learn javascript right now, so I am trying to do the httprequest and callback without jQuery. Basically, I am trying to convert this jQuery sample I found online to vanilla Javascript. But there is something (several things?) wrong with my javascript that I don't understand.
EDIT: When the form is submitted, I am taken to the email-validate.php page, and show the following error object returned by MailChimp.
{"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/","title":"Invalid Resource","status":400,"detail":"The resource submitted could not be validated. For field-specific details, see the 'errors' array.","instance":"","errors":[{"field":"","message":"Required fields were not provided: email_address"},{"field":"email_address","message":"Schema describes string, NULL found instead"}]}
jQuery
Found here (this actually throws an ajax(...).success is not a function error in the console but still submits the form, FWIW)
$('document').ready(function(){
$('.mc-form').submit(function(e){
//prevent the form from submitting via the browser redirect
e.preventDefault();
//grab attributes and values out of the form
var data = {email: $('#mc-email').val()};
var endpoint = $(this).attr('action');
//make the ajax request
$.ajax({
method: 'POST',
dataType: "json",
url: endpoint,
data: data
}).success(function(data){
if(data.id){
//successful adds will have an id attribute on the object
alert('thanks for signing up');
} else if (data.title == 'Member Exists') {
//MC wil send back an error object with "Member Exists" as the title
alert('thanks, but you are alredy signed up');
} else {
//something went wrong with the API call
alert('oh no, there has been a problem');
}
}).error(function(){
//the AJAX function returned a non-200, probably a server problem
alert('oh no, there has been a problem');
});
});
});
My Javascript (that doesn't work)
document.addEventListener("DOMContentLoaded", function() {
document.getElementById("mc-form", function submit(e){
e.preventDefault();
var data = {"email": document.getElementById("mc-email").value};
var endpoint = document.getElementById("mc-form").getAttribute('action');
function formSubmit(callback){
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
//Parse returned string into an object, then pass the object to the callback function.
var response = JSON.parse(request.responseText);
callback(response);
} else {
console.log('JSON request error');
}
}
}
request.open("POST", endpoint , true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send(data);
}
function formResponse(response){
if(response.id){
//successful adds will have an id attribute on the object
alert('Thank you for signing up for Launch Alerts!');
} else if (response.title == 'Member Exists') {
//MC wil send back an error object with "Member Exists" as the title
alert('You are already signed up for Launch Alerts!');
} else {
//something went wrong with the API call
alert('Something went wrong. Please resubmit the form!');
}
}
formSubmit(formResponse);
})
});
My html
<form class="mc-form" method="POST" action="./email-validate.php">
<h2 class="launch-alerts">Never miss a launch with Launch Alerts</h2>
<label for="mc-email">Email Address:</label>
<input type="email" id="mc-email" name="mc-email" autofocus="true" required/>
<input type="text" value="pending" id="status" name="status" hidden/>
<input type="submit" value="Submit">
</form>
It uses a php file to validate and submit the form, as can be seen on the link above. The html and php work to submit the form when using the jQuery script, but not my javascript, which means there is something wrong with my script, but I am too new with javascript to fully understand what it is I am trying to do, and what I am doing wrong.
Thanks!
EDIT 2:
The PHP code (copied directly from here
<?php
//fill in these values for with your own information
$api_key = 'xxxxxxxxxxxxxxxxxxxxxxxx';
$datacenter = 'xxxxx';
$list_id = 'xxxxxxxxx';
$email = $_POST['email'];
$status = 'pending';
if(!empty($_POST['status'])){
$status = $_POST['status'];
}
$url = 'https://'.$datacenter.'.api.mailchimp.com/3.0/lists/'.$list_id.'/members/';
$username = 'apikey';
$password = $api_key;
$data = array("email_address" => $email,"status" => $status);
$data_string = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, "$username:$api_key");
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result=curl_exec ($ch);
curl_close ($ch);
echo $result;
?>
The data argument to request.send() must be a URL-encoded string, you're passing an object. jQuery does this conversion automatically for you; when you do it yourself, you have to do that yourself as well.
var data = "email=" + encodeURIComponent(document.getElementById("mc-email").value);
You're also not adding your submission function to the form's submit event correctly. It should be:
document.getElementById("mc-form").addEventListener("submit", function submit(e){
You can add URL Parameters manually to the URL:
var endpoint = document.getElementById("mc-form").getAttribute('action') +
"?email=" + document.getElementById("mc-email").value;
And then only do
request.send();
without the data in it.
I have an issue with the Internet Explorer/EDGE browser. Basically, I have a script that pulls data from a remote XML file and displays it in page (live example: http://www.oldiesplus.com/ - The Radio info section, top of the page)
The way it works is that every 15 seconds, the XML file is read and the Song Title is updated (that's the scrolling bit). This works perfectly in Google Chrome, under IE/EDGE, however, the script executes (see Console log) but the element is never updated.
The XML file is grabbed using Curl and CURLOPT_FRESH_CONTENT is set to true.
The question being then, why is the element not updating with the new content in IE/EDGE?
Here's some code to help:
sc_conn.inc (PHP):
$ch = curl_init($sc_host . '/admin.cgi?mode=viewxml');
curl_setopt($ch, CURLOPT_PORT, $sc_port);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, $sc_admin.':'.$sc_pass);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, TRUE);
$curl = curl_exec($ch);
shoutcast.js (JavaScript):
function getStreamData() {
var ajax;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
} else {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.open('GET','/sc_data.php', true);
ajax.send();
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var data = ajax.responseText.split("|");
var song = (data[1] == '') ? 'some music.' : data[1];
var cta = (player_state == 0) ? '/new/img/play.png' : '/new/img/pause.png';
if (data[2]) {
document.getElementById('radio-info').innerHTML = '<h2>'+data[2]+'</h2>';
document.getElementById('radio-info').innerHTML += '<p><span class="dj_name">'+data[0]+' is playing</span> '+song+'</p>';
}else{
document.getElementById('radio-info').innerHTML = '<p><span class="dj_name">'+data[0]+' is playing</span> '+song+'</p>';
}
document.getElementById('tunein').src = cta;
console.log("Title Updated!");
}
}
}
The resolution was to circumvent caching of the AJAX request - appending a random number to the end of the call of the PHP script using:
Math.random();
Here i want to pass the 'q' value from ajax to controller function in codeigniter.
ajax code:
function getdata(str)
{
if (str == "") {
document.getElementById("yer").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("bus").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","<?php echo site_url('money_c/taxcalculator1'); ?>?q="+str,true);
xmlhttp.send();
window.location="<?php echo site_url('money_c/taxcalculator'); ?>"
}
}
controller:
function taxcalculator1()
{
$bt=$_GET['q'];
echo $bt;
}
Here i want to pass the 'q' value from ajax to controller function in codeigniter.
As soon as you have started the Ajax request sending with this:
xmlhttp.send();
You leave the page with this:
window.location="<?php echo site_url('money_c/taxcalculator'); ?>"
… which aborts the Ajax request, removes the place you are trying to edit with innerHTML and destroys the JavaScript that would be trying to do that anyway.
If you want to use Ajax then:
Put the data you want to show to the user the response from taxcalculator1
Use onreadystatechange to show it to the user
Don't leave the page before that happens (remove the window.location line).
If you want to load an entirely new page:
Don't use Ajax
Just submit a form to a URL
Display the data you want the user to see (in the form of an HTML document) in the response to that request
I've got a client side js/ajax script like this:
<p>server time is: <strong id="stime">Please wait...</strong></p>
<script>
function updateAjax() {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState==3 && xmlhttp.status==200) {
document.getElementById("stime").innerHTML=
xmlhttp.responseText;
}
if (xmlhttp.readyState==4) {
xmlhttp.open("GET","date-sleep.php",true);
xmlhttp.send();
}
}
xmlhttp.open("GET","date-sleep.php",true);
xmlhttp.send();
}
window.setTimeout("updateAjax();",100);
</script>
And a on the server side:
<?php
echo 6;
for ($i=0; $i<10; $i++) {
echo $i;
ob_flush(); flush();
sleep(1);
}
?>
After first 'open' and 'send' it works ok, but when the server finishes the script and xmlhttp.readyState == 4 then the xmlhttp resends the request but nothing happens.
Instead of re-using the same XHR object all the time, try repeating the function with a new object. This should at least fix incompatibility issues as you listed.
Try re-calling your Ajax function inside the callback of it, if you want to loop it infinitely.
if (xmlhttp.readyState==4) {
updateAjax(); //or setTimeout("updateAjax();",100); if you want a delay
}
I'd also suggest putting your .innerHTML method inside the .readyState==4, which is when the requested document has completely loaded, and .status==200 which means success. Like this:
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("stime").innerHTML=
xmlhttp.responseText;
updateAjax(); //or setTimeout("updateAjax();",100);
}
Also, if you want your Ajax to be cross-browser, you should test if the browser supports the XHR object which you're using:
var xmlhttp = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
I just typed the code above but it should work just fine to add compatibility with older versions of IE and other browsers.