having a minor issue with this javascript+ajax - javascript

am trying to translate information, when i use the following code, it runs successfully, as i have given the textarea information in prior
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-2" />
<title>Example Ajax POST</title>
<script type="text/javascript"><!--
// create the XMLHttpRequest object, according browser
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
// sends data to a php file, via POST, and displays the received answer
function ajaxrequest(php_file, tagID, tolang) {
if(tolang=="-")return;
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
// create pairs index=value with data that must be sent to server
var the_data = 'data='+document.getElementById('txt2').innerHTML+'&to='+tolang;
request.open("POST", php_file, true); // set the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById(tagID).innerHTML = request.responseText;
}
}
}
--></script>
</head>
<body>
<textarea id="txt2" rows="20" cols="50">hi wassup</textarea><br/>
<select name="langlist" onchange="ajaxrequest('translator.php', 'txt2', this.options[this.selectedIndex].value)">
<option value="-" selected>-</option>
<option value="ar">Arabic</option><option value="bg">
Bulgarian</option><option value="ca">
Catalan</option><option value="zh-CHS">
Chinese Simplified</option><option value="zh-CHT">
Chinese Traditional</option><option value="cs">
Czech</option><option value="da">
Danish</option><option value="nl">
Dutch</option><option value="en">
English</option><option value="et">
Estonian</option><option value="fi">
Finnish</option><option value="fr">
French</option><option value="de">
German</option><option value="el">
Greek</option><option value="ht">
Haitian Creole</option><option value="he">
Hebrew</option><option value="hi">
Hindi</option><option value="mww">
Hmong Daw</option><option value="hu">
Hungarian</option><option value="id">
Indonesian</option><option value="it">
Italian</option><option value="ja">
Japanese</option><option value="ko">
Korean</option><option value="lv">
Latvian</option><option value="lt">
Lithuanian</option><option value="no">
Norwegian</option><option value="pl">
Polish</option><option value="pt">
Portuguese</option><option value="ro">
Romanian</option><option value="ru">
Russian</option><option value="sk">
Slovak</option><option value="sl">
Slovenian</option><option value="es">
Spanish</option><option value="sv">
Swedish</option><option value="th">
Thai</option><option value="tr">
Turkish</option><option value="uk">
Ukrainian</option><option value="vi">
Vietnamese</option>
</select><img src="http://www.allsaints-sec.glasgow.sch.uk/Images/QuestionMarkIcon16.gif" title="plz save your copy of data, as there will be chances of data loss during translation"/>
</body>
</html>
if you remove the text in textarea before initial load of page, then the translation is not working, as shown in below code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-2" />
<title>Example Ajax POST</title>
<script type="text/javascript"><!--
// create the XMLHttpRequest object, according browser
function get_XmlHttp() {
// create the variable that will contain the instance of the XMLHttpRequest object (initially with null value)
var xmlHttp = null;
if(window.XMLHttpRequest) { // for Forefox, IE7+, Opera, Safari, ...
xmlHttp = new XMLHttpRequest();
}
else if(window.ActiveXObject) { // for Internet Explorer 5 or 6
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
// sends data to a php file, via POST, and displays the received answer
function ajaxrequest(php_file, tagID, tolang) {
if(tolang=="-")return;
var request = get_XmlHttp(); // call the function for the XMLHttpRequest instance
// create pairs index=value with data that must be sent to server
var the_data = 'data='+document.getElementById('txt2').innerHTML+'&to='+tolang;
request.open("POST", php_file, true); // set the request
// adds a header to tell the PHP script to recognize the data as is sent via POST
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(the_data); // calls the send() method with datas as parameter
// Check request status
// If the response is received completely, will be transferred to the HTML tag with tagID
request.onreadystatechange = function() {
if (request.readyState == 4) {
document.getElementById(tagID).innerHTML = request.responseText;
}
}
}
--></script>
</head>
<body>
<textarea id="txt2" rows="20" cols="50"></textarea><br/>
<select name="langlist" onchange="ajaxrequest('translator.php', 'txt2', this.options[this.selectedIndex].value)">
<option value="-" selected>-</option>
<option value="ar">Arabic</option><option value="bg">
Bulgarian</option><option value="ca">
Catalan</option><option value="zh-CHS">
Chinese Simplified</option><option value="zh-CHT">
Chinese Traditional</option><option value="cs">
Czech</option><option value="da">
Danish</option><option value="nl">
Dutch</option><option value="en">
English</option><option value="et">
Estonian</option><option value="fi">
Finnish</option><option value="fr">
French</option><option value="de">
German</option><option value="el">
Greek</option><option value="ht">
Haitian Creole</option><option value="he">
Hebrew</option><option value="hi">
Hindi</option><option value="mww">
Hmong Daw</option><option value="hu">
Hungarian</option><option value="id">
Indonesian</option><option value="it">
Italian</option><option value="ja">
Japanese</option><option value="ko">
Korean</option><option value="lv">
Latvian</option><option value="lt">
Lithuanian</option><option value="no">
Norwegian</option><option value="pl">
Polish</option><option value="pt">
Portuguese</option><option value="ro">
Romanian</option><option value="ru">
Russian</option><option value="sk">
Slovak</option><option value="sl">
Slovenian</option><option value="es">
Spanish</option><option value="sv">
Swedish</option><option value="th">
Thai</option><option value="tr">
Turkish</option><option value="uk">
Ukrainian</option><option value="vi">
Vietnamese</option>
</select><img src="http://www.allsaints-sec.glasgow.sch.uk/Images/QuestionMarkIcon16.gif" title="plz save your copy of data, as there will be chances of data loss during translation"/>
</body>
</html>
am not getting the point in here, can anyone tell me why is this problem.

It probably doesn't work, because document.getElementById('txt2').innerHTML is null when you remove text from textarea. Check this function in firefox&firebug for possible errors/warnings. You could also provide some more data about your problem - what exactly happens.

I don't know really why it doesn't work. In fact your code changing innerHTML in the first example just work the fist time on chrome, and in a old IE both work always.
And I don't think innerHTML belongs to a W3C standard, if you change to value both will work always. Like:
var the_data = 'data='+document.getElementById('txt2').value+'&to='+tolang;
and
document.getElementById(tagID).value = request.responseText;
EDIT:
Writing standards compliant code is allways good =)

Related

Bring over php variable through ajax into html tag

So i'd like to auto check the boxes based on the data from my database, whenever i click a table row. I'm currently using an AJAX script for this table row click, however, i can't figure out how to bring over the php variable value onto my main file's php variable and replace the value, from my other php file where i'm performing the AJAX php codes.
this is my main file's check box.
<input type="checkbox" name="skincareinuse[]" value="Lotion" <?php if(in_array("Lotion",$skincareinuse)) { ?> checked="checked" <?php } ?>/>Lotion<br>
this is my other php file where my AJAX script is drawing values from. I've done an explode and stored them in a php variable.
$skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
The problem is that in the php file where my AJAX script is drawing values from, the variable $skincareinuse could not be updated into $skincareinuse on my main php file.
Let's say even if i am able to use JSON to bring the value over, how do i go about storing it since JSON is being encoded into javascript?
Sorry if I didn't explain it right, please help!
#Iceman, is it possible to run .ajax function in an ajax script?
function showconsultationdata(str) { //face e.g and checkboxes for that date selected.
var xmlhttp;
if (str == "") {
document.getElementById("txtHint2").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("txtHint2").innerHTML = xmlhttp.responseText;
var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
$("textarea#skinconditionremarks").val(a.skinconditionremarks);
$("textarea#skincareremarks").val(a.skincareremarks);
$.ajax({
url: "BAConsultRecordsAJAX.php"
})
.done(function(data) {
console.log(data);
selectTestAnswer(data.key + "[]", data.value)
})
.fail(function() {
alert("error");
})
}
}
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
EXAMPLE:
$('#mybutton').click(function() {
$.ajax({
//sample json, replace with your data
url: "http://echo.jsontest.com/key/skincareinuse/value/Lotion"
})
//if data retrieval was successfull
.done(function(data) {
console.log(data);
//got data as json from server. NOw lets update the page(DOM).
selectTestAnswer(data.key + "[]", data.value)
})
//if data retrieval was a failure
.fail(function() {
alert("error");
})
});
//a simple function that if called with say with skincareinuse[] and Lotion marks the corresponding checkbox.
var selectTestAnswer = function(chkbox, value) {
$("[name='" + chkbox + "']").each(function() {
if ($(this).val() == value)
$(this).attr('checked', true);
else
if ($(this).attr('checked') == true)
$(this).attr('checked', false);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<input id="myinput" type="checkbox" name="skincareinuse[]" value="Lotion" />Lotion
<br>
<input id="myinput" type="checkbox" name="skincareinuse[]" value="Talcum" />Talcum
<br>
<script>
</script>
<br>
<br>
<button id="mybutton">RUN AJAX</button>
<br>
<br>this ajax calls this url : "http://echo.jsontest.com/key/skincareinuse/value/Lotion" returns this sample json:
<pre>
{
"value": "Lotion",
"key": "skincareinuse"
}
</pre>
</body>
</html>
I have demo-ed an example where the ajax reads the data from the server (here a test url) then update (ie. check the boxes) correspondingly.
This an example on how to do updation from AJAX. I suggest you read on how AJAX works.

Submit issues with form that interact with an API

I have a form that interacts with an API, I used a simple auto submit:
<script type="text/javascript">
window.setTimeout(function(){
document.getElementById('formSubmit').submit();
},1000*20);
</script>
and it worked great in the testing environment. We moved into a new environment and the setup of the hardware was slightly different, realized that didn't work and altered it. Now my auto submit isn't working. The API developers suggested I use watchdog instead so I applied a code according from #Drakes and modified it to interact with my application. This also did not work. I am a noob with Watchdog, and most things in the development world, did I skip a set up with watchdog that wasn't referenced in the previous question?
function watchdog() {
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5 - whatever, it doesn't hurt
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// This is how you can discover a server-side change
if(xmlhttp.responseText !== "<?php echo $currentValue; ?>") {
document.location.reload(true); // Don't reuse cache
}
}
};
xmlhttp.open("POST","page.php",true);
xmlhttp.send();
}
// Call watchdog() every 20 seconds
setInterval(function(){ watchdog(); }, 20000);
I think you haven't posted the field values [Fields of the form]. The AJAX code you have used is checking if some value got changed or not every 20 second. But as much as I can understand you wanted to submit your form every 20 second. In that case the AJAX post code need some editing. May be the following thing can solve your problem. Here I am assuming your form having two fields and hence two values are getting submitted. If you have more then you have to modify it as per your requirement.
EDITED MY TESTCODE (This is tested)
The html code along with the AJAX script is as follows -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script>
function watchdog(value1,value2) {
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5 - whatever, it doesn't hurt
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
// write any code as this block will be executed only after form succesfully submitted.
document.getElementById("showresponse").innerHTML = xmlhttp.responseText;
console.log(xmlhttp.responseText);// You can use this responseText as per your wish
}
}
xmlhttp.open("POST","process.php?value1="+value1+"&value2="+value2,true);
xmlhttp.send();
}
// Call watchdog() every 20 seconds
window.setInterval(function(){
var myForm = document.getElementById('formSubmit');
var value1 = myForm.elements["field1"].value;
var value2 = myForm.elements["field2"].value;
// thus store all required field values in variables ,
//here as instance I am assuming the form has two fields , hence posting two values
watchdog(value1,value2);
}, 20000);
function submitIt(){
var myForm = document.getElementById('formSubmit');
var value1 = myForm.elements["field1"].value;
var value2 = myForm.elements["field2"].value;
watchdog(value1,value2);
}
</script>
</head>
<body>
<form id="formSubmit">
<input type="text" name="field1" value="value1" />
<input type="text" name="field2" value="value2" />
<button type="button" onclick="submitIt();">Submit</button>
</form>
<div id="showresponse"></div>
</body>
</html>
The php code of process.php will be as follows -->
<?php
if(isset($_REQUEST['value1']) && isset($_REQUEST['value1']))
{
$value1 = $_REQUEST['value1'];
$value2 = $_REQUEST['value2'];
echo "Values are respectively : " .$value1." and ".$value2;
}
else
{
echo "Data not found";
}
?>
While testing the above code sample dont forget to keep both html and process.php files in same folder and then test it. The above shown "Run Code snippet" button will not show you any effect of the php code as it only runs html and javascript. So to test it properly you should keep it on some server - local or online .

