How can I make an ajax captcha with confirmation by the url? - javascript

I'm trying to make a form in a website.
This form works sending with Ajax some data in the url to a php file and showing the response.
Is there any way to add a captcha in the url of the ajax and make the php check the captcha?
Thanks
My idea of Script:
<script>
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds) {
break;
}
}
}
function loadDoc() {
var cap = document.getElementById('captcha_code').value
document.getElementById("captcha_code").value = "";
var search = document.getElementById('nombre').value
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("box").innerHTML = xhttp.responseText;
sleep(500);
eval(document.getElementById("runscript").innerHTML);
}
};
xhttp.open("GET", "request.php?nombre=" + escape(search) + "&code=" + cap, true);
xhttp.send();
}
</script>

What crap is this?
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds) {
break;
}
}
}
You have something called setTimeout();. Please use that. And if you are using jQuery, please try this:
$.post(url, data, function (resp) {
// stuff to do when something returns from the server `resp`.
});

To get the captcha code in you PHP file you need to use $_GET('code') instead of GET(reCAPTCHA). You could also check if the permissions the php file has.

Related

XMLHttpRequest looping

I know this question has been asked before, but I tried to apply the answers with no results.
I'm trying to do multiple requests on the same domain with a for loop but it's working for the entire record of my array.
Here is the code I use:
function showDesc(str) {
var prod = document.getElementsByName("prod_item[]");
var xhr = [], i;
for (i = 0; i < prod.length; i++) {
var txtHint = 'txtHint10' + i;
(function(i) {
var xhr = new XMLHttpRequest();
var url = "getDesc.php?q=" + str;
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById(txtHint).innerHTML = xhr.responseText;
}
};
xhr.open("GET", url, false);
xhr.send();
})(i);
}
}
PHP
<select name="prod_item[]" id="prod_item.1" onchange="showDesc(this.options[this.selectedIndex].value)"></select>
<div id="txtHint100"></div>
and then I will use dynamic table for the prod_item field and div_id.
Is there any mistake in my code?

selection in a loop freezes my page

i'm a complete newbie when it comes to Js, trying to make some very simple script that takes a string of binary numbers from a txt document on my server using ajax, to then put it in a string var and change the first 0 it finds in a 1, using an if construct inside a loop.
Problem is, when the page tries to execute the if line, it simply freezes. Taking the same if construct out of the loop, the script is executed no problem, so i'm guessing it has something to do with either that or/and some fundamental misunderstanding of how Js scripts works in the first place.
Here is the script:
function loadPos()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
document.getElementById("demo").innerHTML = this.responseText;
};
xhttp.open("GET", "posizioni.txt", true);
xhttp.send();
}
function takeFirst()
{
var i=0;
var check=false;
var oldPos=[];
loadPos();
oldPos = document.getElementById("demo").innerHTML;
for(i=0;!check||i<10;i++)
{
if(oldPos[i]=="0")
{
oldPos[i]="1";
check=true;
}
}
document.getElementById("demo").innerHTML=oldPos;
}
I don't see any use of loop in it if you can achieve the same without it. Please update your function to the following:
function takeFirst()
{
loadPos();
var oldPos = document.getElementById("demo").innerHTML;
if(oldPos.indexOf("0") > -1){
oldPos = oldPos.replace('0', '1');
}
document.getElementById("demo").innerHTML = oldPos;
}
I think you want for(i=0;!check && i<10;i++).
But there is another way to do this using break;
function loadPos()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
document.getElementById("demo").innerHTML = this.responseText;
};
xhttp.open("GET", "posizioni.txt", true);
xhttp.send();
}
function takeFirst()
{
var i=0;
var oldPos=[];
loadPos();
oldPos = document.getElementById("demo").innerHTML;
for(i=0;i<10;++i)
{
if(oldPos[i]=="0")
{
oldPos[i]="1";
break;
}
}
document.getElementById("demo").innerHTML=oldPos;
}

How do I pull a JSON file that is separate from a RESTFUL API's functions as an authenticated user via an API?

I need to simulate an authenticated user to pull a JSON file. I am using Last.fm's API, but there is currently no method to pull the specific data I want. If I just pull it as plain text in browser, it shows up. However, I want data that is specific to an authenticated user. So, if I login to Last.fm as me, then pull the data, the data is different than if I just pull the data from anywhere.
Basically, the data contained in this file is specific to the user, and as there is no function specifically set to access this file, I don't know how I'd do that....
My function that pulls the current data is listed below:
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
}
function getRadio() {
var trackUrls = new Array();
var resValue;
var station;
var radioStation;
var url;
var data;
var neatDisplay;
var resultsDisplay = document.getElementById('result');
var radioTypeInput = document.getElementsByName('radioType');
var queryInput = document.getElementById('query');
var query = queryInput.value;
for (var i = 0, length = radioTypeInput.length; i < length; i++) {
if (radioTypeInput[i].checked) {
station = radioTypeInput[i].value;
break;
}
}
if (station == 1) {
radioStation = "recommended";
} else if (station == 2) {
radioStation = "library";
} else if (station == 3) {
radioStation = "mix";
} else {
radioStation = "music";
};
if (radioStation != "music") {
url = "https://crossorigin.me/" + "http://www.last.fm/player/station/user/" + query + "/" + radioStation;
} else {
url = "https://crossorigin.me/" + "http://www.last.fm/player/station/music/" + query;
};
console.log(url);
request = createCORSRequest("get", url);
if (request) {
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
data = JSON.parse(request.responseText);
for (i = 0; i < data.playlist.length; i++) {
trackUrls[i] = data.playlist[i].playlinks[0].url;
}
neatDisplay = trackUrls.join("\n ");
resultsDisplay.innerHTML = neatDisplay;
console.log(neatDisplay.toString());
neatDisplay = neatDisplay.toString();
return neatDisplay.toString();
} else if (request.status == 503) {
resultsDisplay.innerHTML = "Connection Error. The application may be overloaded."
} else {}
};
request.onerror = function() {
document.getElementById("result").innerHTML = "Connection Error. The application may be overloaded. Try again later"
};
request.send();
}
}
Ultimately, this used to pull Spotify links in the resulting data, but now it pulls YouTube. So, the problem only occurs if just pulling the file, without authentication.

