dependent drop downlist generation - javascript

I'm trying to make a dependent dropdown list using ajax and php but not able to get the desired result
here is my code of ajax
<html>
<head>
<title>findperson</title>
<script type="text/javascript">
function configureDropDownLists(ddl1,ddl2) {
var x=ddl1.value;
var service;
var url='service.php?data='+x;
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new
ActiveXObject("Microsoft.XMLHTTP");
}
if(XMLHttpRequestObject) {
XMLHttpRequestObject.open("GET",url);
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
service=XMLHttpRequestObject.responseText;
for (var i=0;i<service.length;i++ ){
var opt = service[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
ddl2.appendChild(el);
}
}
}
XMLHttpRequestObject.send(null);
}
}
</script>
</head>
<body>
<form method="post" action="problem.php">
<select name="city" id="city" onchange="configureDropDownLists(this,document.getElementById('service'))">
<option selected="selected" value="">City</option>
<option value="jhansi">Jhansi</option>
<option value="lucknow">Lucknow</option>
</select>
<select id="service">
<option selected="selected" value="">Service</option>
</select>
<input type="submit" name="proceed" value="Next"/>
</form>
</body>
</html>
this is my php file
<?php
include_once('db.php');
$db=new db();
$sql=$db->database_initialise();
$city=$_GET['data'];
$query="select service_name from service_offered where city='$city'";
if($result=$sql->query($query)){
if($result->num_rows >0){
$i=0;
while($row=$result->fetch_array()){
$service[$i]=$row[0];
$i++;
}
}
}
var_dump($service);
?>
problem is that in second dropdown list no changes occur on selecting a city

Replace var_dump($service)
echo json_encode($service);

A couple of problems here:
your PHP is not sending the correct response. What you want to do is have PHP send a JSON response.
once PHP sends this JSON response, you then need to parse this into an object
Once your response is in object format, you can then iterate through the results.
Try this:
PHP (this is an example of what will be returned from your DB):
$response = array(
array(
"id" => "1",
"name" => "something"
)
);
header('Content-Type: application/json');
echo json_encode($response);
JS:
function configureDropDownLists(ddl1, ddl2) {
var url = 'submit.php?data=' + ddl1.value;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json = xmlhttp.responseText;
var obj = JSON.parse(json);
for (var i = 0; i < obj.length; i++) {
var opt = obj[i];
var el = document.createElement("option");
el.textContent = opt.name;
el.value = opt.id;
ddl2.appendChild(el);
}
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
}

Your issue is that you are returning the $service array from your PHP and accessing it in your AJAX as a string. service=XMLHttpRequestObject.responseText; returns a string object. In your for loop it looks like you are trying to index through an array. However, you can't index through a string like that and get what you are expecting.
The best thing is to use echo json_encode($service); like Leo suggested, then in your AJAX transform the responseText by using JSON.parse
var json = JSON.parse(XMLHttpRequestObject.responseText);
Then in the for loop
var opt = json[/*i or column name*/];
or
var opt = json.service_name[i];
Note: To return a JSON string in PHP, you have to set the header: header("Content-type: application/json");
Hope that helps!

Related

How do we send an array that contains text from an xml http request to PHP using mysqli?

This is the code that is preparing my array, it will be sent as a parameter to the function that handles my HTTP request.
for (var i in the_texts) {
if (the_texts[i]._status == "new") {
var instance_texts_object = {};
instance_texts_object._id = parseInt(the_texts[i]._id);
instance_texts_object._data = encodeURIComponent(the_texts[i]._data);
instance_texts_array.push(instance_texts_object);
}
}
the_texts.update_backend_text_instances_ajax(instance_texts_array);
An example of my instance_texts_array record looks like: 4: {_id: 3193, _data: "Click%20Me!"}
My Ajax function looks like this:
update_backend_text_instances_ajax: function(texts_array_) {
texts_array_ = JSON.stringify(texts_array_);
var file_address = "includes/update_backend_texts_intances.php";
var xhttp_request = new XMLHttpRequest();
xhttp_request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = this.responseText;
document.getElementById('test_xml').innerHTML += "<br>" + "texts" + response;
};
};
xhttp_request.open("POST", file_address + "?text_array=" + texts_array_, false);
xhttp_request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhttp_request.send();
}
I am using a POST method.
My PHP script looks like this:
<?php
include_once 'database.php';
$text_array = $_REQUEST["text_array"];
$text_array_entry = json_decode($text_array, true);
foreach($text_array_entry as $row) {
$statement = mysqli_query($connect,"INSERT INTO the_texts (id, user_id, data) VALUES('".$row['_id']."', 600, '".$row['_data']."');");
};
echo print_r($text_array_entry);
?>
I think my problem is that my PHP script is not receiving my text_array variable. Disclaimer: $connect comes from include_once 'database.php'

Self-made calculator doesnt work

