Why isn't my AJAX code working? - javascript

I believe this should be pretty trivial, but I cannot figure it out at all. I am doing a small test with sending an AJAX request, and echoing a variable extracted from a drop-down menu.
However, it doesn't seem to be executing whatsoever. I was wondering if someone could help me point out what's wrong?
Here are the relevant snippets from index.php:
<html>
<?php
//create a drop down of available accounts
echo 'Available Accounts: ';
echo '<select name=dropAccounts class=dropAccounts>';
//if there is at least one account available
if (count($accsAvailable) > 0) {
echo '<option value=0>---Select an account---</option>'; //default option
foreach ($accsAvailable as $account) {
//populate from API
echo '<option value=' . $account->getId() . '>' . $account->getName() . '</option>';
}
} else {
echo '<option value=0>---No accounts---</option>'; //else if no accounts exist
}
echo '</select>';
//for available webproperties
echo '<br> Available Webproperties: ';
echo '<select name=dropProperties class=dropProperties>';
echo '<option selected=selected>---Select a webproperty---</option>';
echo '</select>';
?>
</html>
The important thing to take away from the snippet is that the first drop-down menu is called 'dropAccounts'.
here is my JS script for handling an onchange event on 'dropAccounts':
<script type="text/javascript">
$(document).ready(function()
{
$(".dropAccounts").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "propertyID.php",
data: dataString,
cache: false,
success: function(html)
{
$(".dropProperties").html(html);
}
});
});
});
</script>
I eventually intend to populate the second drop-down menu 'dropProperties' using the value grabbed from 'dropAccounts' but it's not even echoing in my PHP script.
propertyID.php:
<?php
if($_POST['id'])
{
$accountID = $_POST['id'];
echo $accountID;
}
?>
I was following the tutorial found here: http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html

According to what I see the problem is the following:
var dataString = 'id='+ id;
data: dataString
You need to send the data in the following way;
data : {
'id' : id
}
And it should send you the data in the correct format.
EDIT: I'm adding this to clarify how your code would look.
<script type="text/javascript">
$(document).ready(function()
{
$(".dropAccounts").change(function()
{
var id=$(this).val();
$.ajax
({
type: "POST",
url: "propertyID.php",
data: {
'id' : id
},
cache: false,
success: function(html)
{
$(".dropProperties").html(html);
}
});
});
});
</script>

your generated html is not valid. every class and name should be inside quotes.
Change your index.php
like this:
<html>
<?php
//create a drop down of available accounts
echo 'Available Accounts: ';
echo '<select name="dropAccounts" class="dropAccounts">';
//if there is at least one account available
if (count($accsAvailable) > 0) {
echo '<option value="0">---Select an account---</option>'; //default option
foreach ($accsAvailable as $account) {
//populate from API
echo '<option value="' . $account->getId() . '">' . $account->getName() . '</option>';
}
} else {
echo '<option value="0">---No accounts---</option>'; //else if no accounts exist
}
echo '</select>';
//for available webproperties
echo '<br> Available Webproperties: ';
echo '<select name="dropProperties" class="dropProperties">';
echo '<option selected=selected>---Select a webproperty---</option>';
echo '</select>';
?>
</html>
you should append in the ajax success callback:
$(".dropProperties").append(html);

There are a couple of issues here!
For the sake of legibility and syntax highlighting (not to mention that it will draw awareness to your mistakes) you should use direct html output instead of echoing it with php.
Instead of
echo '<select name=dropAccounts class=dropAccounts>';
try
//End php parsing with a closing php tag
?>
<select name=dropAccounts class=dropAccounts>
<?php
//Resume php parsing
This draws attention to the fact that you're not surrounding your attribute values with quotes
Instead of
<select name=dropAccounts class=dropAccounts>
It's important that you quote the attribute:
<select name="dropAccounts" class="dropAccounts">
The next thing is that you're trying to insert the server's output (a raw STRING) into a select element with this code:
success: function(html) {
$(".dropProperties").html(html);
}
I believe this is what you want instead:
success: function(html) {
var newOption = $('<option value="' + html + '">' + html + '</option>');
$(".dropProperties").append(newOption);
}
According to html specification, only option elements should be the children of select elements. In order to add a string into the select element, my code is creating a new option element, making its text the "html" string, and inserting that option element into the select element.
Hope this helps!

