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.
Related
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)"
I select an option from a drop down menu(id="field"), and on the basis of this value I wish to generate another drop down menu, I use ajax to retrieve the value of field1 input. the function is:
function showbranches(degree)
{
var XMLHttp=false;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
XMLHttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
XMLHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
XMLHttp.open("POST","SORS/sendegree.php?degree="+degree,true);
XMLHttp.onreadystatechange = function(){
if (XMLHttp.readyState==4 && XMLHttp.status == 200)
{
document.getElementById('br').innerHTML=XMLHttp.responseText;
}
}
XMLHttp.send(null);
}
code in sendegree.php file is simply
<?php echo $_REQUEST['degree'];
?>
Now I try to receive the string returned by ajax code into a php variable using statement:
<?php
$state="<span id=\"br\"></span>";
echo $state;
?>
Now the problem is, the first statement for echo works fine, but i am not able to use $state as a variable in sql query as below
$get_cty=mysql_query("SELECT * FROM abc WHERE city='$state'")or die(mysql_error());
You need to concatenate the variable
Try this
$get_cty=mysql_query("SELECT * FROM abc WHERE city='".$state."'") or die(mysql_error());
How I learned it in college was whenever you needed a variable to a value in the query to you added '".."' after the equals sign then put the variable in the middle.
Hope that helps.
I have a page that lists customers from a SQL database. It lists the credits they have left and I have a button that I can click to remove one credit. The way it is done is when you click on the button it calls a Ajax function that runs a php page that remopves one credit and echoes the credit after that.
The php page works fine when I input the string in the URL manually but smy Ajax function must be wrong.
here is the listing with the form:
while ($data = mysql_fetch_object($result)) {
print "<TR><TD>".$data->pass_name."</TD><TD><span id='credit'>".$data->credit_left."</span></TD><TD><form><input type='submit' value='- 1' onsubmit='removeOneCredit(pass_id=".$data->pass_id."&credit_left=".$data->credit_left.")'></form></TD></TR>\n";
}
and here is my function:
<script>
function removeOneCredit(str)
{
if (str=="")
{
document.getElementById("credit").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("credit").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","removeonecredit.php?"+str,true);
xmlhttp.send();
}
</script>
I'm not sure why the function is not working. I know for a fact that removeonecredit.php is doing its job.
turns out the = in the function arguments is a problem, I posted a question on how to escape it here: Javascript escape a equal sign PHP
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)
{
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'];
}
}
}