Codeigniter ajax send data to controller using ajax code - php

<script type="text/javascript">
$(document).ready(function () {
$("#select-dept").change(function () {
var id = $("#select-dept").val();
$.ajax({
type: "POST",
url: "<?=base_url()?>.index.php/sms/get_dept_employee",
//url: baseurl + 'sms/get_dept_employee',
data: "id",
dataType = "json",
cache: "false",
success: function (emp_list) {
$("#dept-emp").html(emp_list);
}
});
});
});
</script>
I am unable to send view data to controller function
In view their is select box with departmenr values from mysql database
<select class="select-dept" id="select-dept" name="select-dept">
<option>Select Department</option>
<?foreach ($departments as $dt):?>
<option value="<?=$dt['id']?>">
<?=$dt[ 'name']?>
</option>
<?endforeach;?>
</select>
i need to get refresh when user select department and that need to call controller function
get_dept_employee
And need to display datagrid of employee list

you need to send data option as object
try this
.....
url: "<?=base_url()?>.index.php/sms/get_dept_employee",
data: {"id":id},
dataType:"json",
....
and get the posted value as id in your controller..
$id=$this->input->post('id');
....

var id = $("#select-dept").val();
data:"id", //Here you are sending string as id
should be
data:id, //No double quotes surrounded

Try:
data: {'id':$(this).val()},

i saw few errors
use data: {'id':id}, instead of data: "id",
use dataType:"json", instead of dataType="json",
use cache:false instead of cache: "false",
<script type="text/javascript">
$(document).ready(function () {
var base_url = "<?php echo $this->config->item('base_url'); ?>";
$("#select-dept").change(function () {
var id = $(this).val();
$.ajax({
type: "POST",
url: base_url+"index.php/sms/get_dept_employee";
data: {'id':id},
dataType:"json",
cache: false
success: function (emp_list) {
$("#dept-emp").html(emp_list);
}
});
});
});
</script>

Related

Get Div value when clicked using AJAX