Related

How to put Onchange on Ajax returned html select

I have a problem putting Onchange() on a ajax returned html on my form.
Basically I have clients listed in a select.
<select name="company" id="company">
<?php
$sqlget1 = "SELECT * FROM clients WHERE 1=1 ORDER BY company ASC;";
$resget1 = mysql_query($sqlget1);
while($row1 = mysql_fetch_array($resget1)) {
?>
<option value="<?php echo $row1['id']; ?>"><?php echo $row1['company']; ?></option>
<?php
}
?>
</select>
And when some one selects a client, im using Ajax to fetch projects that are assigned to that client.
$('#company').change(function() {
var selectedProject = $("#company option:selected").val();
$.ajax({
type: "POST",
url: "get_projects.php",
data: { projects : selectedProject }
}).done(function(data){
$("#response").html(data);
});
});
It gets returned back to
<div id="response"></div>
The code for get_projects.php is
<?php
include('inc.php');
if(isset($_POST["projects"])) {
$projects = $_POST["projects"];
$sqlget2 = "SELECT * FROM projects WHERE cid=\"$projects\" ORDER BY pname ASC;";
$resget2 = mysql_query($sqlget2);
echo '<select name="project" id="project" class="select2 form-control">';
echo '<option value="">-- Select a project --</option>';
while($row2 = mysql_fetch_array($resget2)) {
?>
<option value="<?php echo $row2['id']; ?>" pstatus="<?php echo $row2['pstatus']; ?>" ptype="<?php echo $row2['ptype']; ?>"><?php echo $row2['pname']; ?></option>
<?php
}
echo '</select>';
}
?>
Now when i use on change function on the returned html from ajax it is not working.
I tried to see the source code and found out that it is not there atall. It only shows the <div id="response"></div>
But i can see the result on the form but cant see the source in the source code.
Hence i thought that's why the Onchange() is not working for <select name="project" id="project" class="select2 form-control"> because it is not showing.
I see, the data which is return from Ajax is object
You should parse it to get the raw content an set into DIV
When you are dynamically adding mark up to the page the javascript doesn't know about the controls you have added through php.
Try finding the newly added control like this:
var select = document.getElementById('project');
Then you should be able to fire your on change method
Not tested, but it should work
<?php
include('inc.php');
if(isset($_POST["projects"]))
{
$projects = $_POST["projects"];
$varOut = "";
$sqlget2 = "SELECT * FROM projects WHERE cid=\"$projects\" ORDER BY pname ASC;";
$resget2 = mysql_query($sqlget2);
$varOut .= '<select name="project" id="project" class="select2 form-control">';
$varOut.= '<option value="">-- Select a project --</option>';
while($row2 = mysql_fetch_array($resget2))
{
$varOut.= "<option value=" . $row2['id'] . " pstatus=". $row2['pstatus']. ">ptype=".$row2['ptype']."><".$row2['pname']."></option>";
}
$varOut.= '</select>';
}
echo $varOut;
?>
I've finally solved the issue.
Basicall i just pasted the Onclick() script for '#projects' inside the get_projects.php file.
So now every time when it comes from ajax it also brings the javascript as well.
When you use ajax, you add a piece of html later to the DOM (browsers view), because you use .change the onchange is only added to the '#company' elements wich already exist in the browser.
You need to bind the onchange after you appended the html. for example:
$('#company').change(function() {
onCompanyChange()
});
function onCompanyChange(){
var selectedProject = $("#company option:selected").val();
$.ajax({
type: "POST",
url: "get_projects.php",
data: { projects : selectedProject }
}).done(function(data){
$("#response").html(data);
$('#company').change(function() {
onCompanyChange()
});
});
}
OR
You can also use an on change, on change does work with elements added later to to the dom. so this code works with elements wich already exists and new added elements with for example ajax
$("#company").on("change",function(){
console.log("change");
});
Try below code. Hope this works fine.
$(document).ready(function() {
$(document).on('change', '#company', function() {
var selectedProject = $("#company option:selected").val();
$.ajax({
type: "POST",
url: "get_projects.php",
data: { projects : selectedProject }
}).done(function(data){
$("#response").html(data);
});
});
});

