AJAX, refresh INPUT field - php

I am using AJAX for the first time with PHP and mySQL.
I have been following some examples and tutorials on how to use AJAX with INPUT fields.
I have a form with 2 input fields.
1st input field: User type in 4 digits
2nd input field: The 4 digits are looked up in the mySQL db and outputted on this field.
Most examples are based on output in div's and span's while i am interested in output on my 2nd INPUT field.
How is this possible?
My js-file:
function showUser(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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","include/postalcode.php?q="+str,true);
xmlhttp.send();
}

You have written :
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
Instead of innetHTML use value:
document.getElementById("txtHint").value=xmlhttp.responseText;

Most examples are based on output in div's and span's while i am interested in output on my 2nd INPUT field.
You should be able to follow the examples with two changes:
use .value instead of .innerHTML
for input fields
look up your second input field by
its ID
document.getElementById("secondFieldId").value=xmlhttp.responseText;

Related

Ajax function with PHP MySQL not calling the php page

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

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)
{

Javascript document.getElementById concatenating

I'm struggling with some JavaScript code that I have used countless times across my pages just tweaking as I go. The problem I have is concatenating part of the form elements id and a string variable defined elsewhere in the page to make my ajax call dynamic.
Im am using the following code which works perfect when the element is hard coded as below(only works for the item coded and not dynamically so no good after testing)
<script type="text/javascript">
function edttodo(str)
{
if (str=="")
{
document.getElementById("todoitemwr").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("todoitemwr(2)").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","todo/edt_todo.php?q="+str,true);
xmlhttp.send();
}
</script>
So you understand what my need is for the dynamic aspect of the code I have a mysql query undertaken which is as follows:
<?php
//Get Current To-Do Items
//select database
mysql_select_db("jbsrint", $con);
//query users_dash_user
$result1 = mysql_query("SELECT * FROM todo WHERE todo_user_id_fk= '".$_SESSION['user_id']."' AND todo_item_status='1'");
while($row1 = mysql_fetch_array($result1))
{
echo"<div class=\"todoitemwr\" name=\"todoitemwr(". $row1['todo_id'] .")\" ID=\"todoitemwr(". $row1['todo_id'] .")\"><span class=\"todoitem\">" . $row1['todo_item'] . "</span><span class=\"rmv\" onclick=\"rmvtodo(". $row1['todo_id'] .")\" onmouseover=\"className='rmvon';\" onmouseout=\"className='rmv';\">X</span><img src=\"images/edit.png\" class=\"edt\" onclick=\"edttodo(". $row1['todo_id'] .")\"></img></div>";
}
?>
</div>
As you can see the div id is dynamically named based on the id of the information that has been retrieved. The use of my ajax code above is to be able to edit the text that is retrieved in-situ and once corrected/altered it can then be re-submitted and update that record.
I'm sure that it is simply a case of understanding how JavaScript requires me to combine the text and str value in the document.getElementById("todoitemwr(2)") part.
As usual any help is much appreciated.
Alan.
Instead of using id="todoitemwr(2)" write id="todoitemwr_2".
That's because braces are not allowed in ID attributes.
The code would become:
document.getElementById('todoitemwr(' + str + ')')

ajax button loading state

I made this little script with tutorials on internet. php function calls this javascript as many times as there are buttons (foreach), right now i have three. $value is the div name of specific button (buttons are stored in php array).
Everything works fine... except when i click through all the buttons fast, the loading gif remains without javascript changing the button status. The response, witch it gets from another php is the new button state and session variable change. Session variable gets changed but the div dosent.
So, heres where i need help, how can i make it so, when i click buttons fast, the div gets changed too?
my code
function load_javascripts() {
foreach ($GLOBALS["VARIABLES"]["button_list"] as $key => $value) {
$scripts .= "
function run_alias_button_".$value."(str)
{
document.getElementById('aliasbutton_".$value."').innerHTML='<img src=ajax_loader.gif>';
if (str=='')
{
document.getElementById('aliasbutton_".$value."').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('aliasbutton_".$value."').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open('GET','?leht=alias_logimine&alias=".$value."',true);
xmlhttp.send();
}
";
}
return $scripts;
}
Put var xmlhttp; at the very beginning of the function, making the variable explicitly local. Sometimes without that statement browsers may try to find a global variable with this name and readystate monitoring is shifted from one request to another.
Just a tip. Use the open function always before the onreadystatechange event. The way you using may works on firefox but IE doens't understand. LIke this:
xmlhttp.open('GET','?leht=alias_logimine&alias=".$value."',true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('aliasbutton_".$value."').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.send();

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