I wrote small calculator script with JS and PHP. As i saw all is correct, but in output server show me blank ('0') value. I cant find a solution for 2 hours.
JS script, that open connection with POST method with action 'calc.php':
<script type="text/javascript">
function getXmlHttp() {
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
function summa() {
var how0 = document.getElementById("how0").value;
var xmlhttp = getXmlHttp();
xmlhttp.open('POST', 'calc.php', true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("how0=" + encodeURIComponent(how0));
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("how").value = xmlhttp.responseText; //
}
}
};
}
</script>
Form for calculating:
<input type="number" required name="how0" id="how0" min="100" max="999999" placeholder="100">
<input type="number" required readonly name="how" id="how" min="200" max="999999" placeholder="200">
<input type="button" value="Calcul" onclick="summa()" />
Calc.php for checking:
<?php
$a = is_numeric($_POST["how0"]);
$a = floor($a);
if ($a>1) {
$a = $a * 2;
}
if ($a>10000) {
$a = $a * 3;
}
echo $a;
?>
This line:
$a = is_numeric($_POST["how0"]);
Assigns the return value of is_numeric to $a — e.g., true or false. Then you use $a as though it contained the value posted to the script, but it doesn't.
You probably meant to use intval or floatval or similar:
$a = intval($_POST["how0"]);
Note that unless you need to support really old browsers, there's no need for your getXmlHttp function. All vaguely-modern browsers support new XMLHttpRequest.

Changing URL after selecting value from dropdown menu

I have a HTML form with two dropdown menus. First dropdown is prepopulated from database with PHP, second one is linked with first one and uses AJAX to update values according to the selection from first one.
How can I make the URL to change after selecting something from the dropdown menu? E.g. after selecting something from first dropdown, URL would be something like http://myurl.com/form.php/option1 and after second choice http://myurl.com/form.php/option1+option2.
My code:
Scripts:
<script>
function kuvaRingkond(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
else {
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","getringkond.php?q="+str,true);
xmlhttp.send();
}
}
</script>
function AjaxFunction()
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Teie brauser ei toeta Ajaxit!");
return false;
}
}
}
function stateck()
{
if(httpxml.readyState==4)
{
var myarray = JSON.parse(httpxml.responseText);
// Remove the options from 2nd dropdown list
for(j=document.form.kandidaat.options.length-1;j>=0;j--)
{
document.form.kandidaat.remove(j);
}
var optn = document.createElement("OPTION");
optn.text = 'Vali kandidaat';
optn.value = '0';
document.form.kandidaat.options.add(optn);
for (i=0;i<myarray.data.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myarray.data[i].Eesnimi + ' ' + myarray.data[i].Perekonnanimi;
optn.value = myarray.data[i].KandidaadiID;
document.form .kandidaat.options.add(optn);
}
}
}
// end of function stateck
var url="dd.php";
var erakond_id=document.getElementById('s1').value;
url=url+"?erakond_id="+erakond_id;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
//alert(url);
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
Form:
<form role="form" name="form" method="POST" action="haaletamine_form.php">
<div class="form-group">
<label for="erakond">
Erakond:
</label>
<?php
require "connection_pdo.php";// connection to database
echo "<select class ='form-control' name=erakond id='s1' onchange=AjaxFunction();>";
echo "<option selecter='selected'>Vali erakond</option>";
$sql="select * from erakonnad "; // Query to collect data from table
foreach ($dbo->
query($sql) as $row) {
echo "<option value=$row[ErakonnaID]>$row[ErakonnaNimi]</option>";
}
echo "</select>";
?>
</div>
<div class="form-group">
<label for="kandidaat">
Kandidaat:
</label>
<select class="form-control" name=kandidaat id='s2' onchange="kuvaRingkond(this.value)">
<option selecter="selected">
Vali kandidaat
</option>
</select>
</div>
<div id="txtHint">
<b>
</b>
</div>
<button type="submit" class="btn btn-default">
Kinnita valik
</button>
</form>
Thanks!
This is how I would do it.
HTML
<select id="select-list">
<option>Option One</option>
<option>Option Two</option>
<option>Option Three</option>
</select>
jQuery
$(document).ready(function() {
$('#select-list').on('change', function() {
var nSelectOption = $('#select-list').find(':selected').text();
switch(nSelectOption) {
case "Option One":
window.location.href = 'http://google.com';
break;
case "Option Two":
window.location.href = 'http://google.com';
break;
case "Option Three":
window.location.href = 'http://google.com';
break;
}
});
});

Getting variable from php file called by ajax request