Get data from Database Using Ajax and PHP and Return Result as Dropdown list

I have the idea of what i wanted but need assistance on how to get it done.Below is the scenerio: I have a two dropdwon. The First dropdown is fetched from the DB, which works fine. At the change event of the first dropdown,the system should go to the Database, and fetch the result into the next dropdown. see what I have done so far for assistance:
JQUERY SECTION
<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#locate").change(function(){
var selectedloc = $("#locate option:selected").val();
$.ajax({type: "POST",url:"process-loc.php",data:{loca:selectedloc}}).done(function(data){
var ans=jQuery.parse(data);
//using php-mysql before
var ps = ans.res;
$("#subloc").html(ps);
});
});
});
</script>
FrontEnd(HTML)
<tr>
<th>Primary Location:</th>
<?php
$result = mysqli_query($connection,"SELECT * FROM tab_location");?>
<td>
<select name="locate" class="form-control" id="locate">
<option>Select Main Location</option>
<?php while($rw = mysqli_fetch_array($result)){ ?>
<option value="<?php echo $rw['location_name'];?>"><?php echo $rw['location_name'];?></option>
<?php };?>
</select>
</td>
</tr>
<tr>
<th>Sub Location:</th>
<td id="subloc"></td>
</tr>
Process-loc.php
if(isset($_POST["loca"])){
include 'includes/session.php';
include 'includes/db_connection.php';
include 'includes/functions.php';
$main = $_POST["loca"];
$gets = "SELECT * FROM tab_fltlocation WHERE mainloc='".$main."'";
$get = mysqli_query($connection,$gets);
$gt = mysqli_fetch_array($get);
//$nos= $gt['opsNo'];
if(mysqli_num_rows($get)>=0)
{
echo json_encode(array("res"=>$gt));//or do a dropdown using <select name='subloc'><option value=$gt['loc']>$gt['loc']</option></select>
}else{
echo json_encode(array("res"=>"0"));
}
}
?>
This is what I wants to be displayed on the Front End page for the use:
$gt['loc']
How can I achieve this.
$query = "
SELECT
tariff_name
FROM tariff_setting";
$result = mysqli_query($this->_connection, $query);
while ($row = mysqli_fetch_assoc($result))
$response[] = $row['tariff_name'];
}
$tarrifList = json_encode($response);
// $tarrifList is the response and sent it in json encode format and decode on ajax success
// Javascript Process
var obj = JSON.parse(resdata);
var areaOption = "<option value=''>Select State</option>";
for (var i = 0; i < obj.length; i++) {
areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'
}
$("#patientSelectState").html(areaOption);
You can change your AJAX processor to do this:
Process-loc.php
/* Above code the same */
if(mysqli_num_rows($get)>=0) {
$out = '<select id="selSubLoc"><option value="">Choose One:</option>';
foreach($gt AS $loc){
$seld = ($_POST['loca'] == $loc) ' selected' ? : '' ;
$out .= '<option value="' .$loc. '" ' .$seld. '>' .$loc. '</option>';
}
$out .= '</select>';
}else{
$out = 0;
}
echo $out;
And change your front-end code's AJAX routine to be like this:
$.ajax({
type: "POST",
url:"process-loc.php",
data:{loca:selectedloc}
}).done(function(recd){
$("#subloc").html(recd);
});
The data received back from PHP will be in HTML format unless you use dataType: to change it, so you can build the HTML over on the PHP side and then just plop it into the #subloc table cell.
On the event of the first box call the function containing the ajax which would retrieve information from the database. This ajax call will get data according to the first input.
Now query your database and echo the results in a foreach loop(you can make a tag there only).
In the ajax 'success:' catch the data and display it.
//from the database
foreach ($info as $product)
{
echo "<option value=".$product['childsticker_id'].">".$product['name']</option>";
}
//ajax call page
success: function(result)
{
$("#states").html(result);
}
http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html

