Ajax request to php only works once per pageload - javascript

I have seen a few of these questions post on here but none of them are working for me. I have a favourite button that i would like my users to press to favourite things. The ajax request is working just fine and the favourite gets stored in the database but i can only use it once then i have to refresh the page to fav/unfav the item. The code for the button is:
<div id="fav-icon">
<?php
// Function checks if user has fav'd the item.
$isFav = favourite($user->id) ? 'un-fav' : 'fav';
?>
<i id="<?php echo $item->id; ?>" class="<?php echo $isFav; ?>"><span class="font-12 fa fa-heart"></span></i>
</div>
Jquery/Ajax
$('.fav').click(function(e){
var con = $(this).attr('id');
$.ajax({
url: 'fav.php',
type: 'POST',
async: true,
data:{
'fav' : con
},
success:function(){
$('#fav-icon').load(document.URL + ' #fav-icon');
}
});
});
$('.un-fav').click(function(e){
var con = $(this).attr('id');
$.ajax({
url: 'fav.php',
type: 'POST',
async: true,
data:{
'fav' : con
},
success:function(){
$('#fav-icon').load(document.URL + ' #fav-icon');
}
});
});
So this works but only once! I have tried a couple of different functions to try make this work including:
$('.fav').live('click', function(e) {
Can anyone tell me where i am going wrong and the correct method to get my button to work multiple times?

Use $(document).on() click event
$(document).on('click','.fav', function(e) {
...
});

Related

ajax - save javascript value to php

After hours of trying to get this to work, i want to ask you :)
So i have a php Page that can display files from a server. Now I can edit
the files with a editor plugin.
Textarea is the tag where the editor gets rendered.
To save the changed text from the editor, I have a button that gets the innerHTML from the surrounding pre tag of the text with javascript.
I now want to pass that variable via ajax to a php variable on the site get.php,
so I can save it locally and send it to the server.
The problem is, that there is no reaction at all, if i click the "Save" button. I tested a lot of answers from similar ajax functions here, but none of them gave me a single reaction :/
php main
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
...
echo "<textarea><pre id='textbox'> ";
echo $ssh->exec($display);
echo "</textarea></pre>";
echo '<input type="button" value="Save File" id="butt">';
echo "<script>
var show = document.getElementById('textbox').innerHTML;
$(document).ready(function() {
$('#butt').click(function() {
$.ajax({
type: 'POST',
url: 'get.php',
data: {'variable': show},
success: function(data){
alert(data);
}
});
});
});
</script>";
...
get.php
if (isset($_POST["variable"])){
$show =$_POST["variable"];
echo $show;
}
Edit:
This is the actual working state:
echo "<textarea id='textbox'><pre> ";
echo $ssh->exec($display);
echo "</pre></textarea>";
echo '<input type="button" value="Save File" id="butt">';
echo "<script>
$(document).ready(function() {
$('#butt').click(function() {
var show = document.getElementById('textbox').value;
$.ajax({
type: 'POST',
url: 'get.php',
data: {'variable': show},
success: function(data){
alert(data);
},
});
});
});
</script>";
You have an error in the data: {'variable': show)} part. It should be: data: {variable: show}. Also you should use Firebug or Firefox developer tools for these kind of problems. A lot easier to see whats wrong.
I would suggest small changes to see if everything is running as it should.
I can see that pre tag is behind textarea closing tag - try to change it
Try putting var show = document.getElementById('textbox').innerHTML; inside of the ,,butt" function
Then I can see your problem here data: {'variable': 'show')}, - you are sending 'show' as a string - remove quotes to send it as a variable which will appear as a POST value in PHP site.
with this should work:
$.ajax({
type: 'POST',
url: 'get.php',
data: {variable: show)},
success: function (data){
alert(data);

Send js value to php controller by ajax

I have this button
<button id="<?php echo $u['id']?>" name="activation" onclick="handleButton(this);" type="submit" class="btn btn-success"></button>
And this button related to this
<td id="<?php echo $u['id']?>"><?php echo $u['id']?></td>
I'm using this script to send value of button to my php controller
function handleButton(obj) {
var javascriptVariable = obj.id;
// alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: 'myname='+javascriptVariable,
success: function (data){
}
});
}
When I use alert, the result of javascriptVariable is correct and I want it in my controller so I'm trying in my controller to do this:
if(isset($_POST['activation']))
{
$name = $this->input->post('myname');
var_dump($name);
}
But I get null value, what is the wrong?
When you pass data from the browser via AJAX only the data you pass in the data: parameter is sent to the PHP script.
So if you want to test for activation in the PHP script you must actually send that parameter
Also see the amendment to the data: parameter creation below. Its easier to read and a lot easier to code correctly when passing more than one parameter as you dont have to remember &'s and + concatenation.
function handleButton(obj) {
obj.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: {activation: 1, myname: obj.id}, // add parameter
success: function (data){
alert(data);
}
});
}
Now the PHP will see 2 parameters in the $_POST array activation and myname
if(isset($_POST['activation']))
{
$name = $_POST['myname'];
var_dumb($name);
}
Or if you are using a framework which I assume you are
if(isset($this->input->post('activation')) {
$name = $this->input->post('myname');
var_dumb($name);
}
EDIT:
Spotted another issue your button has an attribute type="submit" this will cause the javascript to run AS WELL AS the form being submitted in the normal way.
Remove the type="submit" attribute and to be doubly sure that the form will not be submitted as well as the AJAX add a call to preventDefault(); as well before the AJAX call
Since the php script is conditioned by a second POST variable [if(isset($_POST['activation']))], you should post that as well.
function handleButton(obj) {
var javascriptVariable = obj.id;
// alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: 'myname='+javascriptVariable+'&activation=1',// <-- RIGHT HERE
success: function (data){
alert(data);
}
});
}
SIDE NOTE: you could also echo instead of dump the variable:
if(isset($_POST['activation']))
{
echo $this->input->post('myname');
}
Try this in your ajax function :
function handleButton(obj) {
var javascriptVariable = obj.id;
//alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: {myname: javascriptVariable},
success: function (data) {}
});
}
And in your PHP script, you can do $_POST['myname'] to get it (maybe $this->input->post('myname') can work, you can test it)
Look two id
<button id="<?php echo $u['id']?>" name="activation" onclick="handleButton(this);" type="submit" class="btn btn-success"></button>
AND
<td id="<?php echo $u['id']?>"><?php echo $u['id']?></td>
For both html elements id is same.It can not be used with in the same page.This may cause a problem for you...

