Getting user input for ajax post request? - javascript

I am going through the Ajax tutorial at:
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
They have this example for submitting request to a server:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
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("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","demo_post2.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
The problem I have with the above example is that the values for fname and lname are hardcoded. How can allow a user to enter different values for fname and lname via a <form> tag and still be able to use ajax javascript code?

created jsfiddle example for the same:-
http://jsfiddle.net/c2S5d/24/
added two inputs for fname and lname and fetched there values and set into the params.(As of now commented the code for ajax send) try above given link and enter some values into the text boxed and see the alert)
code:-
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
alert("calle")
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("myDiv").innerHTML = xmlhttp.responseText;
}
}
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value
//xmlhttp.open("POST","demo_post2.asp",true);
//xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var param = "fname=" + fname + "&lname=" + lname;
alert(param)
//xmlhttp.send(param);
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
<input type='text' id='fname' />
<input type='text' id='lname' />
</body>
</html>

Related

use numeric variable as str & increment it

I want to change the value of str used in ajax (str is the string inputted in the html form) part by giving it a variable value, so that by clicking on a button that changes the variable value, the loaded data row in mySQL changes. But it doesn't work. What can I do for this ?
(the ajax works, it's just that the button click doesn't change anything)
Here is the code:
<!DOCTYPE html>
<html>
<head>
<script>
var Pokemon_ID = 0
function changePokemon(str) {
document.getElementById("right-btn").onclick = function() {
Pokemon_ID++;
str = Pokemon_ID
}
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
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 (this.readyState==4 && this.status==200) {
document.getElementById("txtHint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","get_id.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
First name: <input type="text" onkeyup="changePokemon(this.value)">
</form>
<div id="txtHint"></div>
<a id="right-btn" onclick="changePokemon(str)"></a>
</body>
</html>
Just try this out and confirm if it works. I had tried to correct the code according to my understanding of your requirement.
<!DOCTYPE html>
<html>
<head>
<script>
function changePokemon() {
let str = document.getElementById("inpStr").value;
let tempStr=parseInt(str)+1;
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
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 (this.readyState==4 && this.status==200) {
document.getElementById("txtHint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","get_id.php?q="+tempStr,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form>
First name: <input type="text" id="inpStr" onkeyup="changePokemon()">
</form>
<div id="txtHint"></div>
<a id="right-btn" onclick="changePokemon()"></a>
</body>
</html>
Change your HTML codes to
<form>
First name:
<input type="text">
</form>
<div id="txtHint"></div>
<a id="right-btn" onclick="changePokemon(++ Pokemon_ID)">Go</a>
I dont know what does your changePokeMon() function do, but change your script to
var Pokemon_ID = 0
function changePokemon(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
}
xmlhttp.open("GET", "get_id.php?q=" + str, true);
xmlhttp.send();
}

How to load a script in a php file called from a Ajax Request?

I have this JavaScript:
<script>
if (str == "") {
document.getElementById("txtHint1").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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint1").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "/npsmart/umts/action_plano/?q=" + query1, true);
xmlhttp.send();
}
</script>
And this JavaScript call a page called getuser.php.
This is the code of getuser.php:
<!DOCTYPE html>
<html>
<body>
<p id="dumb"></p>
<script>
document.getElementById("dumb").innerHTML = "WORK";
</script>
</body>
</html>
What I would like is only to change the paragraph content, called dumb, to WORK. But when I call the page and it loads, my paragraph content keep null.
It's like my Ajax Call Request don't execute the Script Tag.
EDIT:
I have already solved my problem with this simple but genious solution:
function showUser() {
if(query_num == 2){
if (str == "") {
document.getElementById("txtHint1").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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint1").innerHTML = this.responseText;
eval(document.getElementById("runscript").innerHTML);
}
};
xmlhttp.open("GET","/npsmart/umts/action_plano/?q="+55555,true);
xmlhttp.send();
}
And in my getuser.php file:
<script type="text/javascript" id="runscript">
document.getElementById("dumb").innerHTML = "WORK";
</script>
I just putted the : eval(document.getElementById("runscript").innerHTML); in my function and then in the php file I called this script using this:
<script type="text/javascript" id="runscript">
So thanks everybody =)
Hope this post can help other people.
JS is not executed automatically from a script embedded in the response.
Since getuser.php is a PHP script there's no need to use JS and have the browser set the paragraph content. Use PHP itself:
<!DOCTYPE html>
<html>
<body>
<p id="dumb"><?php echo 'WORK'; /* or anything else */ ?></p>
</body>
</html>
Otherwise you'll have to use JS eval on the returned AJAX response to have the browser run the JS returned from your script. But I recommend against this.

Converting Text input to an actual parameter for javascript function

I need to convert the messbox value so it can be passed into the loadPHPDoc function, but i cannot seem to successfully transfer the data. It successfully loads the php document when i place quotation marks around the actual parameter, but i do not, it simply does not use the function, and does not work. Here's my code:
<!DOCTYPE html>
<html>
<body>
<p id="myDiv">no</p>
<script>
function loadPHPDoc(str){
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");
}
var url = "testSubmit.php";
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","testSubmit.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var sender = "q=" + str;
xmlhttp.send(sender);
document.getElementById("myDiv").innerHTML = str;
}
</script>
<p>Message <input type= "text" id="messbox"></p>
<button type= "button" onclick="loadPHPDoc(document.getElementById(messbox).value)">input</button>
</body>
</html>
document.getElementById() receives a string as a parameter, so:
<button type= "button" onclick="loadPHPDoc(document.getElementById('messbox').value)">input</button>

Ajax-HTML for doing simple calculator

Question: Implement a basic calculator application by getting the two operands and one operator from the form in a textbox. Also have a button called result and when the same is clicked display the result. Only the result part of the page must change
My code is here, but its not at all working, please help me in displaying the output
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script>
function showResult(id,url)
{
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");
}
var val1=document.form1.value1.value;
var valu1=parseInt(val1);
var val2=document.form1.value2.value;
var valu2=parseInt(val2);
var val3=document.form1.operator.value;
var result;
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("id").innerHTML=xmlhttp.responseText;
}
}
if("+"==val3)
{
result=valu1+valu2;
//alert(result);
}
else if("-".equals(val3))
{
result=val1-val2;
}
else if("*".equals(val3))
{
result=val1*val2;
}
else if("/".equals(val3))
{
result=val1/val2;
}
else
{
alert("choose oly +,-,*,/");
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
</head>
<body>
<form name=form1 method=get>
<input type=text name="value1">
<input type=text name="value2">
<input type=text name="operator">
<input type=button value="Result" name=result onClick="showResult('ajaxDiv','BasicCalc.html')">
</form>
<div id="ajaxdiv"> Your Result soon will be display here</div>
</body>
</html>

How to "search" through the response of an XMLHttpRequest

I have a question regarding the followng code
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
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)
{
return xmlhttp.responseText;
}
}
xmlhttp.open("GET","index.html",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
Now I want to search through the xmlhttp.responseText (in other words call the function loadXMLDoc()) for key words, like for example "testfile" and if it exists multiple example "testfile_1" and "testfile_2"....."testfile_n" then "doSomething"
like this
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
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)
{
return xmlhttp.responseText;
}
}
}
function searchADocument(wordToSearchFor){
xmlhttp.open("GET","index.html",true);
xmlhttp.send();
int numberOfTimesWordOccurs=0;
var thePageToSearchThrough [] = loadXMLDoc();
for (i=0; i<thePageToSearchThrough.length; i++){
if(thePageToSearchThrough[i]==wordToSearchFor)
numberOfTimesWordOccurs++;
}
If (numberOfTimesWordOccurs > 1)
document.write(" testfile_1" testfile_2 testfile_n
)
Else
window.location="http://selnc05.go.se:8080/component_test/build/testfile.html";
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="searchADocument("testfile")">Change Content</button>
</body>
</html>
I don't know where to start since I don't know what type xmlhttp.responseText is, can I store it in an array and scan it using for loop etc?
Thanks in advance. =)
EDIT
What am Im doing wrong here
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
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)
{
return xmlhttp.responseText;
}
}
xmlhttp.open("GET","index.html",true);
xmlhttp.send();
}
function searchADocument(){ //wordToSearchFor
var txt=loadXMLDoc();
if(txt.test('hello'))alert('responseText contains "hello"');
else{
document.getElementById("myDiv").innerHTML ="helloaj";
}
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="searchADocument()">Change Content</button>
</body>
</html>
get the following error message on if(txt.test('hello')) Jscript error:'undefined' is null or not an object
EDIT 3
Im guessing im just dumb as hell, but I still can't get this to work, why can't I store the xmlhttp.responseText into a variable?
Like this
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url,cfunc)
{
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=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction()
{
loadXMLDoc("ajax_info.txt",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var txt=xlmhttp.responseText;//This aint working, why, how can I store xlmhttp.responseText into a variable, that I can peform a search on?
document.getElementById("myDiv").innerHTML=txt;//This aint working, why?????
}
});
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction()">Change Content</button>
</body>
</html>
I can add that the above actually works if I replace the following
var txt=xlmhttp.responseText;
document.getElementById("myDiv").innerHTML=txt;
with this
document.getElementById("myDiv").innerHTML=xlmhttp.responseText;
I haven't got the call back function to work as mentiond below, all I get is that xmlhttp is undefined, so I ask on this that works(at least half the way I want it to).
Again sorry for not understanding, but there must be something obvious that I don't get about this, that this simply isn't possible to store this in a variable or something.
var txt=loadXMLDoc();
loadXMLDoc doesn't return anything, so txt is undefined after this. Of course undefined doesn't have the test method, which is a method of String.prototype.
Instead assign a callback handler to your XMLHttpRequest and do whatever you want there.
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4)
if (xmlhttp.status==200) {
// do something with xmlhttp.responseText
} else {
// do something appropriate with status
}
}
Update: Though I think it's usually not preferrable to have these kind of copy-pasta examples, I can show you where you should put this piece of code. Instead of doing this:
function searchADocument() { //wordToSearchFor
var txt = loadXMLDoc();
if (txt.test('hello'))
alert('responseText contains "hello"');
else
document.getElementById("myDiv").innerHTML = "helloaj";
}
where you test the return value of loadXMLDoc (which, as already stated, returns immediately, so before the request is completed), you should put your code inside the callback handler, that you assign by setting onreadystatechange:
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var txt=xmlhttp.responseText; /* manipulate the DOM here */
if (txt.test('hello'))
alert('responseText contains "hello"');
else
document.getElementById("myDiv").innerHTML = "helloaj";
}
}

Categories

Resources