<div id = "Class" class = "Class_ticket" onclick = "caller()" value = "1">
I am trying to get value of div where ID is Class when Div is clicked.
function caller(){
$.ajax({
url: "test.php",
type: "get",
data: {
Class_info: $('#Class').val()
}
}).done(function(data) {
$('#Result').text(data);
alert(data);
});
}
Looks like it isn't reading the value of Div when clicked. Am I using AJAX wrongly?
test.php
<?php
$a = $_GET['Class_info'];
echo($a);
?>
div tag dont have value attribute. So you can use $('#Class').attr('value');
check snippet below..
function caller(){
alert($('#Class').attr('value'));
$.ajax({
url: "test.php",
type: "get",
data: {
Class_info: $('#Class').attr('value')
}
}).done(function(data) {
$('#Result').text(data);
alert(data);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id = "Class" class = "Class_ticket" onclick = "caller()" value = "1">test</div>
You can use this little trick:
<div id "" class="Class_ticket" onclick="caller()" value="1">
<input type="hidden" value="1" id="Class" />
</div>
note that the input is hidden!
And here is your ajax:
function caller() {
$.ajax({
url: "test.php",
type: "get",
data: {
Class_info: $('#Class').val()
}
}).done(function(data) {
$('#Result').text(data);
alert(data);
});
}
Try this:
function caller(){
$.ajax({
url: "test.php?Class_info=test",
type: "get",
data: {
Class_info: $('#Class').val()
}
}).done(function(data) {
$('#Result').text(data);
alert(data);
});
}
I added ?info=test which in theory PHP should be able to take
if PHP takes the value, then instead of test put a variable containing the desired value

AJAX not being called when select box changed

I am using jquery to call a PHP script when a select box changes. I am able to get the ID of the select item that changes, however I get no output from the PHP script. The Javascript is
function initagents() {
$('select.agent').on('change', function() {
var id = $(this).attr("id");
console.log(id);
var data = { id: id };
$.ajax({
type: "POST",
dataType: "json",
url: "updateagent.php",
data: data
}).done(function(msg) {
console.log(msg);
});
});
}
and the PHP is
print_r ( $_POST);
Any ideas?
Please use
echo json_encode($_POST['id']);
instead of
print_r($_POST);
You have made a mistake by placing the onChange event of the select box inside function initagents().
fixed code:
$('select.agent').on('change', function() {
var id = $(this).attr("id");
console.log(id);
var data = {
id: id
};
$.ajax({
type: "POST",
dataType: "json",
url: "updateagent.php",
data: data
}).done(function(msg) {
console.log(msg);
});
});
Just try with the following code:
function getID(val) {
alert(val);
$.ajax({
type: 'POST',
url: 'post.php',
data: {
id: val
},
success: function(data) {
alert(data);
}
});
}
<select name="pks" onchange='getID(this.value);'>
<option value="1">Option1</option>
<option value="2">Option2</option>
</select>
Seems your code is correct and it should send the data to php file. But also I see that, you are not sending selected value to php script. You are posting selected element ID.
Are you trying this in a sub folder ? make sure the php file path is correct in javascript. Better if you can try with the full path. For example
url: "http://localhost/myproject/updateagent.php",

PHP AJAX - Pass a PHP value from one page to another using AJAX

I would like to pass a php variable onto another php page (category-get-secondary.php) through Ajax. I have the following code:
function getSecondaryCat(val) {
$.ajax({
type: "POST",
url: "category-get-secondary.php",
data: 'primary_cat='+val,
success: function(data){
$("#secondary_cat").html(data);
$("#tertiary_cat").html('<option value="">Select specific category</option>')
}
});
}
On category-get-secondary.php I want to get the value: -
$postPrimaryCat = $_POST['primary_cat'];
$categoryType = $_POST['category-select'];
$postPrimaryCat is transferred. Now I want to transfer the value for $categoryType.
I would like to pass the PHP variable 'category-select'. This is what I tried to transfer the value:
function getSecondaryCat(val,cat_val) {
$.ajax({
type: "POST",
url: "category-get-secondary.php",
data:'primary_cat='+val+'&category-select='+cat_val,
success: function(data){
$("#secondary_cat").html(data);
$("#tertiary_cat").html('<option value="">Select specific category</option>')
}
});
}
and to get the value I'm using
$getCategorySet = $_POST['category-select'];
but the value doesn't seem to be transfereed
Updated with full code:
main-page.php
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script>
</script>
<script>
function getSecondaryCat(val, catval) {
$.ajax({
type: "POST",
url: "category-get-secondary.php",
data:'primary_cat='+val+'&categoryselect='+catval,
success: function(data){
$("#secondary_cat").html(data);
$("#tertiary_cat").html('<option value="">Select specific category</option>')
}
});
}
function selectCountry(val) {
$("#search-box").val(val);
$("#suggesstion-box").hide();
}
</script>
<?php
//Get category set from URL bar
$_POST['categoryselect'] = 'premium';
category-get-secondary.php
<?php
//Insert value to ajax
$postCatType = $_POST['categoryselect'];
Valid Characters
In general JavaScript, variable/function names can't contain -. They can only contain letters, $, and _ (Underscore)
So... change data:'primary_cat='+val+'&category-select='+cat_val, to this data:'primary_cat='+val+'&category_select='+cat_val,
Hope it solves your issue.
function getSecondaryCat(val) {
$.ajax({
type: "POST",
url: "category-get-secondary.php",
data: {primary_cat:val},
success: function(data){
$("#secondary_cat").html(data);
$("#tertiary_cat").html('<option value="">Select specific category</option>')
}
});
}
Change data and add below data line in your code.
Ajax
function getSecondaryCat(val,cat_val) {
$.ajax({
type: "POST",
url: "category-get-secondary.php",
data:{primary_cat:val,category_select:cat_val} ,
success: function(data){
$("#secondary_cat").html(data);
$("#tertiary_cat").html('<option value="">Select specific category</option>')
}
});
}
PHP
$postPrimaryCat = $_POST['primary_cat'];
$categoryType = $_POST['category-select'];

refresh div after sending data to db

i have a div that shows the total sum of some products:
<div class="total-price"><?php echo (!empty($cart)) ? $cart['total'] : '0'; ?> $</div>
with ajax, i'm adding products to cart ... se the page is not reloading.
How to refresh the div after I add the product to cart?
The ajax that i'm using:
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
data: $(this).serialize(),
success: function () {
$(".success-message").slideDown().delay(5000).slideUp();
$(".total-price").something...;
}
});
})
</script>
Thank you!
You can do something like this:
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
data: $(this).serialize(),
success: function () {
$(".success-message").slideDown().delay(5000).slideUp();
var oldPrice = $('.total-price').text() * 1;
var itemPrice = "15"; //the price that should be added
$('.total-price').text(oldPrice + itemPrice);
}
});
})
</script>
You should be returning a total basket value from your /tdt/order path.
In the PHP script you should echo some JSON data with all the required information, for example
echo json_encode(array("totalPrice" => "£10.01"));
Then you need to parse this information into your Javascript and update the pages elements;
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
$(".success-message").slideDown().delay(5000).slideUp();
$('.total-price').val(data.totalPrice);
}
});
})
</script>
The above ajax request will expect the data returned to be JSON, you will then use this to update the total-price element.
You can use something like angularjs or knockoutjs - for angular you would update your model - for knockout you would use the self.object.push(value) i.e.,
function OrderViewModel() {
var self = this;
self.myOrder = ko.observableArray([]);
self.addOrderItem = function () {
$.ajax({
type: "post",
url: "yourURL",
data: $("#YOURFORMFIELDID").serialize(),
dataType: "json",
success: function (value) {
self.myOrder.push(value);
},
headers: {
'RequestVerificationToken': '#TokenHeaderValue()'
}
});
}
}
ko.applyBindings(new orderViewModel());
</script>
</pre>