Like Dislike Function AJAX

I have this jQuery AJAX Like Dislike Script
<script>
$(function(){
var PostID = <?php echo $PostID; ?>;
$('.like-btn').click(function(){
$('.dislike-btn').removeClass('dislike-h');
$(this).addClass('like-h');
$.ajax({
type:"POST",
url:"rate.php",
data:'Action=LIKE&PostID='+PostID,
success: function(){
}
});
});
$('.dislike-btn').click(function(){
$('.like-btn').removeClass('like-h');
$(this).addClass('dislike-h');
$.ajax({
type:"POST",
url:"rate.php",
data:'Action=DISLIKE&PostID='+PostID,
success: function(){
}
});
});
});
</script>
Now I want to transform this script to multi post Like Dislike System.
How i can do this? HTML will look like this:
Like
Dislike
LIKE/DISLIKE will be action, 1 will be ID of post to like/dislike. Thanks
you can make something like this. Each post it is each div with postId and two controls inside (like and dislike buttons). When you click like - function will get post id and send with post to server. You must to check ajax part of function.
$(function () {
$('.like').click(function () { likeFunction(this); });
$('.dislike').click(function () { dislikeFunction(this);});
});
function likeFunction(caller) {
var postId = caller.parentElement.getAttribute('postid');
$.ajax({
type: "POST",
url: "rate.php",
data: 'Action=LIKE&PostID=' + postId,
success: function () {}
});
}
function dislikeFunction(caller) {
var postId = caller.parentElement.getAttribute('postid');
$.ajax({
type: "POST",
url: "rate.php",
data: 'Action=DISLIKE&PostID=' + postId,
success: function () {}
});
}
<div class="post" postid="10">
<input type="button" class='like' value="LikeButton" /> </input>
<input type="button" class='dislike' value="DislikeButton"> </input>
</div>
If you have some questions or need more help you can ask me :)
If you want more than one post per page you can do this:
function send(action, id)
{
var opposite;
opposite = action === 'like' ? 'dislike' : 'like';
$('#' + opposite + '-' + id).removeClass(opposite + '-h');
$('#' + action + '-' + id).addClass(action + '-h');
$.ajax({
type:"POST",
url:"rate.php",
data:'Action=' + action + '&PostID=' + id,
success: function(){
}
});
}
Now you only need to attach the handlers properly ($PostID must be different for every post in a loop):
<a href="#"
id="like-<?php echo $PostID; ?>"
onclick="send('like', <?php echo $PostID; ?>)">Like</a>
<a href="#"
id="disloke-"<?php echo $PostID; ?>"
onclick="send('dislike', <?php echo $PostID; ?>)">Dislike</a>
That's just a layout of the code, there may be defects. It's pretty different from where we started, so only you can actually test it and see where it need refinement.

