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);
}
});
});
Related
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>
Simply I would like to load data from two php page using jquery. I put the below code together, however only the one works not both. Any ideas?
$(document).ready(function() {
loadData();
});
var loadData = function() {
$.ajax({
type: "GET",
url: "second.php",
dataType: "html",
success: function(response){
$(".hm_m_un").html(response);
setTimeout(loadData, 1000);
}
});
};
$(document).ready(function() {
loadData();
});
var loadData = function() {
$.ajax({
type: "GET",
url: "test.php",
dataType: "html",
success: function(response){
$(".rx").html(response);
setTimeout(loadData, 1000);
}
});
};
You're overriding your first loadData variable with the second one. Give it a different name and you'll be fine.
As a note, you don't need to call $(document).ready() twice, you can technically call it once. I would write this as something like:
function descriptiveFunctionName() {
$.ajax({
type: "GET",
url: "second.php",
dataType: "html",
success: function(response){
$(".hm_m_un").html(response);
setTimeout(loadData, 1000);
}
});
}
function anotherDescriptiveFunctionName() {
$.ajax({
type: "GET",
url: "test.php",
dataType: "html",
success: function(response){
$(".rx").html(response);
setTimeout(loadData, 1000);
}
});
}
$(document).ready(function() {
descriptiveFunctionName();
anotherDescriptiveFunctionName();
});
Please note though this was a very lazy answer, user Machavity's code is much better for reuse, although you may want to just use a callback sent to loadData for more flexibility in the future.
You've named them all the same. Try some consolidation
$(document).ready(function() {
window.setInterval(function() { loadData('second.php', $('.hm_m_un')); }, 1000);
window.setInterval(function() { loadData('test.php', $(".rx")); }, 1000);
});
var loadData = function(page, ele) {
$.ajax({
type: "GET",
url: page,
dataType: "html",
success: function(response){
ele.html(response);
}
});
};
Very simple....you declared a variable loadData and assigned it to a function.
You then used same variable to assign to another function, thereby wiping out first instance. Use different variable names
hi i want to send javascript data via ajax to the same page in wordpress. Cannot fetch the data in testajax.php page. its shows Undefined index: name. And how to send the data on same php page rather than testajax.php ?
<script>
jQuery.ajax({
type: "POST",
url: 'http://localhost/projects/xxx/wordpress/wp-content/themes/xxx/testajax.php',
data: {name:'foo'},
success: function(data)
{
alert('success');
}
});
var foo = 'somename';
jQuery.ajax({
url:'yourUrl',
type: "POST",
data: {'name':foo},
success: function(data)
{
alert('success');
}
});
php
<?php
if(isset($_POST['name'])){
//Do whatever you want
}else{
//Do whatever you want
}
?>
jQuery.ajax({
url: "./_FILE_" // ./index.php for example
type: "POST",
data: {name:'foo'},
success: function(data)
{
alert('success');
}
});
I am trying to send data to my PHP script to handle some stuff and generate some items.
$.ajax({
type: "POST",
url: "test.php",
data: "album="+ this.title,
success: function(response) {
content.html(response);
}
});
In my PHP file I try to retrieve the album name. Though when I validate it, I created an alert to show what the albumname is I get nothing, I try to get the album name by $albumname = $_GET['album'];
Though it will say undefined :/
You are sending a POST AJAX request so use $albumname = $_POST['album']; on your server to fetch the value. Also I would recommend you writing the request like this in order to ensure proper encoding:
$.ajax({
type: 'POST',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});
or in its shorter form:
$.post('test.php', { album: this.title }, function() {
content.html(response);
});
and if you wanted to use a GET request:
$.ajax({
type: 'GET',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});
or in its shorter form:
$.get('test.php', { album: this.title }, function() {
content.html(response);
});
and now on your server you wil be able to use $albumname = $_GET['album'];. Be careful though with AJAX GET requests as they might be cached by some browsers. To avoid caching them you could set the cache: false setting.
Try sending the data like this:
var data = {};
data.album = this.title;
Then you can access it like
$_POST['album']
Notice not a 'GET'
You can also use bellow code for pass data using ajax.
var dataString = "album" + title;
$.ajax({
type: 'POST',
url: 'test.php',
data: dataString,
success: function(response) {
content.html(response);
}
});
$.ajax({
type: 'POST',
url: 'test.php',
data: { album: this.title },
success: function(response) {
content.html(response);
}
});
hi i want to submit the page through following code but i can't get post data on ajax.php
please tell me where i am wrong
new Ajax(wgScriptPath +'/' + 'ajax.php', {
method: 'post',
data:{items:item},
onComplete: function(res)
{
////Code
}
to keep it simple and fast you can use open source jquery.
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
check links below
- http://api.jquery.com/category/ajax/
http://api.jquery.com/jQuery.post/
example
<script>
$(document).ready(function() {
$('#checkbox').click(function() {
$.ajax({type : "POST",
url : "test.php",
data : "ffs=somedata&ffs2=somedata2",
success : function() {
alert("something");
}
});
});
});
</script>
<body>
<input type = "checkbox" name = "checkbox" id = "checkbox">
</body>
Mention the framework you are using, assuming you are using prototype, try below code
new Ajax(wgScriptPath +'/' + 'ajax.php', {
method: 'post',
parameters:{items:item},
onComplete: function(res)
{
////Code
}
});