<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
Related
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",
I am using ajax, php and json to store click counts in json file...Let's say the file is this:
count.json
{"countbtn1":28,"countbtn2":25,"countbtn3":39}
downloadsCount.php
<?php
$buttonName=$_POST["buttonName"];
$file = "count.json";
$json = json_decode(file_get_contents($file), true);
echo $json['count'.$buttonName] ;
?>
downloads.php
<?php
$buttonName=$_POST["buttonName"];
$file = "downloads.json";
$json = json_decode(file_get_contents($file), true);
$json['count'.$buttonName] = $json['count'.$buttonName] + 1;
file_put_contents($file, json_encode($json));
echo 'success';
?>
And I need to place each btn value inside these on page load:
<div class='smallbtn1'>0</div>
<div class='smallbtn2'>0</div>
<div class='smallbtn3'>0</div>
Counting and updating the json file with this:
$('.download').click(function() {
//get name of button
var name= $(this).prop('name');
$.ajax({
url: "downloads.php",
data:{buttonName:name},
method: "POST",
success: function(response) {
if (response = 'success') {
//get count download
$.ajax({
url: "downloadsCount.php",
data:{buttonName:name},
method: "POST",
success: function(response){
$('.small'+name).html(response);
}
});
}
}
});
return true;
});
..and I tried updating the count on page load with this:
$.ajax({
url: "downloadsCount.php",
data:{buttonName:name},
method: "POST",
success: function(response){
$('.small'+name).html(response); }
});
});
...but it doesn't update the values on load, just after the first click.
PS: The whole thing IS wrapped in $(document).ready(function(){..});
After seeing the code on your server, I'd say the issue is how you are calling the AJAX. You are doing this:
$(document).ready(function(){
$.ajax({
url: "downloadsCount.php",
data:{buttonName:name},
method: "POST",
success: function(response){
$('.small'+name).html(response); }
});
});
But you don't have defined what name is (it is defined on the click event, but not when the page is loaded for the first time). You should do something like this:
$(".download").each(function() {
var name = $(this).attr("name");
$.ajax({
url: "downloadsCount.php",
data:{buttonName:name },
method: "POST",
success: function(response){
$('.small'+name).html(response);
}
});
});
So the AJAX is called for each one of the buttons, and you use the attribute name by doing $(this).attr("name").
Try sending the AJAX request after the page completely loads using $(document).ready():
$(document).ready(function() {
$.ajax({
url: "downloadsCount.php",
data: { buttonName:name },
async: false,
method: "POST",
success: function(response) {
$('.small' + name).html(response);
}
});
});
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>
I have a button within my HTML that, when you click it, I need to have it run a query in a PHP file which would then echo the results.
I've tried the following, however, when I click the button, it does nothing. What's wrong?
HTML/Ajax:
<?php
$reply_id = 15;
?>
<html>
<body>
<center><a class="btn show-more">Show more comments</a></center>
<div id="resultcomments"></div>
<script type="text/javascript">
var id = $reply_id;
$(document).ready(function() {
$(".show-more").click(function() {
$.ajax({
url: 'assets/misc/test.php',
type: "POST",
data: ({id_variable: id}),
function(data) {
$("#resultcomments").html(data);
}
});
});
});
</script>
</body>
</html>
PHP (located in assets/misc/test.php):
<?php
$replyid= $_POST['id_variable'];
echo $replyid;
// query would go here
?>
since $reply_id is PHP variable, for using it inside javascript you need to do like:
var id = <?php echo $reply_id; ?>;
....
and change:
data: ({id_variable: id})
to
data: {id_variable: id}
like:
$.ajax({
url: 'assets/misc/test.php',
type: "POST",
data: {id_variable: id},
success: function(data) {
$("#resultcomments").html(data);
}
});
You're not assigning your AJAX success function to a key, so I don't think it's ever firing. (You could try a console.log() or a debugger to check.) Try this instead:
$.ajax({
url: 'assets/misc/test.php',
type: "POST",
data: {id_variable: id}
}).done(function (data) {
$("#resultcomments").html(data);
});
Try this in javascript
var id = <?php echo $reply_id; ?>;
No brackets needed for data attribute in ajax,
data: {id_variable: id},
Try this for data attribute
<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>