How to prevent that page 'jumps to the top' in jQuery? - php

I'm not a jQuery expert, but tried to create a (simple) function where users can simple click on a button to upvote an item. After a lot of failures, I managed to create the following:
jQuery
function vote(_obj) {
$.ajax({
type: "POST",
data: "id=" + $(_obj).attr("id"),
url: "vote.php"
});
}
$('.favorite').click(function() {
vote(this);
});
So every time a user click, the page refresh (and automatically jumps to the top of the page). I tried already do add a e.preventDefault(); but without any results.
HTML/CSS
<i class="fas fa-heart" style="color:#dc3545"></i>
Kind regards!

Just prevent the default action of the click. This would prevent a form submitting or a link from following it's href url or whatever the default of that element is when that event occurs
$('.favorite').click(function(event) {
event.preventDefault();
vote(this);
});

In additional to e.preventDefault() you can use return false; from a jquery event handler.
$('.favorite').click(function() {
vote(this);
return false;
});
Alternatively, semantically this should really be a <button> not an <a>, make it type='button' and it won't do anything other than your code (the default is type=submit so needs the type= specified otherwise will attempt to submit your form). You may need to add some css to stop it looking like a "button".
<button type='button' class="favorite">
<i class="fas fa-heart" style="color:#dc3545"></i>
</button>
with your same existing code

Prevent reloading
You can use preventDefault() function like this to prevent your browser from reloading :
In your Javascript :
$('.favorite').click(function(e) {
e.preventDefault();
vote(this);
});
Your a tag doesn't have href value so it looks like reloading page (but it's browsing to the same page).
Update vote value
To update your vote value, you can use success() function of jQuery's Ajax call, and update value as you want (ex: only increase or getting value from the call's response), using selector to update the right value.
$.ajax({
type: "POST",
data: "id=" + $(_obj).attr("id"),
url: "vote.php",
success : function(response){
// update your value here, using selector
// ex: $('.vote-' + $(_obj).attr('id')).val(response.vote)
},
error: function(response) {
// handle error
}
});

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.

run php file on button click ajax

