Switch between Jquery AJAX and PHP with target="_blank" - php

I have a search result displayed - in this there is an anchor tag like below.
<div class="addfriend">
Add as friend
</div>
I was doing this because, I want to keep my search result. I dont want to do POST-REDIRECT-GET method. I was using AJAX to update friends nesting DB table. If I prevent default action on anchor tag, the link is being opened in the same page and redirected to add_friend.php?from=kpkdhar22&id=2 , DB is updated and when back is pressed search result page is giving error message and search is gone. I want to keep target="_blank" because in case JS is not enabled in browser, it will do in php.
Can I execute the JS function other than anchor tag and still have a new tab.
My AJAX code is like this :
function addfriend(fid, uid) {
// uid -- person sending friends request
// fid -- person receiving friends request
var id = '#' + uid;
$("id").parent().empty().addClass("friend").removeClass("addfriend").html("<span>Request sent</span>");
var userid = uid;
var friendid = fid;
var status = 'N';
var dataString = 'userid=' + uid + '&friendid=' + fid + '&status=' + status;
$.ajax({
type : "POST",
url : "js/add_friend.php",
data : dataString,
cache : true,
success: function (html) {
var id = '#' + uid; // is this ok as selector
$("id").parent().empty().addClass("friend").removeClass("addfriend").html("<span>Request sent</span>");
},
error : function () {
$("#errors").html('');
$("#errors").html('Failed to send your request.');
}
});
}
When the function addfriend(1,2) is executed, a new tab is opened and in add_friend.php a JS alert message is displayed and I am closing that tab immediately. But AJAX success function is not executed, so I added the same before AJAX call, but that is also not worked.
console message -- XHR finished loading: POST "http://localhost/bp1/js/add_friend1.php".
Please suggest me some process, or steps where am I going wrong.
Regards,
Poorna.

You have to make your link stop acting as such. Your AJAX call inside the addfriend() function complicates this a little, but not too much. First of all, change the "onclick" attribute of your link to
onclick="return addfriend(1, 2)"
i.e. add the return statement, and add this to the very end of your addfriend() JS function (after your AJAX call):
return false;
This will trick DOM into thinking that you did click on your link, but for some reason it didn't go well, and the browser should not follow the "href" URL.

Related

jQuery & AJAX: preventDefault on link, run AJAX request, then follow that link

I have this presumably 'simple' task that is absolutely kicking my butt.
My aim is that when a user clicks a link, I prevent the default, run an ajax function on it, then follow that link (ie. resume default). The only thing I can get to work is capturing the href of the link and then following using window.location - this is not ideal, as it doesn't detect whether a user has opted to open in a new window/tab or in the same window/tab; also I think there must be a better way.
However what is happening is that the default is prevented, AJAX function is run but the link is not then followed. What I'm asking is: how to simulated the link click after the function has run?
HTML
This is the link
jQuery
$(document).on('click', 'a', function(e, options){
// setup our options
options = options || {};
// get some details from the link
var this_href = $(this).attr('href');
var this_id = $(this).data('id');
// if options aren't set and this link has a data-id attribute
if(!options.stuff_done && $(this_id).length){
e.preventDefault(); // prevent link following
// run some ajax
$.ajax({
url: myAjax.ajax_url,
type: 'post',
data: {
action : 'a_php_function',
post_id : this_id
},
success: function(response) {
// do stuff
}).then(function(){
$(this).trigger('click', { stuff_done: true });
});
} else {
// else if it doesn't have a data-id, do default
}
});
Context: Checking if a value ('data-id') is in an array using PHP/AJAX and if it is, removing it. This data-id relates to a post's ID in Wordpress, and needs to be removed when a user follows a link to that post.
Hence - user clicks link, data-id is checked, removed/not-removed from array, link is followed.
First give your href an ID like so:
<a href="some_href" data-id="789" id='#some-link'>This is the link</a>
Then simulate a click of it in your ajax success part:
...
success: function(response) {
$('#some-link').click();
})
...
You can examine the response before triggering the click. Also, I don't think you need the .then and all that.

