Easy modification to AJAX script to assign the returned output in a value instead of printing it in textbox
I am using the following script
<script>
function getXMLHTTP() {
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCurrencyCode(strURL)
{
var req = getXMLHTTP();
if (req)
{
//function to be called when state is changed
req.onreadystatechange = function()
{
//when state is completed i.e 4
if (req.readyState == 4)
{
// only if http status is "OK"
if (req.status == 200)
{
document.getElementById('cur_code').value=req.responseText;
}
else
{
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
to get the currency of some countries using AJAX, based开发者_高级运维 on dropdown value.
<select id="termid" class="selectfield" onChange="getCurrencyCode('find_ccode.php?country='+this.value)">
find_ccode.php is
$country=$_REQUEST['country'];
switch($country)
{
case "1" :
echo "USD";
break;
case "2" :
echo "GBP";
break;
case "3" :
echo "NPR";
break;
}
and my textbox is
<input type="text" name="cur_code" id="cur_code">
What I want is to assign the country's currency code into a PHP variable and echo it on every change. How to do this?
Thank you
There are a few ways you can do this:
Store it in a PHP session. You would do this find_ccode.php
Store it in a cookie, using PHP. Again, this would be in find_ccode.php
Store it in a cookie using JavaScript. You would do this in your ajax response handler.
If you stick with option 1 or 2, you'd just have something like this pseudocode:
$currCode = $.cookie('currcode');
Once the page is loaded, you cant run anymore php code on that page, which is part of the reason for using ajax, it lets you run php code from another file and do something with it (with javascript) on the existing page.
If you just dont like having to put the result it in a text box, you can put it in any other html tag that has an id, like a table cell, a div, a span etc.
You would just says innerHTML= instead of value=
document.getElementById('thisdiv').innerHTML=req.responseText;
if you are usign jQuery why bother with custom HTTPRequest ?
<select id="termid" class="selectfield" onChange="getCurrencyCode(this.value)"><option>...</option></select>
<input type="text" name="cur_code" id="cur_code">
<script type="text/javascript">
function getCurrencyCode(setCountry){
$.get('find_ccode.php', { country: setCountry }, function(data) {
$('#cur_code').val(data);
});
}
</script>
Later edit:
then find_ccode.php
could be:
session_start();
$country=$_REQUEST['country'];
switch($country)
{
case "1" :
echo "USD";
$_SESSION['currency'] = 'USD';
break;
case "2" :
echo "GBP";
$_SESSION['currency'] = 'GBP';
break;
case "3" :
echo "NPR";
$_SESSION['currency'] = 'NPR';
break;
}
精彩评论