Ajax function not working in CodeIgniter

I have a button in my page, when I click on this button it redirect me to this link readMessage/id.
I want when I click on it to stay in the same page, I don't want my page to be reloaded or something else.
The link readMessage/id will update the database, which is a function in a controller :
function readMessage($id) {
$this->message_module->readMessage($id);
$this->index();
}
This function will call the readMessage function in the message module :
function readMessage($id) {
$data = array('is_read' => 1);
$this->db->where('id',(int)$id)
->update($_tbl_msg, $data);
}
This is my button :
<button class="testButton" data-id="<?php echo $message->id; ?>">Test</button>
And this is the code I tried :
$('.testButton').click(function(){
// get jquery object access to the button
var $thisButton = $(this);
var form_data = {
id : $thisButton.data('id')
}
$.ajax({
url:'<?php echo base_url;?>messages/readMessage',
type:'GET',
data: form_data,
success:function(d){
alert(d);
}
});
});
But it's not working.
If someone could show me how to do that I'll be thankful.
Edit 1:
I changed the ajax code, and it worked I can see now the alert box which is in the success attribut :
$('.testButton').click(function(){
$.ajax({
url:"<?php echo site_url('messages/readMessage'); ?>",
type:'GET',
data: {id : $(this).data('id')},
success:function(d){
alert(d);
}
});
});
I think the URL after that will be : messages/readMessage?id=myId , but in CodeIgniter it should be : messages/readMessage/myId, that's why it doesn't work.
I did a test by giving the id manually :
url:"<?php echo site_url('messages/readMessage/5'); ?>"
And it worked.
Now I need to know how to concat that value $(this).data('id') with the url, because when I tried this : url:"<?php echo site_url('messages/readMessage/" + $(this).data('id') + "'); ?>", it didn't worked.
As per your recent edit, try below code in url section
url:"<?php echo site_url('messages/readMessage'); ?>/"+$(this).data('id'),
Then your readMessage should accept a parameter as below
function readMessage($data ="") {
In you controller
try by echoing
function readMessage() {
$id=$this->input->get('id');
$this->message_module->readMessage($id);
$this->index();
echo "something";
}

Show/Hide doesn't work unless page is refreshed

EDIT: for clarity purposes, I've edited this question.
EDIT 2: I was able to solve half of my issue.
Below is a simple script for users to delete the pictures they uploaded.
Depending on whether or not there is an image saved in the database. A toggle OR an upload icon should show.
The issue is that when the delete button is clicked, the picture and the toggle buttons get removed BUT the upload icon won't show (unless page is refreshed).
if (image exists in database) {
<div class="toggle" id="toggle<?php echo $image_id ?>"></div>
}
else {
<div class="upload_icon" id="upload<?php echo $image_id ?>"></div>
}
`SQL query to select image in database`
//this DIV expands when the toggle button is clicked
<div class="content" id="image<?php echo $image_id ?>"><img src="<?php echo
$path ?>" />
<div class="remove content"><a href="#" id="<?php echo $image_id ?>"
class="delete_icon">Remove!</a></div>
</div>
Javascript part:
$(function(){
$('.delete_icon').on("click",function()
{
var ID = $(this).attr("id");
var dataString = 'image_id='+ ID;
$this = $(this);
if(confirm("Are you sure you want to delete this image ?"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: dataString,
cache: false,
success: function(html){
$('#image'+ID).remove()
$('#toggle'+ID).remove()
$('#upload'+ID).show();
});
}
return false;
});
});
What am I missing here ?
this is no longer the link once you're inside the context of the success function. I saved off this and used it inside, that should do the trick.
Also I'm not sure that the find is actually going to work. Based on your example I'm not sure that #toggle elements are actualy nested within .delete_icon.
If they aren't you might want to do $('#toggle'+ID) rather than using find. It's an ID selector anyway so it wouldn't be affecting performance.
$(function(){
$('.delete_icon').on("click",function() {
var ID = $(this).attr("id"),
dataString = 'image_id='+ ID,
$this = $(this);
if( confirm("Are you sure you want to remove this image ?") ) {
$.ajax({
type: "POST",
url: "delete.php",
data: dataString,
cache: false,
success: function(html) {
$this.closest(".content").hide();
$('#toggle'+ID).hide()
$('#upload'+ID).show();
}
});
}
return false;
});
});

Categories