AJAX - Change content based on reply from PHP Script

Scenario
I have a page where users can activate or deactivate the service. I have got a button where it says the current state of the service. I achieve this by getting service state via php and echoing active or inactive at the place of the button text.
Problem I want a AJAX to listen for click on the button. When a user clicks on the active button the AJAX should call a url which triggers change of the users' service state change and returns the current state of the user. I want to change the text in the button to active if the reply was 200 and inactive if the reply from the php was 101.
I want to compare the result in a if-elseif-else style statement like
if(reply=='200')
code-to-change-the-text-to-active;
elseif(reply=='101')
code-to-change-the-text-to-in;
else
alert(some-error);
I made several searches and only found how to change the text with the text from the reply. But, I want a way to fetch the reply as variable and use it to switch my text.
You need to send your reply from PHP to JavaScript as JSON (using json_encode($reply)), then, your AJAX success callback function will receive the state value in a format it can use.
Use the following code format with your actual data:
HTML
<input type="button" value="active" id="active">
JS
$('#active').click(function () {
var status = $(this).attr('value'); // get the value of your button state
var r = confirm("Are You Sure Change Status?");
if (r==true){
$.ajax({
type: "POST",
url: "YOUR URL",
data:"{userstatus:status}",
beforeSend : function () {
},
success:function(result){
//Do whatever you want with result//
}
});
}else{
return false;
}
});
Note: when you click on the active button its call ajax function and put your actual url file name in url param. then run the sql query there and you will get response in success as result.
shortcut/ fast.
JS
function updateStatus(){
$.get('yourPHPCode/getStatus', function(data) ){
$('#status').val(data);
}
}
PHP
function getStatus(){
...
echo $status;
}

PHP AJAX JQUERY load page

I'm using the code below to load the results from a database query in a PHP page:
click me
$('.item > a').click(function(){
var url = $(this).attr('href');
$('.item-popup').fadeIn('slow');
$('.item-content').load(url);
return false;
});
All works fine right now, but the next bit of functionality is a problem. Inside results.php which ajax loads into .item-content, I have another link that is supposed to update and increment click counts for that link, also without refreshing. The functional PHP bits all work fine. My only problem is the jQuery/AJAX aspect of things.
Maybe I'm going about it the wrong way, but what I really want to do is have a page with a container that loads the result of of a database query from a PHP page, but also in that container, I have a link/button whose click count I want to be able to save and update all without refreshing.
EDIT
I guess the most important question I need answering is: When the ajax on index.php loads the content of results.php into the container in index.php, do browsers treat the newly loaded ajax content as part of the parent page (index.php) or is it still treated as a different page loaded into the container like an iFrame?
If say for example it is click event then you need to write
$('input element').on('click',function() {
// write code over here
})
Dont know for sure if you want this, When returning the data in the load function you will have to add a link like this in the resultant HTML which will be clickable:
Now in javascript you need to catch the click event of the link like this:
<script type="text/javascript">
$(function(){
$(".item-content").on("click", ".clickable", function(){
var counter = $(this).data('counter');
var id = $(this).data('id');
$.ajax({
url : //your url here,
data : {'id' : id, 'counter' : counter },
type : 'POST',
success : function(resp){
//update the counter of the current link
$(this).data('counter', parseInt( $(this).data('counter') )+1 );
//whatever here on successfull calling of ajax request
},
error : function(resp){
}
});
});
});
</script>

JQuery onclick issue when calling a function from the parent page

