I am trying to make a like button on a page and cant seem to get it to work right. Basically there are three function that use ajax to send the data to a php page that updates the database. Ive checked the db and all three update correctly. If the user doesnt originally like and clicks, it correctly shows the unlike button but then, if you click unlike it doesnt switch back (although it does update the database).
Is this the correct way to set this up? Im pretty new to ajax and am not sure if this is the right approach. THanks in advance
Steve
public function likesScript($p){?>
<script>
//display list of people who like this
function getLikes(){
$.ajax({
type: "POST",
url: "likelist.php",
data: { p: "<?php echo $_GET['p']?>"}
}).success(function(res) {
//check to see if current user likes this
if($('li#<?PHP echo $_SESSION['userId']; ?>').length){
$(".Like").addClass('hidden');
$(".UnLike").removeClass('hidden');
}
else{
$(".UnLike").addClass('hidden');
$(".Like").removeClass('hidden');
}
$("#likedBy").append(res);
console.log(res);
});
}
function removeLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "0" }
})
getLikes();
return false;
}
function addLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "1" }
})
getLikes();
return false;
}
$(document).ready(function() { getLikes();
$(".UnLike").live('click',removeLike);
$(".Like").live('click',addLike);
});
</script>
likelist.php:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/view.class.php';
$view = new view();
include $_SERVER['DOCUMENT_ROOT'].'/profile.class.php';
include $_SERVER['DOCUMENT_ROOT'].'/init.php';
$profile = new profile($dbh);
if(isset($_POST)){
$p = $_POST['p'];
$view->printLikes($profile->getLikes($p));
}
likedata.php:
<?php
include $_SERVER['DOCUMENT_ROOT'].'/profile.class.php';
include $_SERVER['DOCUMENT_ROOT'].'/init.php';
$profile = new profile($dbh);
if(isset($_POST)){
$liker = $_POST['arg1'];
$likee = $_POST['arg2'];
$likeYesNo = $_POST['arg3'];
$profile->insertLikes($liker, $likee, $likeYesNo);
}
?>
AJAX is ayshcronous so the getLikes functions will fire before the AJAX is completed in both addLike and removeLike. You definitely need to put getLikes into the success callback of $.ajax so it doesn't retrieve data that may not have been updated
function addLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "1" },
success: getLikes
})
}
Ok... this is what I have learned from using ajax repeat calls...
IE hates them and sometimes they just don't work the way they should.
Try this
function addLike() {
var randnum = Math.floor(Math.random()*1001); //Add This Here on all Ajax Calls
$.ajax({
type: "POST",
url: "likedata.php",
cache: false, //Add This Here - Assists in helping Browsers not to cache the Ajax call
data: yourdata + '&random=' + randnum, // Add this to the end of your data you are passing along *'&random=' + randnum,*
success: function() {
getLikes();
}
})
}
Adding a random piece of data causes the browsers to think its a new call.
Also, the random=randnum wont effect anything on the php side.
Related
I believe I have the right syntax but am missing something important. Been searching on here for a while but can't figure out why the POST variable is not being detected. Basically my .ajax is firing because my test statement has been changing due to the value but some reason can't receive variable via $_POST (i.e. my echo in php echo that it is not firing) Also the native file and php that I am sending it to are the same file blankFormTemplate.php but don't think that should be an issue.
$(document).ready(function()
{
var $selectedContexts = [];
$('.allContextField').change(function(){
//alert($(this).val());
hideField = $(this).val();
$('#'+hideField).remove();
$.ajax
({
type: "POST",
url: "blankFormTemplate.php",
data: addedContext=hideField,
cache: false,
success: function(addedContext)
{
$('#test').html($('#test').html()+hideField);
}
});
});
});
in my PHP blankFormTemplate.php:
<?php
if(isset($_POST['addedContext']))
{
echo 'hello';
}
else
{
echo 'why';
}
?>
Any help would be greatly appreciated.
Thanks,
Your javascript
$(document).ready(function()
{
$('.allContextField').change(function(){
hideField = $(this).val();
$('#'+hideField).remove();
});
if (hideField.trim()) {
$.ajax
({
type: "POST",
url: "blankFormTemplate.php",
data: (addedContext:hideField},
cache: false,
success: function(msg)
{
$('#test').html(msg);
}
});
}
});
Your PHP
<?php
if(isset($_POST['addedContext']))
{
echo 'hello';
}
else
{
echo 'why';
}
?>
I am using AJAX to load content from mysql database when I CLICK on LINKS.
once I load the content successfully, I refresh the container every 5 seconds so the new content will be displayed.
the content gets loaded fine and the refresh part works fine too.
but the issue that I have is that when the refresh happens, the loaded content gets lost.
by "it gets lost" i mean that it will display the LAST result from the mysql database.
so, to help you understand the situation I will explain it further:
Lets say I have 3 results stored in mysql database.
I create <a></a> from each result in mysql using PHP. i am doing this without any issue.
I click on the link 2. (works fine)
the content of the link 2 will load on the page using AJAX. (works fine)
The container of content will refresh every 5 seconds. (works fine)
(THIS IS WHERE THE PROBLEM STARTS) once the refresh happens, the content of link 3 will be displayed even though I haven't clicked on the link 3!
so basically, for some strange reason, the content of the last Link or last mysql result will be displayed at all time which is un-wanted. I need to load the content of the CLICKED link and make it stay until another Link is clicked.
I hope I haven't confused you. :)
here is my html code:
<div id="chattercontent" style="width:90%; height:150px; resize:none; border:solid 1px #ccc; background:#F2EDF0; overflow:scroll; text-align:left;"></div>
<script type="text/javascript">
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "file.php?u_id=<?php echo $u_id; ?>",
dataType: "html", //expect html to be returned
success: function (response) {
$("#chattercontent").html(response);
setTimeout(load, 5000)
}
});
}
load();
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$(".list-group-item").click(function(e) {
e.preventDefault();
$("#chattercontent").load(this.href);
return false;
});
});
</script>
and PHP code for the links:
while (mysqli_stmt_fetch($stmt)) {
$product_list .= "<a id='listc' class='list-group-item' href='file.php?u_id=".$u_id."' >".$u_id." ".$date_added." <img src='light-red-flash.gif' width='20' /></a>";
}
}
any help would be appreciated.
Thanks
edit:
this is the code for file.php
<?php
session_start();
if (isset($_GET['u_id'])) {
$u_id = $_GET['u_id'];
$sql = "SELECT * FROM chat WHERE u_id='$u_id' ";
$query = mysqli_query($db_conx, $sql);
$productCount = mysqli_num_rows($query); // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$user_message = $row["user_message"];
}
} else {
echo "Sorry, there was an error.";
exit();
}
echo $user_message;
}
?>
as I mentioned before, the file.php returns the result properly according to the link that have been clicked on but then it will JUMP on the last result after each refresh!
You need to keep track of the current url the user has selected:
$(document).ready(function () {
//set url 1st time
var currentUrl = "file.php?u_id=<?php echo $u_id; ?>";
//variable to reference the timeout
var timer;
function load(url) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: url,
dataType: "html", //expect html to be returned
success: function (response) {
$("#chattercontent").html(response);
timer = setTimeout(function(){
load(currentUrl);
}, 5000);
}
});
}
load(currentUrl);
$(".list-group-item").click(function(e) {
e.preventDefault();
//update url on click
currentUrl = this.href;
//cancel existing timer
clearTimeout(timer);
load(currentUrl);
});
});
You aren't loading your dynamic content with the javascript function. Check out the following, hope it will fix your problem.
function load(href) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: href,
//url: "file.php?u_id=<?php echo $u_id; ?>", <-- NON DYNAMIC CONTENT
dataType: "html", //expect html to be returned
success: function (response) {
$("#chattercontent").html(response);
setTimeout(function() {
load(href);
}, 5000)
}
});
}
var _currentUrl;
function load(href) {
if (!href) {
href = _currentUrl;
}
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: href,
//url: "file.php?u_id=<?php echo $u_id; ?>", <-- NON DYNAMIC CONTENT
dataType: "html", //expect html to be returned
success: function (response) {
$("#chattercontent").html(response);
setTimeout(load, 5000)
}
});
_currentUrl = href;
}
I am a bit confused. I would be glad if you would explain it a bit more with some examples.
Anyway from what I could get from your text is that, the previous result is being overwritten.
In order to stop that, as we do while making a chatbox, you need to add the response "after" the previous result as in -
<script type="text/javascript">
/* A variable to hold the last response */
var lastResponse = "";
$(document).ready(function () {
function load() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "file.php?u_id=<?php echo $u_id; ?>",
dataType: "html", //expect html to be returned
success: function (response) {
/* Check if it is the same response or not */
if (lastResponse != response)
{
/* Save the last response */
lastResponse = response;
/* Add content after the previous */
$("#chattercontent").html($("#chattercontent").html()+response);
}
setTimeout(load, 5000)
}
});
}
load();
});
</script>
I created an Ajax navigation system but I've an issue when I want to send a variable.
I've an index.php like this
<script src="navigation.js" type="text/javascript"></script>
<div id="pageContent"></div>
page1
profile
This is navigation.js
$(document).ready(function(){
checkURL();
$('a').click(function (e){
checkURL(this.hash);
});
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#','');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
}
}
});
}
And this is the load_page.php page:
<?php
if(!$_POST['page']) die("0");
$page = $_POST['page'];
include('pages/'.$page.'.php');
?>
This is the issue: when I load profile.php page I want to see values by GET... example:
<?php
$nome_utente = $_GET['user'];
if(!$_GET['user']) {
print 'Attention! You have to insert a username';
}
else
{
print $nome_utente;
}
?>
To do this I tried to change the link in index.php
profile
But this doesn't work because load_page.php doesn't find the "profile?user=test.php" page.
What do I have to do to send a GET variable at profile.php, from a link in index.php?
I've to edit JS or PHP code?
Mixing get/post variables is considered poor practice, but is easily done:
function loadPage(url) {
url=url.replace('#','');
$.ajax({
type: "POST",
url: "load_page.php?user=whatever_you_want_here",
^^^^^^^^^^^^^^^^^^^^^^^^^^^^---your 'get' query
The other optiont would be to add the 'user' parameter to your ajax data line:
data: { page: url, user: whatever_you_want_here }
The first one would make 'user' available in $_GET, the second one would make it available in $_POST.
I've created one Ajax function like this:
function searchPlanAjax(url){
jQuery('#loader').css('display','block');
var plan = jQuery('.rad').val();
var site = url+"fbilling_details/subscription";
jQuery.ajax({
type: "POST",
url: site,
data: "plan="+plan,
//data: "business_name="+val+"&bs="+bs,
success: function(msg){
jQuery('#loader').css('display','none');
}
});
}
Which I'm calling on radio button's onclick:
<?php echo $form->text(BILLING_DETAIL.'][id_plan', array('type'=>'radio', 'value'=>$val[PLAN]['id'], 'id'=>'id_plan_'.$val[PLAN]['id'], 'class'=>'rad','onclick'=>'searchPlanAjax('."'".SITE_NAME.ROOT_FOLDER_NAME."'".')')); ?>
The Ajax call will be processed in controller of cakePHP like this:
if(!empty($_REQUEST['plan'])){
$search_plan = $this->{PLAN}->find("all",array("conditions"=>array("id=".$_REQUEST['plan'])));
$this->set('search_plan',$search_plan);
}
but I couldn't get value in $search_plan variable. thanks if anybody can help.
Look at conditions in your find query
if(!empty($_REQUEST['plan'])){
$search_plan = $this->{PLAN}->find("all",array("conditions"=>array("id" => $_REQUEST['plan'])));
$this->set('search_plan',$search_plan);
}
I'm using zend framework, i would like to get POST data using Jquery ajax post on a to save without refreshing the page.
//submit.js
$(function() {
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
url: 'http://localhost/myproject/public/module/save',
async: false,
data: 'id=' + id + '&details=' + details,
success: function(responseText) {
//alert(responseText)
console.log(responseText);
}
});
});
});
On my controller, I just don't know how to retrieve the POST data from ajax.
public function saveAction()
{
$data = $this->_request->getPost();
echo $id = $data['id'];
echo $details = $data['details'];
//this wont work;
}
Thanks in advance.
Set $.ajax's dataType option to 'json', and modify the success callback to read from the received JSON:
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/myproject/public/module/save',
async: false,
// you can use an object here
data: { id: id, details: details },
success: function(json) {
console.log(json.id + ' ' + json.details);
}
});
// you might need to do this, to prevent anchors from following
// or form controls from submitting
return false;
});
And from your controller, send the data like this:
$data = $this->_request->getPost();
echo Zend_Json::encode(array('id' => $data['id'], 'details' => $data['details']));
As a closing point, make sure that automatic view rendering has been disabled, so the only output going back to the client is the JSON object.
Simplest way for getting this is:
$details=$this->getRequest()->getPost('details');
$id= $this->getRequest()->getPost('id');
Hope this will work for you.