Entry level user here. I've seen countless AJAX\PHP examples with data being passed via POST or GET and modified one of their examples. When clicking the button (id="clickMe) I want it to execute advertise.php and nothing more (no variables need to be passed) without refreshing the page and a notification that says success. When I click the button with my current code nothing happens.
<button type="button" id="clickMe">CLICK ME TO RUN PHP</button>
<script type="text/javascript">
$(document).ready(function(){
$('#clickMe').click(function(event){ // capture the event
event.preventDefault(); // handle the event
$.ajax({
url: 'advertise.php',
data: {
'ajax': true
},
success: function(data) {
$('#data').text(data);
}
});
});
});
</script>
Updated, but still isn't executing.
Here is your editted version code:
$(document).ready(function(){
$('#clickMe').click(function(){
$.post("PHP_FILE.php",{ajax: true},function(data, status){
alert(data);
});
});
});
2 things - you need a document ready handler and to prevent the default click action.
$(document).ready(function() {
$('#clickMe').click(function(event){ // capture the event
event.preventDefault(); // handle the event
$.ajax({ // remainder of code...
});
When loading jQuery scripts at the top of the page you need to make sure they do not run until the DOM has loaded, that is what the document ready handler is for. The you capture the click event by including it as an argument for your click's callback function and handle the click with the preventDefault() method.
Since this request is "simple" you may want to consider using one of the shorthand methods, like $.post()

Jquery AJAX appended data reset

I've this script:
<script>
$(document).ready(function() {
$('#signUpForm').submit(function() {
$.ajax({
type: 'POST',
url: "process.php",
data: $("#signUpForm").serialize(),
success: function(data)
{
$('#errors').show();
$('#errors').append(data);
}
});
return false;
});
});
</script>
It displays errors from php script. And right now every time I click submit button, new errors are added to old ones. I wonder, is it possible to reset old errors and show just new, after I click submit button?
Use $('#errors').html(data); instead of $('#errors').append(data);, When you use .append(), you add to the content you already had. .html() replaces the content.
Another alternative might be to empty first and then append. Like $('#errors').empty().append(data);
I wonder why do you have $('#errors').show();? If it was hidden first, maybe better to put .show() after the .html() / .append()`
Use $('#errors').empty().append(data);

Ajax-returned elements do not trigger in jQuery

In the HTML, a dropdown with the ID="project_pick" will fire a change event, sending the selected value to the getallreports.php file. This works. The PHP file does a MySQL lookup and returns values inside some HTML. This also works, and looks great on the page. Here below is the jQuery/ajax code that sends the selected item to the PHP file:
$('#project_pick').change(function(e) {
$.ajax({
type: "POST",
url: "getallreports.php",
data: "project_id=" + $(this).val(),
success:function(data){
$('#reportstable').html(data);
}
});
});
The returned data appears inside the specified div, and includes anchor tags with specific IDs that should allow other JQuery events to happen. Snippet of returned HTML:
<table><tr>
<td>Report 1</td><td>click to change</td>
<td>Report 2</td><td>click to change</td>
</tr></table>
The jQuery code to trigger on the above click event is:
$('#change_1').click(function() {
alert('Change Report One was clicked');
});
However, clicking the above anchor tag does nothing. Also, the returned HTML does not even appear in the source -- although it shows on the screen and in firebug.
What am I missing? How can I get that click event to fire?
EDIT:
I've been reminded about the .on('click', etc) event (thanks Michael and Zirkms), but when I attempted to add it to my code the dropdown's .change event stopped firing. Perhaps the below code needs a facelift?
$('#project_pick').on(change(function(e) {
$.ajax({
type: "POST",
url: "getallreports.php",
data: "project_id=" + $(this).val(),
success:function(data){
$('#reportstable').html(data);
}
});
});
On the moment of $('#test').click() code execution #test didn't exist in the DOM, so you didn't bind that handler to somewhere.
Use
$(document).on('click', '#test', function() { ... });
instead
Or (better) if you have a particular node where you insert the retrieved html - use some particular selector rather than $(document) like
$('#reportstable').on(...)
does not even appear in the source
In the "view source" browsers usually show the response from the server as it was retrieved on request, without reflecting JS DOM modifications.

ajax jquery search form in PHP

This is my form:
<form id="submitsearch" action="Classes/system/main/searchresult.php" method="POST">
Search by <span style="font-size:15px;">(developer, specialization, profession,major)</span>
<input type="text" name="searchbox" id="searchbox" />
in
<select style="text-align:center;" name="countrysearch" id="countrylist">
<option selected="selected" value="0">None</option>
<option value="1">USA</option>
</select>
<input style="margin-left:25px;" id="submitSearch" type="submit" value="Search"/>
</form>
and this is the Ajax jquery code:
$("#submitSearch").click(function(){
$.ajax({type:'POST', url: 'Classes/requests/search.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#submitsearch').find('#pagePanel').html(response);
});
Why isn't it working ? The php file is returning the correct result normaly.
But i want it to load inside another div with an id "pagePanel" without reloading, using ajax.
Any help ? I'm new to Ajax.
Edit:
$("#submitbutton").click(function(){
$.ajax({type:'POST', url: 'Classes/system/main/searchresult.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#pagePanel').html(response);
}})});
This worked out with me.
Thanks for all your help.
If you have a input of type submit, it will, guess what :), submit the form, and therefore reload the page. Turn it into:
<input style="margin-left:25px;" id="submitSearch" type="button" value="Search"/>
Then make sure you actually have a pagePanel element in your html.
And now a couple of suggestions:
don't id your form #submitsearch and the button as #submitSearch... confusion may arise
you can use AJAX's .load() instead of .ajax() to get directly the result in the DIV:
So:
$("#pagePanel").load('Classes/requests/search.php', {$('#submitsearch').serialize()});
If you want to use ajax in the form submition you'll need to cancel it.
$("#submitSearch").click(function(event){
$.ajax({type:'POST', url: 'Classes/requests/search.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#pagePanel').html(response);
});
event.preventDefault();//prevents submitting of the form
}
First you need to stop the default form submittal. return false in the submit handler to stop default. Just use the ID of the element without using find() to insert data into. The elemnt you are trying to find doesn't appear in your html though within the form where your code suggests it should be
$("#submitSearch").click(function(){
$.ajax({type:'POST',
url: 'Classes/requests/search.php',
data:$('#submitsearch').serialize(),
cache: false,
success: function(response) {
$('#pagePanel').html(response);
}
})
return false;
});
After pushing the submit button, the default behaviour is to submit the form and indeed go to the action URL you provided to your form. Now, you want to prevent that behaviour. This means, you'll have to look at the onsubmit event of the form, and prevent the actual submission. jQuery has a preventDefault() method to do this.
In your case, all you'll have to do is add the following code:
$(document).ready(function() {
$("#submitsearch").on("submit", function (e) {
e.preventDefault();
});
});
And here is a jsFiddle to demonstrate it.
You can obviously do the same thing to your submit button, just add the e variable as the argument to your click event and use e.preventDefault() to cancel the actual submit (but you can still perfectly do the AJAX request).
First of all, you are missing a few closing parenthesis and curly brackets. Be sure to run your dev tools in your browser to check console for errors like that. I normally don't use $.ajax...I usually use $.post, but using what you have so far, I would rewrite to something closer to:
$("#submitsearch").submit(function(){
var submitData = $(this).serialize();
$.ajax(
{
type:'POST',
url: 'Classes/requests/search.php',
data: submitData,
cache: false,
success: function(response) {
$('#pagePanel').html(response);
}
}
);
return false;
});​
Instead of sending back loads of HTML to the page, you could just send results in form of a set of JSON objects and then dynamically create the HTML based on the results, this means a lot less data being sent back to the browser which is quicker and more efficient.

Categories