I have main file index.php. Where user perform login I load url.php in <div> inside index.php through ajax request.
Now on url.php, on button click event I submit the form and post data to data.php file. As url.php is loaded into index.php, button click event on url.php will call function in section of index.php.
I am getting two variable $x and $y as a result on data.php.
On index.php I have JS function where I want to use $x and $y. How can I retrieve?
index.php
<script type="text/javascript">
//------------------script 2 starts ---------
function showUser(form, e) {
//alert(myid);
e.preventDefault();
e.returnValue=false;
var xmlhttp;
var sent = form.elements['sent'].value;
//var sent2 = form.elements['sent2'].value;
//alert(sent2);
//var divElements = document.getElementById('d1').innerHTML;
var text1 = document.getElementById('previewUrl').innerText || document.getElementById('previewUrl').textContent;
var text2 = document.getElementById('previewTitle').innerText || document.getElementById('previewTitle').textContent;
var text3 = document.getElementById('previewDescription').innerText || document.getElementById('previewDescription').textContent;
//alert(text3);
console.log(sent);
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(e) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
sent = encodeURIComponent(sent);
text1 = encodeURIComponent(text1);
text2 = encodeURIComponent(text2);
text3 = encodeURIComponent(text3);
xmlhttp.send('sent=' + sent + '&text1=' + text1 + '&text2=' + text2 + '&text3=' + text3);
}
</script>
+
$.ajax({
url:'url.php'
,async: true
,type : 'POST'
,cache: false
,data : 'myid=' + myid
,dataType: 'html'
,success: function(data){
$('body').html(data);
FB.XFBML.parse();
}
}
);
url.php
<form action="data.php" method="POST" onsubmit="showUser(this, event)">
data.php
if (preg_match_all('/[^=]*=([^;#]*)/', shell_exec("/home/technoworld/Desktop/test/b '$test'"), $matches)){ //Values stored in ma.
echo "hi";
$x = (int) $matches[1][0]; //optionally cast to int
$y = (int) $matches[1][1];
this x and y I want to fetch in index.php.
I know this is not impossible. But complex to thing for me!
My preferred method of sending data back from the server side is responding with JSON response..
$data['x'] = $x;
$data['y'] = $y;
header('Content-Type: application/json');
echo json_encode($data);
That should give a response to your ajax callback, so you could use it like this:
$.post('data.php', { "myid": id }, function(data) {
console.log(data.x); //data.x = $x
console.log(data.y); //data.y = $y
});
I didn't test the code to see if it actually works, but it should give an idea of what to do. Let me know if it makes sense :)
If you want to retrieve only two value.
Simplest solution just like boiling a egg is:
just print both value in with separating value like ':'
echo $x.':'.$y;
and when you getting response. separate value with ':' and then you can use them..
or JSON response is also good practice for this.

xmlHttpRequest issues in a Google-like autosuggestion script

I am trying to build up an autosuggestion search field similar to Google Suggestion (or Autosuggestion?).
I am using pure javaScript/AJAX and 2 files: index.php and ajax-submit.php (is the file where I will actually query the database). But for moment I am simply echo a text for debugging.
There are a few issues:
Issue 1: The issue is the firebug outputs: xmlhttp is not defined as soon as I type something in the search input [solved, see below].
Issue2: I would like also to echo the content of the search input something like this:
echo $_GET['search_text'];
or
if(isset($_GET['search_text'])) {
echo $search_text = $_GET['search_text'];
}
but I get the following error: *Undefined index: search_text in ajax-submit.php*
So here is my function suggest call:
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
And here is my function suggest():
<script type="text/javascript">
//function does not needs params because is unique to the input search_text
function suggest() {
//browser object check
if(window.xmlHttpRequest) {
xmlhttp = new xmlHttpRequest();
}
else if (window.ActiveXObject) {
//console.log("error");
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
//when the onreadystatechange event occurs
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementByID('results').innerHTML = xmlhttp.responseText;
}
}//end onready
xmlhttp.open('GET', 'ajax-submit.php', true);
xmlhttp.send();
}//end suggest
</script>
and here is my php ajax-submit file:
<?php
echo 'Something';
?>
Can someone help me debug? It might be a scope issue but I have no clue.
The second question would be how would you normally debug an Ajax request in Firebug?
Thanks
Actually, it is
XMLHttpRequest()
not
xmlHttpRequest()
To have a true cross-browser compliant XHR object creation, go with this:
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
var xhr = ( function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
Use:
new XMLHttpRequest
not
new xmlHttpRequest
I wrote a better implementation: cross-browser/more readable code, function splits. Below is the code. Unfortunately tough reads php echo text it won't read the variable search_text, I don't know why:
<script type="text/javascript">
/*note xmlHttp needs to be a global variable. Because it is not it requires that function handleStateChange to pass the xmlHttp
handleStateChange is written in such a way that is expects xmlHttp to be a global variable.*/
function startRequest(getURL){
var xmlHttp = false;
xmlHttp = createXMLHttpRequest();
//xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.onreadystatechange=function(){handleStateChange(xmlHttp);}
xmlHttp.open("GET", getURL ,true);
xmlHttp.send();
}
function createXMLHttpRequest() {
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
//req is assiqning to xmlhttp through a self invoking function
var xmlHttp = (function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
return xmlHttp;
}
//handleStateChange is written in such a way that is expects xmlHttp to be a global variable.
function handleStateChange(xmlHttp){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
//alert(xmlHttp.status);
//alert(xmlHttp.responseText);
document.getElementById("results").innerHTML = xmlHttp.responseText;
}
}
}
function suggest() {
startRequest("ajax-submit.php?search_text="+document.search.search_text.value");
}
</script>
and HTML code:
<body>
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
</body>
and ajax-submit.php:
<?php
//echo 'Something';//'while typing it displays Something in result div
echo $_GET['search_text'];
?>

Categories

Resources