I am trying to implement "ADD TO SHORTLIST" via php/ajax
Here's my relevant codes
Calling ajax from this page :
<a id="shortlist" class="pull-right add-to-shortlist">Add to shortlist</a>
<p id="cookieShortList"><?=$_COOKIE['shortlist_count']?></p>
<script>
$("#shortlist").click(function(){
$.ajax({
type: "post",
url: "ajaxcall.php",
data:{spId : "111",prId : "222"},
success: function(result)
{
$('#cookieShortList').html(result);
}
});
});
</script>
POST DATA page:
$s_id = $_REQUEST['spId'];
$product_id = $_REQUEST['prId'];
setcookie("cookie_product[$s_id]", $product_id, time()+ (30),'/');
echo $shortlist_count_c = count($_COOKIE['cookie_product']);
if (isset($_COOKIE['cookie_product'][$s_id])) {
echo "blah blah";
}
setcookie("shortlist_count", $shortlist_count_c, time()+ (30),'/');
The problem is I can see that cookie is being set on my browser under resources tab as "cookie_product[111]" => "222" on first click on "add to shortlist" but the count gets updated only after second click on "add to shortlist".
Read documentation
Once the cookies have been set, they can be accessed on the next page load with the $_COOKIE array.
Try this:
$shortlist_count_c = count($_COOKIE['cookie_product']) + 1;
Related
I am trying to implement "to favourite" feature for my website.
User can visit whole website without login, but if they want to mark their favourite out of some results they need to login.
I'm clear with the login of add to favourite feature, now only problem is, as I said user don't need to login when they land on website but if they clicked on an "add to favourite" button it should check for login status (I know they are not logged in initially) then bootstrap modal should appear with social login (real problem).
So how I could present login page in modal if he is not logged in?
My code is:
<button class='btn btn-sm btn-info favourite_feature' value="<?php echo $id;?>">favourite</button>
$(document).ready(function()
{
$(".favourite_feature").click(function(){
var _this = $(this);
var postid = _this.val();
$.ajax({
type : 'POST',
url : '/add_favourite.php',
dataType : 'json',
data : '$postid='+ postid,
});
});
});
Basically it's your back-end's responsibility to check whether the user is logged in or not, when receiving a request for "add to favourite" action.
When JS posts data to the server, it should respond accordingly (whether the operation was successful or not and what was the problem).
Suppose the backend "add to favourite" action responds with this json, when user is not logged in:
{
"success" : 0,
"error_type" : "login"
}
... and this json when action was performed with no errors:
{
"success" : 1
}
That way your server informs JavaScript that the user should log in. Then you can handle above response accordingly (in my example the element with id loginModal is the modal to show):
$(document).ready(function()
{
$(".favourite_feature").click(function(){
var _this = $(this);
var postid = _this.val();
$.ajax({
type : 'POST',
url : '/add_favourite.php',
dataType : 'json',
data : '$postid='+ postid,
success : function(response) {
if (response.success) {
// if add to favourite succeeded
}
else {
// handle errors
if (response.error_type == 'login') {
// if user should log in - show modal (example jQuery)
$('#loginModal').modal('show');
}
}
}
});
});
});
I have an AJAX call to the create_pdf.php page:
$('body').on('click', '.PrintButtonWithClass', function (event) {
var1 = $('#id1').val();
var2 = $('#id2').val();
dataString='var1='+var1+'&var2='+var2+'&pdf_name=PdfName&pdf_creator=myname';
$.ajax({
type: 'post',
url: '/path/to/createpdf/file/create_pdf.php',
data: dataString,
success: function (data) {
alert('success');
}
});
});
In create_pdf.php I tried to use this line to download the file:
$pdf->Output(str_replace(' ','_',utf8_decode($_POST['pdf_name'])).'.pdf', 'D');
I tried also the FD and I parameters with no success, the file does not get downloaded.
How can I force downloading the file created without saving it to the webserver and without redirecting user to any other page? I want him to stay on the same page, and that the browser pops up a (download or preview dialog box) for the PDF. Is there any way to do it?
EDIT : create_pdf.php is Waiting for POST variables. and uses them to create the HMTL for the pdf.
You can try to submit the form to a new window( like a popup ):
<form method="post" id="myform" action="your_url">
<input name="param1">
</form>
And in javascript
// create popup window
var wind = window.open('about:blank', '__foo', 'width=700,height=500,status=yes,resizable=yes,scrollbars=yes');
// submit form to popup window
$("#myform").attr("target", "__foo");
Do not forget to send content-type header from php:
header("Content-Type", "application/pdf");
Edit:
Browsers should display your pdf content and also show download or print options.
The code is not tested but I think it would do what you requested;
I found a work-around for my problem.
I did an AJAX call inside another AJAX call.
the first AJAX call creates the file on webServer and opens the file in a new Window.
In his success parameter I do the following:
The second AJAX call that deletes the file from Server.
$.ajax({
type: 'post',
url: '/path/to/create_pdf.php',
data: dataString,
success: function (data) {
window.open(
data,
'_blank' // <- This is what makes it open in a new window.
);
window.setTimeout(function () {
dataString2 = 'Downloaded=true';
$.ajax({
type: 'post',
url: '/path/to/create_pdf.php',
data: dataString2,
success: function (data) { alert(data); }, // handler if second request succeeds
});
}, 5000);
},
});
Using this answer to my similar request : send a csv file from php to browser
I needed to (1) get and display a pdf in another window; and
(2) get a CSV file and prompt for saving.
I have 2 simple buttons on the page (http://potoococha.net/) for each. Here is the code:
function getCSVText(evt) {
if (currentChecklistCountry) {
var form = $('<form method="post" action="../php/sendCSV.php?country=' + currentChecklistCountry + '"></form>');
$('body').append(form);
form.submit();
form.remove();
}
else checklistCountryButton.classList.add("needsAttention");
}
function openChecklistPage() {
if (!currentChecklistCountry) {
checklistCountryButton.innerHTML = "Select Country";
checklistCountryButton.classList.add("needsAttention");
return;
}
if (gNumDays == undefined) gNumDays = 12;
vars = "?country=" + currentChecklistCountry;
vars += "&num_days=" + gNumDays;
vars += "&line_nos=" + lineNumbers.checked;
vars += "&left_check=" + leftCheck.checked;
vars += "&endemics=" + showEndemics.checked;
vars += "&sci_names=" + !sciNames.checked;
vars += "&italics=" + !italics.checked;
window.open( '../php/makePDF.php' + vars, '_blank' );
}
So the getCSVText() methods downloads a file using a temporary form appended and then immediately removed, and openChecklistPage() successfully opens another browser window with a pdf file. The pdf file is never saved on the server. The CSV file is already stored there and just retrieved. Perhaps you can modify the code for your purposes.
I have a DIV which contains how many likes fetching from Mysql database.
I click on button which says like and it will go through ajax function like(id1) with parameter.
Ajax use page likes.php and does all job adding to database. And it gives out JSON data as feedback with code zero if successful. And one if fails.
In success section ajax _js.code is one then its already liked. Thus shows us message. But my problem is I cannot refresh DIV likes when code is zero which is success. It either goes to top of the page instead of staying at DIV likes.
For information it also appends hash TAG at the end of URL.
Button line, I want like button which should work as facebook or other major app does. Without moving page on top. And update like button immediately when clicked.
My main page
<input type="checkbox" id="like" onclick="like(<?php echo $_SESSION["id"];?>);"/>
<div id="likes">
<?php
$like = 0;
$conditions = "WHERE id = $_SESSION[id]";
echo $total = $ll->get_likes($conditions); //displaying how many likes
?>
</div>
Ajax
<script>
function like(id1) {
$.ajax ({
type: "POST",
url: "likes.php",
data: {id: id1 },
success: function(feedback) {
var _js = jQuery.parseJSON(feedback);
$("#likes").html(_js.message); //printing message here
$("#likes").attr("class", ""); //resetting class of CSS
if( _js.code == 0) {
/**I want to refresh DIV likes after this **/
} else {
$("#likes").addClass("red"); //This is working fine, i get message when already liked
}
}
});
}
likes.php
<?php
if ( isset($_POST)) {
//All PHP staff goes here and its working
if ( $success) {
$return = array (
'code' = 0,
'message' = ""
);
} else {
$return["code"] = 1;
$return["message"] = "You already liked";
}
echo json_encode($return);//Converting PHP into JSON format
}
?>
change following in HTML and JS
<input type="checkbox" id="like" onclick="return like(<?php echo $_SESSION["id"];?>);"/>
<script>
function like(id1) {
$.ajax ({
type: "POST",
url: "likes.php",
data: {id: id1 },
success: function(feedback) {
var _js = jQuery.parseJSON(feedback);
$("#likes").html(_js.message); //printing message here
$("#likes").attr("class", ""); //resetting class of CSS
if( _js.code == 0) {
/**I want to refresh DIV likes after this **/
} else {
$("#likes").addClass("red"); //This is working fine, i get message when already liked
}
}
});
return false;
}
#tashi,
There is a syntax error in likes.php. Use => operator when declaring arrays. The code should be as follows.
$return = array (
'code' => 0,
'message' => ""
);
if you want to display no of likes on success the change your code as follows
In likes.php
<?php
if ( isset($_POST)) {
//All PHP staff goes here and its working
if ( $success) {
$return = array (
'code' => 0,
'message' => "",
'likes_count' => $likes_count //get updated likes count from db
);
} else {
$return["code"] = 1;
$return["message"] = "You already liked";
//here you do not need to send the like count
}
echo json_encode($return);//Converting PHP into JSON format
}
?>
javascript code
function like(id1) {
$.ajax ({
type: "POST",
url: "likes.php",
data: {id: id1 },
success: function(feedback) {
var _js = jQuery.parseJSON(feedback);
$("#likes").html(_js.message); //printing message here
$("#likes").attr("class", ""); //resetting class of CSS
if( _js.code == 0) {
/**I want to refresh DIV likes after this **/
$('#likes').html(_js.likes_count);//this will update your likes count
} else {
$("#likes").addClass("red"); //This is working fine, i get message when already liked
}
}
});
}
I am quite new to jQuery and AJAX.
I am sending the request via AJAX to check file 'test' every 5 seconds which works fine. 'test' stands for test.php file.
<script>
$(document).ready(function () {
function load() {
var test = "<?php echo $test; ?>/";
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: test,
dataType: "html", //expect html to be returned
contentType: "text/html",
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
});
</script>
<div id="responsecontainer"></div>
test.php
$id = $this->session->userdata('UserID');
$get_friends_notification = $this->friends_model->get_friends_alert_by_ID($id);
if(isset($get_friends_notification) && !empty($get_friends_notification))
{
?>
<div id="test" style="width:200px; height:auto; border:1px solid red;">
<h3>Friend invitation from:</h3>
<?php
foreach($get_friends_notification as $key => $value)
{
$new_id = $get_friends_notification[$key] = $value["FrieInviter"];
$new_name = $get_friends_notification[$key] = $value["UserName"];
echo ''.$new_name.'<br />';
}
?>
</div>
<?php
}
Then it just displays it in the div # responsecontainer which works fine too.
$("#responsecontainer").html(response);
In the file 'test' I am checking database if there were any updates.
So I am pulling the information from DB and return to #responsecontainer. As it runs every 5 seconds, after it ran for the first time I would like to grab the last ID that I pulled and before it runs again and save it in variable and then I would like to pass that ID to the 'test' or process it differently. Basically I want to be able to use it. How can I do that??
EXAMPLE:
ajax checks test.php file and find 5 rows. returns these 5 rows with 5 IDs. The last ID is number 5. In the meantime there were some other rows inserted so next time it will find more rows.
Before it checkes again I want to tell it to not to check ID 1,2,3,4,5 but start from ID 6.
Also how does this method works with DB connections? Assuming that I have for example 500 users, and on all of theirs profiles that check would run every 5 seconds wouldnt it kill database connections?
Basically you need to add a pgination effect in here. Pass a parameter in the ajax request for example : if you are getting 5 records at a time,
then initialize a variable say
current_page = 0 , increment the same as you request via ajax
var current_page=0;
function load() {
var test = "<?php echo $test; ?>/";
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: test,
data : current_page
dataType: "html", //expect html to be returned
contentType: "text/html",
success: function (response) {
if(response.length!==0){
$("#responsecontainer").html(response);
current_page+=1;
}
setTimeout(load, 5000)
}
});
}
in the php page make the necessary changes (hope you know how pagination is done).
I have this "Read More" link:
echo '<p>'.$readNewsResult['content'].'<a class="test" href="#fancybox'.$readNewsResult['id_news'].'">Read More</a></p>';
When I click in this link, my goal is to update views column of my news table.
So I have a jQuery where Im passing id of my news, and it is working fine, when I click on "Read more" link I get an alert message saying: "action=update&update=311", where 311 is id of my clicked news.
My jQuery until now:
$(function(){
var read = $('.news');
read.on('click','.test',function(){
var updateid = $(this).attr("id");
var updatedata = "action=update&update="+updateid;
alert(updatedata);
$.ajax({
data: updatedata,
beforesend: '',
error: '',
success: function(updateR)
{
alert(updateR);
}
});
});
});
But now with php, Im trying to get update action and id, and do update on my news table, but its not working, because it seems that I never enter in my switch condition.
I tried to give some "echos" inside my case, and when I click on my "Read more" link my echo never appears.
Do you see where might be the problem??
$action = $_POST['action'];
switch($action)
{
case 'update':
$id = $_POST['id'];
$updateViews = $pdo->prepare("UPDATE news SET views=:views WHERE id=:id");
$updateViews->bindValue(':views', '1');
$updateViews->bindValue(':id', $id);
$updateViews->execute();
break;
}
At the very least you are trying to work with $_POST['id'] in your PHP but you are actually creating an URL parameter called update which contains the ID in your JavaScript.
The actual issue is that you are lacking an URL argument to your $.ajax call.
You are also naming your var udpdatedata on this line:
var udpdatedata = "action=update&update="+updateid;
but are referencing updatedata in the $.ajax call:
data: updatedata,
As such your query parameters are never added to the non-existent URL.
An extra one:
sucess: function(updateR)
Is actually spelled success, note the double c.
Where is your ajax controller url, I mean url and also type of call type,
$.ajax({
type: 'POST',
url: '/url/myphpfunction',
data: updatedata,
beforesend: '',
error: '',
sucess: function(updateR)
{
alert(updateR);
}
});
Here is the tutorial http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php
You had a few things wrong with your ajax function. The first was that you should be passing through an object of values instead of a string. Then you need to specify a method of getting to your script. Then you need to set the URL to your script. See the comments below:
$(function(){
var read = $('.news');
read.on('click','.test',function(){
var updateid = $(this).attr("id");
// pass data as a JS object
var udpdatedata = {action:'update', update:updateid};
alert(udpdatedata);
$.ajax({
// set the method to post
type: "POST",
// the URL to your PHP script
url: "pathtoscript/script.php"
data: updatedata,
beforesend: '',
error: '',
success: function(updateR)
{
alert(updateR);
}
});
});
});
Your PHP also had an error, you're passing through 'update', not 'id':
$action = $_POST['action'];
switch($action)
{
case 'update':
// you're passing through 'update', not 'id'
$id = $_POST['update'];
$updateViews = $pdo->prepare("UPDATE news SET views=:views WHERE id=:id");
$updateViews->bindValue(':views', '1');
$updateViews->bindValue(':id', $id);
$updateViews->execute();
break;
}