AJAX POST: echoing posted anchor tag value

HTML/jQuery:
Friends
<script type="text/javascript">
$(document).ready(function() {
$('a#friends').click(function() {
$.ajax({
type: "POST",
url: "data.php",
data: $('#friends').html(),
success: function(data) {
$('#questions').html(data);
},
dataType: "HTML"
});
});
});
</script>
data.php:
<?php
echo $_POST['#friends'];
?>
How do I return this POST value of an id in an anchor tag? The variable is being passed to PHP because I can alert it, but the problem is getting it back.
You need to specify the name of the value you are sending across in your AJAX request. Try this:
$.ajax({
type: "POST",
url: "data.php",
data: { 'friends': $('#friends').html() }, // Note the value is sent in an object with a key of 'friends'
success: function(data) {
$('#questions').html(data);
},
dataType: "HTML"
});
<?php
echo $_POST['friends']; // retrieve the 'friends' value
?>
How you are passing the data to PHP,
please use the following code,
Friends
<script type="text/javascript">
$(document).ready(function() {
$('a#friends').click(function() {
$.ajax({
type: "POST",
url: "data.php",
data: {'friends' : $('#friends').html()},
success: function(data) {
$('#questions').html(data);
},
dataType: "HTML"
});
});
</script>
<?php
echo $_POST['friends'];
?>
Your syntax is wrong for passing friends value to data.php
Try this
$(document).ready(function() {
$('a#friends').click(function() {
$.ajax({
type: "POST",
url: "data.php",
data: "friends="+$('#friends').html(),
success: function(data) {
$('#questions').html(data);
},
dataType: "HTML"
});
});
<?php
echo $_POST['friends'];
?>
First of all you can't send data to the ajax page in this way
data: $('#friends').html(),
A more suitable way would be
data : {'key1':'val1', 'key2':'val2'}
Then on the php page, you can retrieve these values in this fashion
$key1 = $_POST['key1']; // will contain 'val1'
$key2= $_POST['key2']; // will contain 'val2'
alternatively you can use
Friends
<script type="text/javascript">
$(document).ready(function() {
$('a#friends').click(function() {
$.post("data.php",{
friends: $("#friends").html()
},function(data){
$("#questions").html($.trim(data)); // trim to be sure
});
});
});
</script>
and in the php:
<?php
echo $_POST['friends'];
?>
Pass the data variable in data field. For more info see below example
$(document).ready(function() {
$('a#friends').click(function() {
alert("");
$.ajax({
type: "POST",
url: "data.php",
data: "#friends="+$('#friends').html(),
success: function(data) {
alert(data);
$('#questions').html(data);
},
dataType: "HTML"
});
});
});

Categories