on my web page i have text area like this
and i suppose to get data in textarea when i alternate the value of select box( or onChange event), so i used ajax function
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function myCall() {
var request = $.ajax({
url: "ajax.php",
type: "GET",
dataType: "html"
});
request.done(function(msg) {
$("#mybox").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
and this is my select box code,
<select name="txtname" id="txtname" onChange="myCall()" >
<option value="0">Select Age:</option>
<option value="100083">100083</option>
<option value="22-26">22-26</option>
<option value="26-30">26-30</option>
<option value="30-34">30-34</option>
</select>
actualy i want to fetch record on the basis of select box value, this function working fine for static value but i am puzzled how to get data from data base..
and my ajax page coding is here..
<?php
$con=mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("hmc", $con);
$sql="SELECT * FROM news WHERE name = '22-26'";
$result = mysql_query($sql);
?>
<?php
while($row=mysql_fetch_array($result))
{
?>
<tr>
<td>
<?php echo $row['news1'];?></h3></td>
</tr><br /><hr /><br />
<?php
}
?>
</div>
any idea will be appreciated...
Your ajax call is not proper, you need to pass your select box value to the php side, like this
$.ajax({
url: "ajax.php",
type: "GET",
dataType: "html",
data:"value="+$("#txtname").val();
});
then use this value on php side using $_GET['value']
Related
I'm trying to use ajax on a select tag with 2 options, but it's not getting the $_POST for some reason. It prints out the "---", but it does not print out the $_POST value, which is either 1 or 2. I'm not sure what I did wrong. Please take a look at my code:
newtest.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>
<?php
echo "<select name = 'name' onchange = 'ajax(\"newtestx.php\",\"input\",\"name\",\"output\")'>";
echo "<option value = '1'> 1 </option>";
echo "<option value = '2'> 2 </option>";
echo "</select>";
echo "<div id = 'output'></div>";
?>
newtestx.php
<?php
$name = $_POST['name'];
echo $name."---";
?>
You are sending a POST parameter with the key "select" to the server in your AJAX call:
data: { select: $(type+'[name='+theName+']').val()},
In newtestx.php you are trying to retrieve the value from a POST parameter with the key "name" - which doesn't exist:
$name = $_POST['name'];
You could fix this easily by giving the parameter keys the same name. If you would look for $name = $_POST['select'] the parameter would be found.
Inline Javascript is considered bad practice and there's no need to echo out the HTML markup, it makes the mark up harder to work with.
newtest.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="[link to your javascript file here]"></script>
<select name='numbers' class="postValueOnChange" data-id-to-update="output" data-post-url="newtestx.php">
<option value='1'>1</option>
<option value='2'>2</option>
</select>
<div id='output'></div>
Javascript file
$(document).ready(function () {
$('.postValueOnChange').change(postSelectedValue);
function postSelectedValue(e) {
var $self = $(this);
var url = $self.data('post-url');
var $elementToUpdate = $('#' + $self.data('id-to-update'));
var jqxhr = $.ajax({
type: "POST",
url: url,
data: {
selected: $self.val()
}
});
jqxhr.done(function (data) {
$elementToUpdate.html(data);
});
jqxhr.fail(function (jqXHR, textStatus, errorThrown) {
alert(errorThrown);
});
}
});
newtestx.php
<?php
$name = $_POST['selected'];
echo $name."---";
?>
You are sending post param select and trying to receive as $_POST['name'].
Make sure they match...either both as name or as select
First, Since you are using jQuery, why are you still using inline javascript?
Well I suggest you first to restrucure your code around the jQuery change event:
$(document).ready(function() {
$('select').change(function(e) {
e.preventDefault();
var selected = $('.select option:selected').val();
var id, theName, url= ...// get it from the DOM
$.ajax({
type: "GET",
url: url,
data: { select: selected},
error: function(xhr,status,error){alert(error);},
success:function(data) {
$('#'+id).html(data);
}
});
});
});
Second, why are you coding HTML with PHP, you are making yourself struggle and lose time only with quotes and double quotes, and no-needed spaces.
<form action="">
<select name="name">
<option value="1">1</option>
<option value="1">1</option>
</select>
</form>
<div id="output"></div>
Table book contains: book_id,book_title
Table bookext contains: bookext_id,book_id(foreigned key to book),bookext_tag
Here is my script where i want to populate my dropdown is.
<script>
function get_bookextt() {
var request = $.ajax({
url: "getbookext.php",
type: "POST",
dataType: "html"
});
request.done(function(msg) {
$("#get_bookext").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
Seeing that code, here is the body part for my first dropdown that will associate the second dropdown that must appear
<select id="book" name='book' onchange="get_bookextt();">
<option value=''>Select</option>
<?php while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['book_id'] . "'>" . $row['book_title'] . "</option>";}
?>
</select>
<div id="get_bookext"></div>
I really feel dumb for posting my whole getbookext.php file in here because I think this is where I messed up.
<?php
include 'db_connection.php';
if ($_POST) {
$book_id = $_POST['book_id'];
if ($book_id != '') {
$sql1 = "SELECT * FROM bookext WHERE book_id=" . $book_id;
$result1 = mysql_query($sql1);
echo "<select name='bookext'>";
echo "<option value=''>Select</option>";
while ($row = mysql_fetch_array($result1)) {
echo "<option value='" . $row['bookext_id'] . "'>" . $row['bookext_tag'] . "</option>";}
echo "</select>";
}
else
{
echo '';
}
}
?>
Please pinpoint to me where did I go wrong.
--EDITED--
Here is my whole head area
include 'db_connection.php';
$sql = "SELECT * FROM book";
$result = mysql_query($sql);
?>
<script>
function get_bookextt() {
var request = $.ajax({
url: "getbookext.php",
type: "POST",
data: {'book_id', $(this).val()},
dataType: "html"
});
request.done(function(msg) {
$("#get_bookext").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
Whilst here is the whole body area
<select id="book" name='book' onchange="get_bookextt($(this).val());">
<option value=''>Select</option>
<?php while ($row = mysql_fetch_array($result)) {
echo "<option value='" . $row['book_id'] . "'>" . $row['book_title'] . "</option>";}
?>
</select>
<div id="get_bookext"></div> // Sub will be appended here using ajax
PS1. I don't understand why get_bookextt($(this).val()); isn't highlighting in my notepad++.
Your AJAX request doesn't have book_id in it which your PHP needs to return the data, http://api.jquery.com/jquery.ajax/.
So your JS function should be something like...
function get_bookextt(book_id) {
var request = $.ajax({
url: "getbookext.php",
type: "POST",
data: {'book_id': book_id},
dataType: "html"
});
request.done(function(msg) {
$("#get_bookext").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
Then your HTML should send the value on change so swap the select to:
<select id="book" name='book' onchange="get_bookextt($(this).val());">
When I have issues with AJAX requests the first thing I do is look at the request in the developer tools of Chrome.
Make sure the request makes it to the PHP script
Make sure it sends the data I'm expecting
Here's an article on using the tools, it's written using IE but Chrome is pretty similar. http://forums.asp.net/t/1982579.aspx?Using+the+browser+s+dev+tools+to+diagnose+ajax+problems+and+other+things+
You also should switch over to PDO or mysqli so you case use prepared statements and because mysql_ is deprecated. There are two current ways to limit injection possibilities.
Cast your POST id as an int so it has to be a number.
Use the mysql_real_escape_string
Option 1:
$book_id = (int)$_POST['book_id'];
Option 2:
$book_id = mysql_real_escape_string($_POST['book_id']);
Here's a thread for when you switch over on how to prevent these. How can I prevent SQL injection in PHP?
UPDATE
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
<script type="text/javascript">
function get_bookextt(book_id) {
var request = $.ajax({
url: "getbookext.php",
type: "POST",
data: {'book_id': book_id},
dataType: "html"
});
request.done(function(msg) {
$("#get_bookext").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
</script>
<select id="book" name='book' onchange="get_bookextt($(this).val());">
<option value=''>Select</option>
<option value='1'>test</option>
</select>
<div id="get_bookext"></div>
</body>
</html>
There is a xyz dropdown on the basis if this I am hitting AJAX get data but the response data I got in console but the data is not rendering in front view dropdown.
Here is my html and php code. I got the value it's just not showing in front view:
<tr>
<td class="style2"> District </td>
<td><select name= "district" id="district_response" class="span6 chzn-select" >
<option value="">Select District</option>
</select></td>
</tr>
PHP code
<?php $con = mysqli_connect("hostname","username","password","DBname") or die (mysql_error());
$sname = $_POST['state_select'];
$sq = "SELECT distinct(bank_district) FROM bank_all whereb ank_state ='".$_POST['state_select']."' order BY bank_district ASC";
$result1 = mysqli_query($con,$sq) or die('Error'.mysqli_error());
$resul1="";
while($row=mysqli_fetch_assoc($result1)){$resul1.= "<option value ='{$row["bank_district"]}' >{$row["bank_district"]}</option>";}echo $resul1;?>
function jsFunction(){
var myselect = $('#state_response').val();
jQuery.ajax({
url: "districtajax.php",
global: false,
type: "POST",
data: ({
state_select:myselect,
}),
dataType: "html",
async: false,
success: function (msg) {
console.log(msg);
//return false;
$('#district_response').html(msg);
}
});
}
</script>
Hello I am trying to make a <select> menu from which when you select some of the options the selected option to be writen inside the database using Ajax, here is what I have acomplished so far:
this is my select menu:
<select name="status">
<option value="">Select option:</option>
<option value="aproved">aproved</option>
<option value="canceled">canceled</option>
</select>
Here is my java script which should select the change and send it to the backend php file where the database conection and the UPDATE query are, the select method is ot working ot it is not updating imediately after a selection is done. The Goal is once a user make a selection the result to go inside the database withoud the need of pressing button or doing anything else.
<script>
$(document).ready(function(e) {
$('select[name=status]').change(function(){
selectstatus = $("select[name=status]").val();
$.ajax({
type: "POST",
url: "selectbackend.php",
data: {"selectstatus": selectstatus
},
})
.done(function(data, textStatus, jqXHR){alert(textStatus);})
.fail(function(jqXHR, textStatus, errorThrown){alert(jqXHR+"--"+textStatus+"--"+errorThrown);});
});//end change
});//end ready
</script>
but it is not working either is giving any error, my suspicions are that the java script is not working in some way.
here is backend file:
<?php
$selectstatus = $_POST['selectstatus'];
$cxn = mysqli_connect($host,$user,$password,$dbname);
if (mysqli_connect_errno()) {echo "No connection" . mysqli_connect_error();}
$query = " UPDATE test
SET var = '$slectstatus'
WHERE id='1";
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<html>
<select id="status" name="status">
<option value="">Select option:</option>
<option value="aproved">aproved</option>
<option value="canceled">canceled</option>
</select>
</html>
<script>
$(document).ready(function(){
$('#status').change(function(){
//var selectstatus = $("select[name=status]").val();
$.ajax({
type: "POST",
url: "selectbackend.php",
data: {"selectstatus": $(this).val()},
})
.done(function(data, textStatus, jqXHR){alert(textStatus);})
.fail(function(jqXHR, textStatus, errorThrown){alert(jqXHR+"--"+textStatus+"-- +errorThrown);});
});//end change
});//end ready
</script>
Then:
<?php
$selectstatus = addslashes($_POST['selectstatus']);
$cxn = mysqli_connect($host,$user,$password,$dbname);
if (mysqli_connect_errno()) {echo "No connection" . mysqli_connect_error();}
$query = " UPDATE test
SET var = '$selectstatus'
WHERE id='1'";
try this:
<script>
$(document).ready(function(e) {
$('select[name=status]').change(function(){
selectstatus = $("select[name=status]").val();
$.ajax({
type: "POST",
url: "selectbackend.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({"selectstatus": selectstatus}),
})
.done(function(data, textStatus, jqXHR){alert(textStatus);})
.fail(function(jqXHR, textStatus, errorThrown){alert(jqXHR+"--"+textStatus+"--"+errorThrown);});
});//end change
});//end ready
</script>
Basically I have a list of data that is shown via a foreach statement from a table in my database. I want a dropdown list next to each that has some values in them that need to be saved to a field in my table, however I want to autosave the value in the dropdown list to the field as soon as the value in it is changed. Can anyone point me to a tutorial or something that might help?
I am using php and mysql to create the system, but will happily use JavaScript if required
I have had a look at this: dynamic Drive Autosavehttp://www.dynamicdrive.com/dynamicindex16/autosaveform.htm which is similar to what i want, however i need it to actually store that data in my database not temporary storage.
Any Guidance appreciated,
Ian
BIG EDIT
So, thankyou for the replys but I have no clue about ajax call.....I found this:How to Auto Save Selection in ComboBox into MYSQL in PHP without submit button?.
can i get it to work?
<script>
$(document).ready(function(){
$('select').live('change',function () {
var statusVal = $(this).val();
alert(statusVal);
$.ajax({
type: "POST",
url: "saveStatus.php",
data: {statusType : statusVal },
success: function(msg) {
$('#autosavenotify').text(msg);
}
})
});
});
</script>
<?php foreach ( $results['jobs'] as $job ) { ?>
<td width="25%"><?php echo $job->job_id</td>
<td>
<select name="status" id="status">
<option value=''>--Select--</option>
<option value='0'>Approve</option>
<option value='1'>Reject</option>
<option value='2'>Pending</option>
</select>
<div id="autosavenotify"></div>
</td>
</tr>
<?php } ?>
and on the page saveStatus.php:
<?php
if (isset($_POST['statusType'])) {
$con=mysql_connect("localhost","username","mypass","rocketdb3");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("jobs", $con);
$st=$_POST['statusType'];
$query = "UPDATE jobs SET status=$st WHERE job_id=$id";
$resource = mysql_query($query)
or die (mysql_error());
}
?>
Where is the $id in saveStatus.php ?
You need to pass the statusType and job_id via AJAX to update correctly in the saveStatus.php.
For example:
<script>
$(document).ready(function(){
$('select').on('change',function () {
var statusVal = $(this).val();
var job_id = $(this).id;
alert(statusVal);
$.ajax({
type: "POST",
url: "saveStatus.php",
data: {statusType : statusVal, job_id: job_id },
success: function(msg) {
$('#autosavenotify').text(msg);
}
})
});
});
</script>
<?php foreach ( $results['jobs'] as $job ) { ?>
<td width="25%"><?php echo $job->job_id; ?></td>
<td>
<select name="status" id="<?php echo $job->job_id; ?>">
<option value=''>--Select--</option>
<option value='0'>Approve</option>
<option value='1'>Reject</option>
<option value='2'>Pending</option>
</select>
<div id="autosavenotify"></div>
</td>
</tr>
<?php } ?>
*Note: .live() is deprecated, use .on() instead.
And saveStatus.php
$st = (int)$_POST['statusType'];
$id = (int)$_POST['job_id'];
$query = "UPDATE jobs SET status=$st WHERE job_id=$id";
You will need to use JavaScript (+ jQuery for easier working) to achieve this.
Catch the 'change' of the value using JavaScript and fire an AJAX call to a PHP script that saves the value to the MySQL db.
Use jQuery! On the drop-down onchange event do a ajax call and update the record in DB. Here is a link to jQuery Ajax method.