Ajax Pull Content From another webpage

So I got this code for pulling rss feeds from another website (i asked them, and they gave me permission) I Don't know what should i Write in TAG1 and TAG2. Basically that is just my problem:
Here is the html (its an ajaxed page)
<!doctype html>
<html lang="hu">
<head>
<title>Videók</title>
<meta charset="utf-8"/>
<script type="text/javascript" src="../js/videok.js"></script>
</head>
<body>
<h2>Van egy jó videód? Töltsd fel és kikerülhet az oldalra!</h2>
<div id="videok"></div>
</body>
</html>
And here is the Javascript for pulling
window.onload = initAll;
var xhr = false;
var dataArray = new Array();
var url = "choose url";
function initAll() {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) { }
}
}
if (xhr) {
xhr.onreadystatechange = setDataArray;
xhr.open("GET", url, true);
xhr.send(null);
}
else {
alert("couldn't create XMLHttpRequest");
}
}
function setDataArray() {
var tag1 = "subject1";
var tag2 = "subject2";
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseXML) {
var allData = xhr.responseXML.getElementsByTagName(tag1);
for (var i=0; i<allData.length; i++) {
dataArray[i] = allData[i].getElementsByTagName(tag2)[0].firstChild.nodeValue;
}
}
}
else {
alert("the request failed" + xhr.status);
}
}
}
You won't be able to use javascript to pull from another web page because javascript is sandboxed when in browsers. Sandboxing means that you will only be able to send requests to the same domain that the javascript originally came from (also known as the 'same orgin policy').
You can use a serverside language like php to do the pulling and then hand it down to the javascript through ajax.
The code that you posted looks like it just makes a simple ajax call but it shouldn't work when trying to request an RSS from anything other than your own site.
It's better that you have the server side of your application fetch data for the xml and format the data how you want it.
You would have the Ajax request hit your server's end point, then your server will fetch the xml data, format it properly and respond to the request with the correct formatted data.