I'm having a problem..
Actually I do have an issue when sending a value from a child page to the parent page.
I'm actually loading a page via JQuery and that page is getting refreshed to display new results, but one of these problems is that the function from the parent page doesn't get called from the child page.
Although this works perfect on Google Chrome, Opera and Safari, it doesn't seem to work on Firefox.
I heard Firefox doesn't manage events the same way as Safari or Google Chrome does?
I've been searching on answers for this but I couldn't find anything pretty much..
Alright, here's what I'm doing:
The child page calls another file which has all the functions that make my site work, this is what should trigger the function:
$like = "<a href='$comment_poster' id='$msgid' class='like'
onclick='parent.likecomment(this);'>Like</a>";
echo "$like";
And this is the function that gets fired from the onclick event which is located in the parent page (the function is in the parent page the onclick is in the child page):
This function is the one that receives the id from the child page to later on add the value to the database.
function likecomment(commentID)
{
event.preventDefault();
var likeid = commentID.id;
var author = ($(commentID).attr('href'));
// forming the queryString
var data = 'likeid='+ likeid + '&author=' + author;
if(likeid)
{
// ajax call
$.ajax({
type: "POST",
url: "likeprofmessage.php",
data: data,
beforeSend: function(html)
{
$(".word").html(likeid);
},
success: function(html){
$("#resultsprofcomments").fadeIn('slow');
$('#profcommentsdiv').load('showprofmessages.php?vprofile=<?php echo $row['1'];?>').fadeIn("slow");
$("#resultsprofcomments").append(html);
}
});
}
}
I've tried the Firefox console and I've received the error: event is undefined so this should be a problem on how Firefox manages events.
Again, any help is appreciated, thank you very much.
I think the following will work as long as you set the onclick handler inline in your HTML (as you did in your example):
<A href="..." onclick='parent.likecomment(event,this);'>blah</A>
<SCRIPT>
function likecomment(evt, commentID) {
evt.preventDefault();
var likeid = commentID.id;
// etc
}
</SCRIPT>
For event handlers not set inline in HTML, the standards compliant browsers (including FF) should automatically pass the event object as a parameter to your handler function. IE, up to version 8, anyway, uses a different event model and lets you reference event directly - really it is window.event but generally as with most window properties it works even if you omit window..
So if you assign your click handler on document ready (or onload) you can do this:
function yourOnloadFunction() {
document.getElementById('yourElementId').onclick = clickHandler;
}
function clickHandler(e) {
// check if event object was passed in, otherwise use window.event
if (!e) e = window.event;
// but how to get a reference to the clicked element?
// use the event object's target property, except (of course)
// in IE, which uses srcElement:
var elRef = e.srcElement ? e.srcElement : e.target;
// rest of your function here, e.g.
e.preventDefault();
}
You have managed to make a mess of your code, but try to change
onclick='parent.likecomment(this);'
to
onclick='parent.likecomment(this);return false;'
and then remove
event.preventDefault();
from your function likecomment(commentID).
Instead of using the in-line onClick, have you tried sending back a script that does something like
<Script>$('#{id}').click(function() {
var id = this.id;
likecomment(id);
return false;
})</Script>

Looking for syntax guidance on implementing AJAX project

