am trying to generate report through dynamically generated form. Through XMLHttpRequest the form loads well but the validation against the form fields wont work. I have tried eval() it works only during load time ( like eval(alert("hi")) but not on dom objects , think some scope problem. The form fields are dynamically generated and so its validation based on selection and availability role in database.
The code of two files is attached below
<script>
function showUser(str)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var s= xmlhttp.responseText;
parseScript1(s);
parseScript(s);
}
}
xmlhttp.open("GET","test2.php",true);
xmlhttp.send();
}
function parseScript1(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
var k = "<script> "+ scripts +"<\/script>";
document.getElementById("txtHint1").innerHTML=k ;
// Return the cleaned source
return source;
}
function parseScript(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
document.getElementById("txtHint").innerHTML=source;
// Return the cleaned source
return source;
}
function valid()
{
eval(validate());
}
</script>
<div id="txtHint1"><b>javascript will appear here</b></div>
<form>
<div id="nons1" >
<select id="nope1" name="users" onchange="showUser(this)">
<option value="">Select a option:</option>
<option value="1">not working here</option>
</select>
</div>
</form>
<div id="txtHint"><b>Select the value .</b></div>
test2.php
echo "<p>This form works fine singly not with xmlhttprequest";
echo'<form name="frm" method="post" action="test2.php" onsubmit="return(eval(validate()));">';
echo '<input value="" name="kfrm19" type="text">';
echo '<input name="save" value="submit" type="submit"></form>';
echo '<script>
function validate(){
if( document.frm.kfrm19.value.trim()=="")
{
alert( "If you can see this message .its working..." );
document.frm.kfrm19.focus() ;
return false;
}
}
</script>';
?>
try this:
function validate(){
if(document.frm.kfrm19.value.length == 0)
{
alert("If you can see this message .its working...");
document.frm.kfrm19.focus();
return false;
}
}
Related
Right now I have a program that uses AJAX to read in a XML file and a json file. The problem is once the user clicks one of these buttons the text stays on the page forever. I was wondering if there was a way to make a button that would delete the text and sort of start over. I tried making a reset button but it didn't work. Here is the code that I have. Thanks for the help in advance.
<!DOCTYPE html>
<html>
<head>
<title>Assignment8</title>
<script src="ajax.js"></script>
<script>
function getXML() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get XML Document
var xmlDoc = xmlHttp.responseXML;
// Variable for our output
var output = '';
// Build output by parsing XML
dinos = xmlDoc.getElementsByTagName('title');
for (i = 0; i < dinos.length; i++) {
output += dinos[i].childNodes[0].nodeValue + "<br>";
}
// Get div object
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = output;
}
}
xmlHttp.open("GET", "dino.xml", true);
xmlHttp.overrideMimeType("text/xml")
xmlHttp.send();
}
function getJSON() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get Response Text
var response = xmlHttp.responseText;
// Prints the JSON string
console.dir(response);
// Get div object
var divObj = document.getElementById('dinoJSON');
// We used JSON.parse to turn the JSON string into an object
var responseObject = JSON.parse(response);
// This is our object
console.dir(responseObject)
// We can use that object like so:
for (i in responseObject) {
divObj.innerHTML += "<p>" + responseObject[i].name
+ " lived during the " + responseObject[i].pet
+ " period.</p>";
}
}
}
xmlHttp.open("GET", "json.php", true);
xmlHttp.send();
}
</script>
</head>
<body>
<form>
<h3>Dinosaur Web Services</h3>
<div id="home"></div>
<button type="reset" value="Reset">Home</button>
<div id="dinoJSON"></div>
<button type="button" onclick="getJSON();">JSON Dinos</button>
<div id="dinoXML"></div>
<button type="button" onclick="getXML();">XML Dinos</button>
</form>
</body>
</html>
You can empty the div before inserting the new value in it. Like below i have done for one of the div, and with same you can do to other.
Add this to your script
<script>
function reset() {
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = ""; // empty the div here
divObj.innerHTML = output;
}
</script>
and add this button in your HTML
RESET
Here you go:
<!DOCTYPE html>
<html>
<head>
<title>Assignment8</title>
<script src="ajax.js"></script>
<script>
function getXML() {
document.getElementById('msg').style.display = "none";
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get XML Document
var xmlDoc = xmlHttp.responseXML;
// Variable for our output
var output = '';
// Build output by parsing XML
dinos = xmlDoc.getElementsByTagName('title');
for (i = 0; i < dinos.length; i++) {
output += dinos[i].childNodes[0].nodeValue + "<br>";
}
// Get div object
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = output;
}
}
xmlHttp.open("GET", "dino.xml", true);
xmlHttp.overrideMimeType("text/xml");
xmlHttp.send();
}
function getJSON() {
document.getElementById('msg').style.display = "none";
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get Response Text
var response = xmlHttp.responseText;
// Prints the JSON string
console.dir(response);
// Get div object
var divObj = document.getElementById('dinoJSON');
// We used JSON.parse to turn the JSON string into an object
var responseObject = JSON.parse(response);
// This is our object
console.dir(responseObject)
// We can use that object like so:
for (i in responseObject) {
divObj.innerHTML += "<p>"+responseObject[i].name + " lived during the " + responseObject[i].pet + " period.</p>";
}
}
}
xmlHttp.open("GET", "json.php", true);
xmlHttp.send();
}
function resetDivs(){
document.getElementById('msg').style.display = "block";
document.getElementById('dinoJSON').innerHTML = "";
document.getElementById('dinoXML').innerHTML = "";
}
</script>
</head>
<body>
<form>
<h3> Dinosaur Web Services </h3>
<div id="home"></div>
<div id="msg">Select a button</div>
<button type="reset" value="Reset" onclick="resetDivs();"> Home</button>
<div id="dinoJSON"></div>
<button type="button" onclick="getJSON();"> JSON Dinos</button>
<div id="dinoXML"></div>
<button type="button" onclick="getXML();"> XML Dinos</button>
</form>
</body>
</html>
I have a page with 2 select boxes, one of which is loaded by an AJAX call. I then want to validate the elements with jquery before I enable the submit button. The jquery works fine when I change the static select (strDirectorate) but not when I change the one loaded by AJAX (new_cc).
Is it because jquery is getting the value of new_cc as it was when the page was loaded?
<div class="selectfield">
<select id="strDirectorate" name="strDirectorate" class="mainform_select" onChange="getNewCostCentre(this.value)">
<option value="" selected="selected"></option>
<?php do { ?>
<option value="<?php echo $row_rsLocality['strLocalityShort']?>" <?php if($row_rsLocality['strLocalityShort'] == $strDirectorate){ echo $selected; } ?>><?php echo $row_rsLocality['strLocalityLong']?></option>
<?php
} while ($row_rsLocality = mysql_fetch_assoc($rsLocality));
$rows = mysql_num_rows($rsLocality);
if($rows > 0) {
mysql_data_seek($rsLocality, 0);
$row_rsLocality = mysql_fetch_assoc($rsLocality);
}
?>
</select>
</div>
<div id="txtNewCostCentre" class="selectfield">
<select id="new_cc" name="new_cc" class="mainform_select" onChange="getNewPosition(this.value)">
<option value="" selected="selected"></option>
</select>
</div>
<div class="actions">
<input type="submit" id="submit_button" name="submit_button" class="styled_button" value="Submit" />
</div>
The function getNewCostCentre is
function getNewCostCentre(str)
{
if (str=="")
{
document.getElementById("txtNewCostCentre").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("txtNewCostCentre").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getNewCostCentre.php?q="+str,true);
xmlhttp.send();
}
The code for getNewCostCentre.php is
$sql="SELECT * FROM `tblcostcentreorganisation` WHERE `strOrganisation` LIKE '363 ".addslashes($dir)."%'";
$result = mysql_query($sql);
if(isset($_GET["q"])){
$display_string = '<select id="new_cc" name="new_cc" class="mainform_select" onChange="getNewPosition(this.value)" style="background-color:#F8E0E0">';
$display_string .= '<option value="" selected="selected" disabled="disabled"></option>';
}else{
$display_string = '<select id="new_cc" name="new_cc" class="mainform_select" onChange="getNewPosition(this.value)">';
}
while($row = mysql_fetch_array($result))
{
$cc = substr($row['strCostCentre'], 3, strlen($row['strCostCentre'])-3) . " " . substr($row['strOrganisation'], 3, strlen($row['strOrganisation'])-3);
$org_name = $row['strOrganisation'];
if ($org == $org_name){
$display_string .= '<option value="'.$org_name.'" selected="selected">'.$cc.'</option>';
}else{
$display_string .= '<option value="'.$org_name.'">'.$cc.'</option>';
}
}
$display_string .= '</select>';
echo $display_string;
And the jquery validation is:
$(document).ready(function() {
$('.selectfield select').change(function() {
var empty = false;
$('.selectfield select').each(function() {
$(this).css("background-color", "#FFFFFF");
if ($(this).val().length == 0) {
$(this).css("background-color", "#F8E0E0");
empty = true;
}
});
if (empty) {
$('.actions input').attr('disabled', 'disabled');
} else {
$('.actions input').removeAttr('disabled');
}
});
});
The onload code is as follows. I assume it's because I'm using .load within (after) .onload?
$(document).ready(function(){
window.onload = function(){
//Load directorate, cost centre and position
if ($('#hid_stage').val() == "Rejected") {
var str = $('#hid_criteria').val();
strencoded = encodeURIComponent(str);
$('#txtNewCostCentre').load("getNewCostCentre.php?cr="+strencoded);
$('#txtNewPosition').load("getNewPosition_ba.php?cr="+strencoded);
}
var empty = false;
$('.selectfield select').each(function() {
$(this).css("background-color", "#FFFFFF");
if ($(this).val().length == 0) {
$(this).css("background-color", "#F8E0E0");
empty = true;
}
});
if (empty) {
$('.actions input').attr('disabled', 'disabled');
} else {
$('.actions input').removeAttr('disabled');
}
}
});
You are binding your change handler for $('.selectfield select') when the page loads. This attaches the handler to all elements that match that selector.
If you then change this element, it won't have the handler attached.
Instead, you should use the live handler, to match all elements that exist now or are ever created in the future.
$('.selectfield select').live("change", function() {
...
});
UPDATE:
For you onload issue, it would be far easier not to repeat your code. If you need to fire off the validation after loading the content dynamically, then trigger the change event once the load has finished - like the following example:
$(document).ready(function(){
//Load directorate, cost centre and position
if ($('#hid_stage').val() == "Rejected") {
var str = $('#hid_criteria').val();
strencoded = encodeURIComponent(str);
$('#txtNewCostCentre').load("getNewCostCentre.php?cr="+strencoded, function() {
$('.selectfield select').trigger("change");
});
$('#txtNewPosition').load("getNewPosition_ba.php?cr="+strencoded);
}
});
An ajax update of the input shouldn't trigger the javascript change event so the handler you've specified in change won't get called.
From the javascript specification (http://www.w3.org/TR/html401/interact/scripts.html) :
onchange = script [CT] The onchange event occurs when a control loses
the input focus and its value has been modified since gaining focus.
This attribute applies to the following elements: INPUT, SELECT, and
TEXTAREA.
I'd suggest performing the validation logic in the same part of your javascript where you're handling the response from the ajax request. Right after the line
document.getElementById("txtNewCostCentre").innerHTML=xmlhttp.responseText;
add the call
validate();
Where validate is earlier defined as :
function validate() {
var empty = false;
$('.selectfield select').each(function() {
$(this).css("background-color", "#FFFFFF");
if ($(this).val().length == 0) {
$(this).css("background-color", "#F8E0E0");
empty = true;
}
});
if (empty) {
$('.actions input').attr('disabled', 'disabled');
} else {
$('.actions input').removeAttr('disabled');
}
}
So that your jquery validation becomes:
$(document).ready(function() {
$('.selectfield select').change(validate());
I have an HTML dropdown list which i'm populating from a database. My question is how can i retrieve the value of a selected item from this dropdown list using AJAX?
My javascript:
<script type = "text/javascript">
function getData(str){
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("div1").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "/display-product.php?q="+str, true);
xhr.send(null);
}
}
</script>
The dropdown list in display-product.php:
<div>
<?php
echo '<select title="Select one" name="selectcat" onChange="getData(this.options[this.selectedIndex].value)">';
while($row1 = $result->fetch_assoc()){
echo '<option value="' . $row1['id'] . '">' . $row1['category'] . '</option>';
}
echo '</select>';
?>
</div>
The div to display the selected item:
<div class="product_directory" id="div1"></div>
I'm not very conversant with AJAX. I tried to access the "str" variable passed to the getData function in my PHP script using "$string = $_GET['q']" but still didn't work. Thanks in advance for the help.
UPDATE: i was able the figure out the source of the problem: I have two functions that populate the select lists from the database. When a user selects an option from the first dropdown(with id="categoriesSelect"), the second one(id = "subcatsSelect") is automatically populated. Here is the code for both functions:
<script type="text/javascript">
<?php
echo "var categories = $jsonCats; \n";
echo "var subcats = $jsonSubCats; \n";
?>
function loadCategories(){
var select = document.getElementById("categoriesSelect");
select.onchange = updateSubCats;
for(var i = 0; i < categories.length; i++){
select.options[i] = new Option(categories[i].val,categories[i].id);
}
}
function updateSubCats(){
var catSelect = this;
var catid = this.value;
var subcatSelect = document.getElementById("subcatsSelect");
subcatSelect.options.length = 0; //delete all options if any present
for(var i = 0; i < subcats[catid].length; i++){
subcatSelect.options[i] = new Option(subcats[catid][i].val,subcats[catid][i].id);
}
}
</script>
The code works fine if i manually put in the select list . But using these two functions to pull from the database, nothing is displayed. I call the loadCategories() function like this
<body onload = "loadCategories()">.
The other select box is very similar to this one.
I don't know the specific issue but i know it's coming either from loadCategories() or updateSubCats().
It seems your code is retrieving the value on the select. But it fails on your function.
I tried using that open function Here. But, in my side it didn't work using an slash (/). So, try to remove that and try it.
...
xhr.open("GET", "display-product.php?q="+str, true);
...
EDIT: full working code...
<script type = "text/javascript">
function getData(str){
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById("div1").innerHTML = xhr.responseText;
}
}
xhr.open("GET", "display-product.php?q="+str, true);
xhr.send(null);
}
}
</script>
<select title="Select one" name="selectcat" onChange="getData(this.options[this.selectedIndex].value)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="div1"></div>
... on display-product.php
echo $_GET['q'];
Try this for the edited part of your question.
And this other to make it work together.
Hope this helps.
You can use a this possible solution with JQuery:
Add the attribute "id" in option tag in php code and remove onChange function:
echo "<select id='mySelect' title='Select one' name='selectcat'>";
Add Jquery File JQuery 1.9.1 and add the javascript HTML tag
Put before close tag body:
$(document).ready( function() {
$('#mySelect').change(function(){
var $selectedOption = $(this).find('option:selected');
var selectedLabel = $selectedOption.text();
var selectedValue = $selectedOption.val();
alert(selectedValue + ' - ' + selectedLabel);
$('.product_directory').html(selectedValue + ' - ' + selectedLabel);
$.ajax({
type:"POST",
url:"display-product.php",
data:selectedValue OR selectedLabel,
success:function(response){
alert('Succes send');
}
})
return false;
});
});
Read in php:
echo $_POST['selectedValue'];
or
echo $_POST['selectedLabel'];
I'm trying to do an AJAX call to pull back data to popluate a drop down box based off the select of another drop down box. My code is working fine in FF 9.0.1 (used for firebug), but failing in IE 7 (which is my company standard). I've tried several ways to show the data, and I don't have the time right now to learn how to do this in jQuery. I'm sure this will be a head smacker, but what about IE is causing this issue?
Here are my code pages. First is the trimmed down version of the form calling the JavaScript.
<html>
<head>
<script language="JavaScript" src="/includes/Transaction_Update.js"></script>
<form id="submit" name="submit" action="Transaction_Process.php" method="post">
<table align='left'>
<tr>
<td class='reporttd'>Vendor</td>
<td>
<select name='selVendorCode' id='selVendorCode' onChange="getServiceCode()">
<option value='' selected='selected'></option>
<?php echo $vendorOptionList; ?>
</select>
</td>
</tr>
<tr>
<td class='reporttd'>Service Code</td>
<td class='reporttd'>
<select name='selServiceCode' id='selServiceCode'>
<option value='' selected='selected'></option>
</select>
</td>
</tr>
</table>
</div>
</div>
</form>
JavaScript page
//setup xmlHttp request for Ajax call
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlhttp;
try{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
var xmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.5.0",
"MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP",
"Microsoft.XMLHTTP");
for (var i=0; i<xmlHttpVersions.length && !xmlHttp; i++){
try{
xmlHttp = new Activexobject(xmlHttpVersions[i]);
}
catch(e) {}
}
}
if (!xmlHttp){
alert("Error creating the XMLHttpRequest object.");
}
else{
return xmlHttp;
}
}
//Call page to get all service codes for a vendor.
function getServiceCode(){
if (xmlHttp){
try{
var vCode = document.getElementById("selVendorCode").value;
var parms = "vCode=" + vCode;
//Call Transaction_AJAX.php to pass back an XML.
xmlHttp.open("GET", "Transaction_AJAX.php?" + parms, true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
catch(e){
alert("Can't connect to server:\n" + e.toString());
}
}
}
//Checks state of the HTTP request call, and proceed if status is ready
function handleRequestStateChange(){
if (xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
try{
handleServerResponse();
}
catch(e){
alert("Error reading the response: " + e.toString());
}
}
else{
alert("There was a problem retrieving the data:\n" + xmlHttp.StatusText);
}
}
}
//Handles response from the server
function handleServerResponse(){
var xmlResponse = xmlHttp.responseXML;
if (!xmlResponse || !xmlResponse.documentElement){
throw("Invalid XML Structure:\n" + xmlHttp.responseText);
}
var rootNodeName = xmlResponse.documentElement.nodeName;
if(rootNodeName == "parsererror"){
throw("Invalid XML Structure:\n" + xmlHttp.responseText);
}
xmlRoot = xmlResponse.documentElement;
if(rootNodeName != "root" || !xmlRoot.firstChild){
throw("Invalid XML structure:\n" + xmlHttp.responseText);
}
//Get response and load it into drop down
responseText = xmlRoot;
var sel = document.getElementById("selServiceCode");
sel.options.length = 0;
var opt = document.createElement("option");
document.getElementById("selServiceCode").options.add(opt);
for(var i=0; i < responseText.childElementCount; i++){
var newOpt = new Option(responseText.childNodes[i].childNodes[1].textContent,responseText.childNodes[i].childNodes[0].textContent);
sel.options[sel.options.length] = newOpt;
}
}
The PHP page creating the XML file
<?php
header('content-type:text/xml; charset=utf-8');
include("../includes/DBConn.php");
$vCode = $_GET['vCode'];
///Setup cursers and proc command
$curs = OCI_New_Cursor($c);
$stmt = OCI_Parse($c,"begin schema.package.procedure(:var_code, :expected_cv); end;");
OCI_Bind_By_Name($stmt, ":var_code", $vCode);
OCI_Bind_By_Name($stmt,":expected_cv",&$curs,-1,OCI_B_CURSOR);
//execute statment and cursors
oci_execute($stmt);
oci_execute($curs);
//Create xml document
$dom = new DOMDocument('1.0', 'UTF-8');
$root = $dom->createElement('root');
$root = $dom->appendChild($root);
//loop through results of Proc
while (ocifetchinto($curs,&$vendor_cv )) {
//Add node for each row
$occ = $dom->createElement("cell");
$occ = $root->appendChild($occ);
//Id Value
$id = "value";
$child = $dom->createElement($id);
$child = $occ->appendChild($child);
//Here is the actual value
$id = $vendor_cv[1];
$value = $dom->createTextNode($id);
$value = $child->appendChild($value);
//Id text
$id = "text";
$child = $dom->createElement($id);
$child = $occ->appendChild($child);
//Here is the actual value
$id = $vendor_cv[1];
$value = $dom->createTextNode($id);
$value = $child->appendChild($value);
}
//Close xml tags and save.
$xmlString = $dom->saveXML();
//Echo XML back to Transaction_Update.js
echo $xmlString;
?>
Here is how you do it in jQuery
1) Include jQuery library in your head section of the page. (here i am refering it from the google cdn)
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
In your javascript
$("#stateDropDown").change(function(){
var stateId=$("#stateDropDown").val();
$.ajax({
url: 'getcities.php?stateid='+stateId,
success: function(data) {
$("cityDropDown").html(data);
}
});
});
Assuming you have a HTML select element with id "stateDropDown" for states and another one with id "cityDropDown" for cities.
The above code will do the follolwing
1) When the value of state dropdown changes, it executes the inside code.
2 ) Reade the selected item value and store it in a variable called stateId.
3) Using the jQuery ajax method , it makes a call to getcities.php page with a query string key called stateid
4) when we get a response from the ajax call, the control flow will be in the part called "success" handler. there we are receiving the response in a variable called data.
5) setting the received response (data) as the inner html of the city dropdown.
Assuming the getcities.php page will return some output like this
<option value='1'>Ann Arbor</option>
<option value='2'>Dexter</option>
<option value='3'>Novi</option>
jQuery will take care of your cross browser issues. Yes its is well tested and everybody is using it.
http://www.jquery.com
You can change your for loop in handleServerResponse to the following to fix this issue:
for(var i=0; i < responseText.childNodes.length; i++){
var node = responseText.childNodes[i];
var text = node.childNodes[1].text ? node.childNodes[1].text : node.childNodes[1].textContent;
var value = node.childNodes[0].text ? node.childNodes[0].text : node.childNodes[0].textContent;
var newOpt = new Option(text,value);
sel.options[sel.options.length] = newOpt;
}
I want to make a php ajax post.(post value without refresh the page) here is my code. It can return the value and show in <div id="msg"></div>, But I also want to use this value.
In #benhowdle89 's help, I made $name= "<div id='msg'></div>". but when I use echo $name, in the source code, I can see <div id='msg'></div>(html tag), this is not a pure value, so I tried to use strip_tags, but the value lost. it seems the left the ajax pointed div tag, the value also gone. Still waiting for help...
index.php
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript">
function saveUserInfo() {
var msg = document.getElementById("msg");
var f = document.user_info;
var userName = f.user_name.value;
var url = "value.php";
var postStr = "user_name="+ userName;
var ajax = false;
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
if (ajax.overrideMimeType) {
ajax.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
if (!ajax) {
window.alert("wrong");
return false;
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(postStr);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
// myPhpVariable is now a variable which you can use
alert( myPhpVariable );
}
}
}
</script>
</head>
<body>
<?php
echo $name="<div id='msg'></div>";
$name1=strip_tags($name);
$name2 = explode("|",$name1);
$namea=$name2[0];
$nameb=$name2[1];
?>
<form name="user_info" id="user_info" method="post">
<input name="user_name" type="hidden" value="abc|def" /><br />
<input type="button" value="abc|def" onClick="saveUserInfo()">
</form>
</body>
value.php
<?php
echo $_POST["user_name"];
?>
This is what I want. post value from index.php, then get the value by self without refresh the page. one botton with two values, I want explode them and finally get $namea and $nameb. I want use them in other php part.
You can put the ajax response into a javascript variable, then you can manipulate it from there:
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
alert( myPhpVariable );
Here is a working javascript example (full code):
function saveUserInfo() {
var msg = document.getElementById("msg");
var f = document.user_info;
var userName = f.user_name.value;
var url = "value.php";
var postStr = "user_name="+ userName;
var ajax = false;
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
if (ajax.overrideMimeType) {
ajax.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
if (!ajax) {
window.alert("wrong");
return false;
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(postStr);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
// myPhpVariable is now a variable which you can use
alert( myPhpVariable );
}
}
}
The PHP file would look like:
$postVar = $_POST["user_name"];
$postVarArr = explode('|', $postVar);
// will show abc
//echo $postVarArr['0'];
// will show def
echo $postVarArr['1'];
by including $name= "<div id='msg'></div>" and calling echo $name, you're just telling the program to store "" in the $name variable and then print what is stored in that variable. That's why you're getting the unwanted output.
not sure if you're having problems posting the value or showing it in the value, but you need to echo the variable where the userName is stored, may need to send that from the ajax to the php and set it to $name.