There is a long suffering, but I can not do cross- site request

What now is:
A page on localhost, which sends a request:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title></title>
<script language="javascript" type="text/javascript">
var script = document.createElement('script');
script.setAttribute('src', 'http://www.3dfind.ru/site/js.js');
document.getElementsByTagName('head')[0].appendChild(script);
</script>
</head>
<body>
<form method="get">
<div id='searchform'>
<table>
<td>
<input name='q' id='searchinput' type='text' value=''>
</td>
<td>
<select name='type' id='searchselect'>
<option value='1'>Val 1</option>
</select>
</td>
<td>
<input name='search' type='submit' onclick='MakeRequest();' value='Поиск!' id='searchsubmit'>
</td>
</table>
</form>
<div id='ResponseDiv'>
</div>
</body>
</html>
Then there js script on the server, which receives the request:
function getXMLHttp()
{
var xmlHttp
try
{
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
//Internet Explorer
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest()
{
var xmlHttp = getXMLHttp();
var params = 'q=' + encodeURIComponent(q) + '&type=' + encodeURIComponent(type) + '&search=' + encodeURIComponent(s)
xmlHttp.open("GET", '/result.php?'+params, true)
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('ResponseDiv').innerHTML = response;
}
If the file result.php search on the server, you get a url:
http://3dfind.ru/site/result.php?q=%E4%F4%E4%E4%F4%E4&type=1&search=%CF%EE%E8%F1%EA%21
Also in result.php I accept the GET- request :
$var = #$_GET['q'] ;
$s = $_GET['s'] ;
$typefile = $_GET['type'];
What am I doing wrong ?
Alright my man, I think you're a bit confused. Your HTML contains
<input name='search' type='submit' onclick='MakeRequest();' value='Поиск!' id='searchsubmit'>
And your Javascript contains
function MakeRequest()
but you say "Then there js script on the server, which receives the request:"
The Javascript should be on the client and sends the request.
Then I'm not even sure what you're trying to do and what's going wrong. Are you getting errors? Is it supposed to do something that it isn't?
Back to basics: use Firefox and install Firebug. Enable the "console". Open your page and do what you're trying to do. If you have Javascript errors, they'll show in the console. You can open every ajax request in the console as well so you can see if you're getting a server side error.
Yeah, I'm a bit confused what you're asking, here is a reference you may look into for cross-site xmlhttprequests here. There is another good reference to cross-site requests here also
From your other question ("cross-site request") I think I understand what you're trying to do. I think you're trying to get the results from "results.php" which is hosted in a different server.
What you need to do is change your MakeRequest() function. Instead of
xmlHttp.open("GET", '/result.php?'+params, true)
it should be
xmlHttp.open("GET", 'http://URL_OF_OTHER_SERVER/result.php?'+params, true);
Hope this helps.

why isn't my eval turning the json string into an object

When I execute the eval function it doesn't turn my json response into a object it just breaks my code. I've tried parsing with prototype.js and JSON2.js to no avail some please explain what I am doing wrong here?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<title>Inventory Management</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script src="call.js" type="text/javascript"></script>
<script src="prototype.js" type="text/javascript"></script>
</head>
<body>
<div>
<p id="resp" >new</p>
<script type="text/javascript">
var xhr;
var results=getPlants(xhr,results);
var plants;
function getPlants(xhr,results){
try {
xhr=new XMLHttpRequest();
}catch(microsoft){
try{
xhr=new ActiveXObject("Msxml2.XMLHTTP");
}catch(othermicrosoft){
try{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}catch(failed){
xhr=false;
alert("ajax not supported");
}
}
}
xhr.onreadystatechange= function () {
if(xhr.readyState==4 && xhr.status==200) {
results = xhr.responseText;
}
}
xhr.open("GET","db_interactions.php",true);
xhr.send(null);
alert("sent");
return results;
}
plants = eval('('+results+')');
document.write(typeof(plants));
</script>
</div>
</body>
</html>
You're issuing an asynchronous request. That means the function will return even when the data isn't ready yet. But your call assumes the JSON response is ready when getPlants is called. Which obviously makes results undefined because you aren't waiting for it.
Put your
plants = eval('('+results+')');
document.write(typeof(plants));
Inside the xhr.onreadystatechange function to make it work, or open the connection as synchronous
xhr.open("GET","db_interactions.php",false);
By the way, don't use eval to parse JSON because code may be injected maliciously. Use a JSON parser instead.

Categories

Resources