I am taking on my first AJAX project and conceptually have everything mapped out for the most part but am being held back due to my lack of knowledge syntactically. I think I also might be off the mark slightly with my structure/function logic.
I am looking for some guidance, albeit reference to tutorials or any corrections of what I am missing or overlooking.
profile.php: this is the page that has the actual thumb icon to click and the $.post function:
Here is the thumb structure.
When thumb is clicked, I need to send the id of the comment? I know I need to calculate the fact that it was clicked somehow and send it to the $. Post area at the bottom of this page, I also need to put some sort of php variable in thumb counter div to increment numbers when the $. Post confirms it was clicked.
<div id="thumb_holder">
<div id="thumb_report">
<a href="mailto:info#cysticlife.org">
report
</a>
</div>
<div id="thumb_counter">
+1
</div>
<div id="thumb_thumb">
<?php $comment_id = $result['id'];?>
<a class="myButtonLink" href="<?php echo $comment_id; ?>"></a>
</div>
</div>
Here is the $.post function
This should be sent the id of the comment? But most certainly should be sent a record of the thumb link being clicked and somehow send it to my php page that talks to the db.
<script>
$.ajax({
type: 'POST',
url:" http://www.cysticlife.org/thumbs.php,"
data: <?php echo $comment_id; ?>,
success: success
dataType: dataType
});
</script>
thumbs.php: is the page that the request to increment is sent when the thumb is clicked and then in turn tells the db to store a clikc, I don't really have anything on this page yet. But I assume that its going to be passed a record of the click from via $.post function from the other page which syntactically I have no clue on how that would work and then via insert query will shoot that record to the db.
Here is what the table in the db has
I have three rows: a id that auto incrments. a comment_id so it knows which comment is being "liked" and finally a likes to keep track on the number of thumbs up.
At least you've made a good start, there are still some mistakes. First of all there are some basic principles you might want to get used to:
1) How to create a click event
First of all the button, I inserted '2' as the href.
<a class="myButtonLink" href="2">Vote Up!</a>
EDIT: Just in case JS in disabled, this would be a better option:
<a class="myButtonLink" href="voteup.php?id=2" id="2">Vote Up!</a>
Then the JS:
$('.myButtonLink').click(function(e) {
e.preventDefault();
alert('the button has been clicked!');
});
The e represents the event, so the first thing we do after the submit is to cancel the default action (redirecting to '2'). Then we're alerting that the button was clicked. If this works, we can go to the next step.
2) Getting the ID value from the clicked link.
Inside the click function, we can use $(this), it's a representation of the element clicked. jQuery provides us with a set of functions to get attributes from a given element, this is exactly what we need.
$('.myButtonLink').click(function(e) {
e.preventDefault();
var comment_id = $(this).attr('id');
alert('We are upvoting comment with ID ' + comment_id);
});
When everything goes well, this should alert 'We are upvoting comment with ID 2'. So, on to the next step!
3) Sending the Request
This might be the harders step if you're just getting started with ajax/jquery. What you must know is that the data you send along can be a url string (param=foo&bar=test) or a javascript array. In most cases you'll be working with an url string because you are requesting a file. Also be sure that you use relative links ('ajax/upVote.php' and not 'http://www.mysite.com/ajax/upVote.php'). So here's a little test code:
$('.myButtonLink').click(function(e) {
e.preventDefault();
var comment_id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'thumbs.php',
data: 'comment_id=' + comment_id,
success: function(msg) { alert(msg); }
});
the dataType is detected automatically, you can for instance choose between a JSON response (which can be an array with a status and message response) or just plain text. Let's keep it simple and take plain text to start of with.
What this script does is calling thumbs.php and sending a $_POST value ($_POST['comment_id'] = 2) along with this request. On thumbs.php you can now do the PHP part which is:
1) checking if the comment_id is valid
2) upvoting the comment
3) print the current amount of votes back to the screen (in thumbs.php)
If you print the number of votes back to the screen, the last script I gave you will alert a messagebox containing the number of votes.
4) Returning an array of data with JSON
In order to get a proper response on your screen you might consider sending back an array like:
$arr = array(
'result' => 'success', // or 'error'
'msg' => 'Error messag' // or: the amount of votes
)
Then you can encode this using the php function json_encode($arr). Then you would be able to get a more decent response with your script by using this:
$('.myButtonLink').click(function(e) {
e.preventDefault();
var comment_id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'thumbs.php',
data: 'comment_id=' + comment_id,
success: function(data) {
if(data.result == "error") {
alert(data.msg);
} else {
alert('Your vote has been counted');
$('#numvotes').html(data.msg);
}
}
});
As you can see we're using (data) instead of (msg) since we're sending back a dataset. The array in PHP ($arr['result']) can be read as data.result. At first we're checking to see what the result is (error or success), if it's an error we alert the message sent along (wrong DB connection, wrong comment ID, unable to count vote, etc. etc.) of the result is success we alert that the vote has been counted and put the (updated) number of votes inside a div/span/other element with the ID 'numvotes'.
Hopefully this was helpfull ;-)
//edit: I noticed some mistakes with the code tags. Fixed the first part of the 'manual'.

Categories