Ajax call returnign [object HTMLInputElement] - php

i am learning ajax and doing some practice. I am facing a problem. Here is my code.
<input class="category" id="design" type="button" value="Design" onclick="loadXMLDoc(design)" />
Ajax:
function loadXMLDoc(name)
{
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)
{
var array = xmlhttp.responseText;
alert(array);
}
}
xmlhttp.open("GET","server.php?cat="+name,true);
xmlhttp.send();
}
server.php:
if(isset($_GET['cat']))
{
$cat = $_GET['cat'];
echo $cat;
}
Now, when i click on the button, the alter gives me [object HTMLInputElement] when i am expecting to get "design". What is wrong in it?

What is wrong in it?
You have to pass a string to the function:
onclick="loadXMLDoc('design')"
Currently you are passing the variable design. Since you have an element with ID "design" this variable happens to refer to that element. Then when you are trying to send the element to the server it is converted to a string. The default string representation of an input DOM element in JavaScript is "[object HTMLInputElement]".

Try this :
onclick="loadXMLDoc(this.value)"

Related

Data is not stored into $_POST array from ajax request

So I've already done an AJAX request using GET, and so now i wanted to try my luck using POST instead. But for some reason, when i try to send data, I get a crazy weird message in the console - NS_ERROR_XPC_JSOBJECT_HAS_NO_FUNCTION_NAMED: 'JavaScript component does not have a method named: "available"' when calling method: [nsIInputStream::available]
I literally have no idea what this means, and I know the data isnt going through because all im doing in the load.php file that I request is echo the variable its supposed to store. So its something in the javascript.
Here is my HTML for the first page that makes the request.
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<input id="input">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
And my 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)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
var data = "id="+document.getElementById("input").value;
xmlhttp.open("POST","load.php",true);
xmlhttp.send(data);
}
And finally, the code for load.php:
$param = $_POST['id'];
if($param){
echo "Variable was stored.";
} else{
echo "Not working";
}
And everytime i run this, i get "not working" in the browser. So the php code is at least attempting to store the variable, but its not. Thankyou!
Your forgot to add xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'). With this line we are basically saying that the data send is in the format of a form submission
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;
}
}
var data = "id="+document.getElementById("input").value;
xmlhttp.open("POST","load.php",true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(data);
}

calling two js functions and don't print message

I have problem in ajax and it doesn't print the message I want. Let's explain.
In php code i have an input tag:
<input type="submit" id="login_button_add" name="submit" value="Add"
onclick="add_building(); showbuildings( );" />
Those two js functions are:
function add_building(){
var str1=document.getElementById("building_name").value;
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("txtHint10").innerHTML=xmlhttp.responseText;}
}
xmlhttp.open("GET","add_building.php?q="+str1,true);
xmlhttp.send();
}
In add_building.php I add a row in database and print messages. The query works fine, but it doesn't print the message in my page with id that I have in my html code. I think that the problem is that I call second js function. Because when I call add_building() alone it works perfect(prints messages).
The php code of add_building.php is:
$q=$_GET["q"];
if ($q!==''){
$link= mysqli_connect(...);
mysqli_set_charset($link, "utf8");
$sql="SELECT * FROM buildings WHERE name='$q'";
$result = mysqli_query($link,$sql);
if (!mysqli_num_rows($result)){
mysqli_set_charset($link, "utf8");
$sql="INSERT INTO buildings VALUES ('','$q','')";
$result =mysqli_query($link,$sql);
echo "The building added successfully.";
}
else {echo 'Building name exists. Try a different.';}
# db_close($link);
}
else{echo 'Please insert a name.';}
The other js function is:
function showbuildings(str)
{
if (str=="")
{
document.getElementById("show_buildings_js").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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("show_buildings_js").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","showbds.php?q=",true);
xmlhttp.send();
}
In this function I print the table in my page. That works fine.
The problem is that the messages from add_building.php don't print in id='txtHint10' ,
despite all the others in add_building.php work. I think that the problem is that I call second js function and I have two xmlhttp.responseText. Because when I call js function add_building() alone it works perfect and prints the messages.
The problem is that you are overwriting you xmlhttp variable with the second javascript function. The result is that only the callback from the second function is executed.
For both functions to work independently of each other, you would need to use different variable names or declare them locally in each of your functions with var xmlhttp; (the cleaner solution).
Note that the scope of a variable in javascript is global unless you declare it using var in your function.

Tags shown in xmlhttp.responseText

How come when I populate my textbox with what's in xmlhttp.responseText tags are shown? It shows
<!DOCTYPE html><html><body></body></html>
as well as what I want it to show. Is there a way to make it so that the tags aren't shown? The Javascript and AJAX code is as follows:
function loadDoc()
{
var xmlhttp;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("textbox").value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","loadTextBox.php?id=4",true);
xmlhttp.send();
}
ADDED-Code for loadTextBox.php is as follows:
<?php
---placeholder for correct db login info---
$result = $mysql->query(---placeholder for correct SQL query---);
while ($row = $result->fetch_object())
{
$queryResult = $row->column_1;
}
$textboxValue = $queryResult;
echo $textboxValue;
?>
Well, I was unable to reproduce your problem, so I had to improvise slightly to get the same responseText as you. Anyway, this is what I came up with, please let me know if it doesn't work:
var doc = window.document.createElement("doc");
doc.innerHTML = xmlhttp.responseText;
document.getElementById("textbox").value=doc.innerHTML;
Replace your current instance of:
document.getElementById("textbox").value=xmlhttp.responseText;
With that.

Javascript XMLHttpRequest result will not store in a variable for other use

I'm submitting a form but need my form to run some checks first so i'm calling in some javascript which needs to run an XMLHttpRequest to see if something is set on another PHP script. I can get the value back but only output the message within the area where i am getting the response, any attempt of putting this into a variable and using elsewhere doesn't work, here's my script:
function validateform() {
var complete = "Please fill in the following fields:";
var temp;
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)
{
temp=xmlhttp.responseText;
alert(temp);
}
}
xmlhttp.open("GET","hrp/recaptcha/verify.php",true);
xmlhttp.send();
alert(temp);
The first "alert(temp") gets outputted but then the one after at the end of the code always says undefined so I cant use it outside.
Any ideas?
Thanks :D
It appears that you don't want an asynchronous call, in which case you'll want to do:
xmlhttp.open("GET","hrp/recaptcha/verify.php",false);
You can also remove the block:
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{

AJAX & PHP -Retrieving more than one value

I'll get to the point, assume my PHP script returns an array with two values, how would I address them within javascript?
<script type="text/javascript">
function ValidateCard(cardno)
{
if (cardno.length==0)
{
document.getElementById("txtprice").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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtprice").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","coding/validation/validatecard.php?cardno="+cardno,true);
xmlhttp.send();
}
</script>
As you can see whatever is returned is send to display within a div tag, how would I differentiate between data?
Thanks
You could use json to serialize it so that javascript can read it.
So, in php json_encode($arr);
http://www.php.net/manual/en/function.json-encode.php
Then in javascript.
you should be able to do something like jsarr[key] to get the values
<?php
$result = array('success'=>1, 'messgae'=>"the message you want to show");
echo json_encode($result);
?>
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
result = xmlhttp.responseText.evalJSON(true);
//you can use result as array to get the information you want to check
if (result['success']) {
document.getElementById("successs").innerHTML=result['message'];
}
}
}

Categories