AJAX GET function using hyperlink? - php

I'm trying to use AJAX GET function in my code instead of POST.
i have a few hyperlinks which look like this:
<a class=netro" href="mypage.php?search=dog"></a>
<a class=netro" href="mypage.php?search=cats"></a>
<a class=netro" href="mypage.php?search=donkey"></a>
<a class=netro" href="mypage.php?search=apples"></a>
and in mypage.php I have this:
if (isset($_GET['search'])) {
$search = $_GET['search'];
////rest of my code////
}
without AJAX, the page page works fine and it gets the results bases on $search properly.
but with AJAX, i get nothing back in response that I get from AJAX.
this is my ajax code:
$(document).ready(function() {
$(function() {
$('.netro').click(function(event) {
event.preventDefault();
var urlssg = "mypage.php"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: urlssg,
dataType: "html", //expect html to be returned
success: function (response) {
$("#col1").html(response);
//alert('sent');
}
});
});
});
});
could someone please advise on this issue?
Thanks in advance,

You need to provide the search parameter along with the request. Try this:
$(document).ready(function() {
$('.netro').click(function(event) {
event.preventDefault();
var $a = $(this);
$.ajax({
type: "GET",
url: $a.attr('href'), // note that this will include the querystring param
dataType: "html", //expect html to be returned
success: function (response) {
$("#col1").html(response);
}
});
});
});

Here is a clean, simple approach:
HTML
<a class="netro" id="dog">Dog</a>
<a class="netro" id="cats">Cat</a>
<a class="netro" id="donkey">Donkey</a>
<a class="netro" id="apples">Apples</a>
JS/JQUERY
$(function() {
$(".netro").click(function(e) {
e.preventDefault();
var sId = $(this).attr("id");
$.ajax({
type: "GET",
url: "mypage.php?search="+sId ,
data: { search: search_id },
dataType: "html",
success: function (data) {
//Do something with the response data....
}
});
});
});

Related

Jquery simple Ajax Post PHP not working

I have a simple code but is not working. I want to create a more complex function but I just need the basic structure.
HTML
<span class="cleanreport">Delete Record</span>
Javascript:
$( ".cleanreport" ).click(function() {
var token = "test";
$.ajax({
data: {"data": token},
type: "post",
url: "clean.php",
success: function (data) {
console.log(data);
$('.test').html(data);
}
});
});
PHP clean.php
$data = $_POST['data'];
echo $data;
What I am doing wrong?
This should work for you:
var token = "test";
$.ajax({
type: 'POST',
url: "clean.php",
data: {id: token},
dataType: "json",
success: function(response) {
// some debug could be here
},
error: function(a,b,c) {
// some debug could be here
}
});
If not, please debug success and error parameters using console.log().
Based on jquery documentation setting type is an alias for method so this could not be a problem in you case for sure.
$( ".cleanreport" ).click(function() {
var token = "test";
$.post('clean.php",
{
data: token
},
function (data,status) {
//console.log(data);
$('.test').html(data);
});
});

Get the content of json file on page load

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);
}
});
});

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>

auto load data from database using jquery

I would like to display newly inserted data from database. I found the below code from another question and it does what I want but it only shows the data when clicked. So can someone tell me how can I make the data auto load every 5 secs?
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "second.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
//alert(response);
}
});
});
});
</script>
<input type="button" id="display" value="Display All Data" />
<div id="responsecontainer" align="center">
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "second.php",
dataType: "html", //expect html to be returned
success: function (response) {
$("#responsecontainer").html(response);
setTimeout(load, 5000)
}
});
}
load(); //if you don't want the click
$("#display").click(load); //if you want to start the display on click
});
Try to add setTimeout:
success: function(response){
$("#responsecontainer").html(response);
setTimeout(success, 5000);
}
You can use function setTimeout as a timer to trigger. For detail, please look at below code:
$(document).ready(function() {
loadData();
});
var loadData = function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "second.php",
dataType: "html", //expect html to be returned
success: function(response){
$("#responsecontainer").html(response);
setTimeout(loadData, 5000);
}
});
};
You may use jquery's setInterval() or setTimeout() inside onload();
refer to the following questions, its answer explains well what you need exactly.
Calling a function every 60 seconds

How can I get data after click on text with AJAX jquery?

I used this code for sending and returning result.
<script type="text/javascript">
$(document).ready(function() {
$('.special').click(function(){
var info = $(this).attr("rel");
//$(this).html(sku);
$.ajax({
type: "POST",
url:"../ajax/addSpecialFlag.php",
async: false,
data: {info:info},
success:function(result){
$(this).html(result);
}});
});
});
</script>
<b style="cursor: pointer" class="special" rel="<?=$v['number']."/*".$v['vid']; ?>">Special</b>
addSpecialFlag.php
<?php
echo $_POST['info'];
?>
This code should return "Info" in "<-b class='special' ->" but no returning result. Where is the problem ? Thanks in advance !
The problem should be that $(this) inside your success-handler is not the same as outside of the handler. Doing it like this should solve your problem:
$(document).ready(function() {
$('.special').click(function(){
var $this = $(this);
var info = $this.attr("rel");
$.ajax({
type: "POST",
url:"../ajax/addSpecialFlag.php",
async: false,
data: {info:info},
success:function(result){
$this.html(result);
}});
});
});
<b>? Umad? Please use <strong>.
I have tidied your code so the paranthesis match their line indents and adjusted your success handler. The issue was the success handler is in a different scope to the click function scope so you needed to refer to it in another way, i.e. by assigning it to another variable.
$(document).ready(function () {
$('.special').click(function () {
var info = $(this).attr("rel");
var _this = $(this);
//$(this).html(sku);
$.ajax({
type: "POST",
url: "../ajax/addSpecialFlag.php",
async: false,
data: {
info: info
},
success: function (result) {
_this.html(result);
}
});
});
});

Categories