div replacing everything after it, AJAX, PHP, JAVASCRIPT

Using ajax, I'm trying to display what is being selected on a div, and it's working, but everything after the div gets replaced by the div's output. I don't know why it's happening or how to fix it. If you know, please let me know.
test1.php
<?php
include('ajax.php');
echo "<select name = 'select' onchange = 'ajax(\"test2.php\",\"select\",\"select\",\"output\")'>";
echo "<option value = '1'> one </option>";
echo "<option value = '2'> two </option>";
echo "<option value = '3'> three </option>";
echo "</select>";
echo "<div id = 'output'>";
echo "text";
?>
test2.php
<?php
$select = $_POST['select'];
echo $select;
?>
ajax.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function ajax(url,type,theName,id) {
$.ajax({
type: "POST",
url: url,
data: { select: $(type+'[name='+theName+']').val()},
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( id ).innerHTML = data;
}
});
}
</script>
I testing your code in my pc and it worked. But after change this echo "<div id = 'output'>"; into this echo "<div id = 'output'></div>";, the output only show inside div block and everything after the div gets not replaced.
If you want something similar to onload, just use trigger function to trigger the onchange event after page load like so :
function ajax(url,type,theName,id) {
$.ajax({
type: "POST",
url: url,
data: { select: $(type+'[name='+theName+']').val()},
error: function(xhr,status,error){alert(error);},
success:function(data) {
document.getElementById( id ).innerHTML = data;
}
});
}
$(function(){
$('select[name="select"]').trigger('change');
});
You are missing the closing div tag.

How using ajax can update mysql database from dropdown menu