update function on ajaxObject

When a button is clicked on the webpage a table of data is displayed. I want to scrape that data but I can't find where it comes from in the website source code.
This is the tag for the button:
<button type="submit" onclick="divChangeStateOn('load-raw-0062294377Amazon.com'); getRaw('0062294377', 'Amazon.com', 'lr-0062294377Amazon.com',this);"style="margin-bottom: 4px; width: 120px; text-align: left;" name="load-raw"><img src='images/workstation.png'/> raw data</button>
I believe that the getRaw function is where the data comes from (I'm not positive about this) so I looked at the javascript code for the getRaw function
function getRaw(asin, store, res, caller)
{ document.getElementById(res).innerHTML = '<p align="center" valign="top"><img align="center" src="phpmy_loading.gif"></p>';
var poststr = "raw=" + encodeURI(asin) +
"&site=" + encodeURI(store);
var updateResults = new ajaxObject(res, 'extra.php', caller);
updateResults.update(poststr);
}
I have been having a hard time finding any documentation about ajaxObject and can't find any information about the update function. What is ajaxObject.update doing and is it possible for me to access the data that appears when the button is clicked?
function divChangeStateOn(divID)
{ var divElem = document.getElementById(divID);
divElem.style.display = 'block';
}
EDIT: The link to the source code view-source:http://www.ranktracer.com/account_workstation.php it might be password protected but I was just using the demo version
EDIT 2:
I am basically trying to write a script that replicates the Ajax http request. This where I am at, it doesn't work and I am especially concerned about where data = uri
x = time.time()
print x
timestamp = datetime.fromtimestamp(x/1000.0)
print timestamp
uri = "raw=0062294377&site=Amazon.com&timestamp="+str(timestamp);
url = "lr-0062294377Amazon.com"
length = str(len(uri))
headers = {'X-Requested-With': 'XMLHttpRequest',
"Content-type": "application/x-www-form-urlencoded",
"Content-length": length,
"Connection" : "close"}
s = Session()
r = s.post(url= url, data= uri, headers= headers)
The entire code for ajaxObject is present in the link you provided. Please let us know what help you are expecting here?
function ajaxObject(layer, url, caller) {
if (caller) {
disableButton(caller, 'disable');
}
var that = this;
var updating = false;
this.callback = function() {}
var LayerID = document.getElementById(layer);
this.update = function(passData) {
if (updating == true) {
return false;
}
updating = true;
var AJAX = null;
if (window.XMLHttpRequest) {
AJAX = new XMLHttpRequest();
} else {
AJAX = new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX == null) {
alert("Your browser doesn't support AJAX.");
return false
} else {
AJAX.onreadystatechange = function() {
if (AJAX.readyState == 4 || AJAX.readyState == "complete") {
if (caller) {
disableButton(caller, 'enable');
}
LayerID.innerHTML = AJAX.responseText;
delete AJAX;
updating = false;
that.callback();
}
}
var timestamp = new Date();
var uri = passData + '&timestamp=' + (timestamp * 1);
AJAX.open("POST", url, true);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.setRequestHeader("Content-length", uri.length);
AJAX.setRequestHeader("Connection", "close");
AJAX.send(uri);
return true;
}
}
}

Ajax Call Only Works the First Time

My JavaScript/ajax code works the first time, but not there after. The GetAttribute element is null when the function is called again. I have try using createElement and AppendChild, but it does the same thing. If I didn't need the getAttribute it would work fine, but I cannot get the function to work with the getAttribute method. Any help would be appreciated.
function ajaxFunction(Picked) {
var getdate = new Date();
if(xmlhttp) {
var Pic1 = document.getElementById("Pic1").getAttribute("name");
var Pic2 = document.getElementById("Pic2").getAttribute("name");
if (Picked === Pic1 ){
var Chosen = Pic1;
var NotChosen = Pic2;
}
else {
var Chosen = Pic2;
var NotChosen = Pic1;
}
xmlhttp.open("POST","choice.php",true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("Chosen=" + Chosen + "&NotChosen=" + NotChosen );
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
var response = xmlhttp.responseText;
response = response.split("|");
document.getElementById('Pic1').innerHTML = response[0];//New Pic
document.getElementById('Pic2').innerHTML = response[1];
}
else {
alert("Error. Please try again");
}
}
}
Change your if to
if (Picked === Pic1)
By writing if (Picked = Pic1 ), you're assigning Picked to Pic1.

Categories