As the question suggest can you tell me how i can update mysql database using a dropdown menu with the help of ajax. I want to update my database with out reloading my whole webpage.When a user click edit button the selected option from the drop down list is updated. After searching a while i found some tutorials for this method and took ajax codes from there. But when i tried those in my database; it didn't worked out. Below is the sample code for my php script, parent file contains both ajax script and php code in a single php file called samefile.php. Below script only contains the problematic codes, some html and php codes are intentionally removed.
//THIS AJAX SCRIPT FETCHES VALUES FROM THE SELECTED DROPDOWN
<script>
function get_da(str){
$.ajax({
url: "samefile.php",
type: "POST",
async: true,
data: { dropdown1:$("#dropdown").val()}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
}
);
</script>
///////////////////////////////FIRST BLOCK//////////////////
<?php
//THIS PHP SCRIPT GENERATES DROP DOWN VALUES FROM DATABASE
echo "<select name='dropdown' onChange='get_da(this.value)'>";
while ($row = mysql_fetch_array($result))
{
if($row['id']==$row['user'])
{
echo "<option value='" . $row['id'] . "' selected>" . $row['name'] . "</option>";
}
else{
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
}
echo "</select>";
/////////////////////////////SECOND BLOCK//////////////////////////////
//THIS PHP SCRIPT VALIDATES THE SELECTED DROPOWN VALUE AND PASS THOSE VALES FOR FURTHER PROCESSING.
if(isset($_REQUEST['dropdown1']))
{
$name=get_the_selected_dropdown_name; //i dont know how to fetch name from dropdown menu
$sql = "UPDATE table SET name = '$name' WHERE id =10";
mysql_real_escape_string($sql);
$result = mysql_query($sql) or die (mysql_error());
if ($result==1) {
echo "Success";
}
else { echo "Failed";}
}
//////////////////////////////THIRD BLOCK////////////////////////////////////
?>
I believe this is how my above script works. when a user select a particular option from the drop down menu this function onChange='get_da(this.value)' sends the value (both id and name) to ajax query. in ajax query the drop down values are collected (both id and name) and renames as dropdown1 (data: { dropdown1:$("#dropdown").val()}) and pass it to php script inside the same file. Php script confirms the request from ajax using this if(isset($_REQUEST['dropdown1'])) and the script inside will be executed.
Please forgive me if i made a mess of my code. I suck at java script and ajax so am not sure whether my coding is right for those scripts. if possible can you suggest any other scripts for updating mysql database using ajax drop down list.
EDITED
ID DROPDOWN VALUE
1 ROY
2 TOM
3 CHASE
4 THOMAS
5 GEORGE
6 MICHAEL
have tried by printing the value you are sending in ajax request. You are passing this.value to your function get_da(str). But I think you are using it anywhere , In ajax post you are sending the value like
data: {dropdown1:$('#dropdown').val()}
But this will not post your selected vaule from dropdown, Try like this:
<script>
function get_da(this){
var id = $("#dropdown option:selected").val();
var selectedName = $("#dropdown option:selected").text();
$.ajax({
url: "samefile.php",
type: "POST",
async: true,
data: { dropdown1:id, name:selectedName}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
//drawVisualization();
},
});
}
</script>
Hope this will work.
Your dropdown script should be like this:
<?php
echo "<select name="dropdown" onchange="get_da()" id="dropdown">";
while ($row = mysql_fetch_array($result))
{
if($row['id']==$row['user'])
{
echo "<option value='" . $row['id'] . "' selected>" . $row['name'] . "</option>";
}
else{
echo "<option value='" . $row['id'] . "'>" . $row['name'] . "</option>";
}
}
echo "</select>";
This will send your selected value from drop down to your samefile.php.And also you are not doing good with your php script it should be like:
if(isset($_REQUEST['dropdown1']))
{
$id=$_REQUEST['dropdown1'];
$name=$_REQUEST['name'];
$sql = "UPDATE table SET name = '$name' WHERE id ='$id'";
mysql_real_escape_string($sql);
$result = mysql_query($sql) or die (mysql_error());
if ($result==1) {
echo "Success";
}
else { echo "Failed";}
}
?>

how to select the select box item based on another and vice versa

how to select the select box item based on one another and vice versa.here I use ajax for redirect to query page.
while($fet = mysql_fetch_assoc($sql1))
{
echo "<option value=".$fet['username'].">".$fet['username']."</option>";
}
echo '</select></td>';
echo "<td><div id='myDiv'><select id=id name=id onchange=loadXMLDoc()>";
$sql = "select * from sample";
$sql1 = mysql_query($sql);
while($fet = mysql_fetch_assoc($sql1))
{
echo "<option value=".$fet['id'].">".$fet['id']."</option>";
}
echo '</select></div></td>';
You Need To Use Ajax For That,
For Example You Have A Select like This
<select id=id1 name=id1 onchange=loadXMLDoc()>
here is the second one you want to change
<select id=id2 name=id2>
On Javascript You Call a php file via ajax Like This
function loadXMLDoc(){
$.ajax({ // i think you used jquery on your project
type: "post",
url: "getdata.php",
data: $('input[\'name=id1\']'),
dataType: "json",
success:(function(result){
html = '';
if(result.data.length > 0){
$.each(result.data, function( index, value ) {
// alert( index + ": " + value );
html += '<option value="'+value.id+'">'+value.title+'</option>';
});
$('#id2').html(html);
}else{
// nothing
}
}));
});
}
then on php file you just echo the json_encode result you want to get
$sql = mysql_query('SELECT id,title FROM your_table Where your_field='.$_POST['id1']);
$query= mysql_query($sql);
while( $row = mysql_fetch_array($query)){
$json['data'][] = array('id' =>$row->id,'title'=>$row->title )
}
echo json_encode($json);

Categories

Resources