How to load a function only once with JS or PHP? - javascript

I've been making some research these hours and without any success. I will explain my situation and I hope you help me in some way.
I'm making a project for my university, on my site I use the database on a local server with PHP my admin, PHP coding js functions, and html/css. My problem is that when I load the "dashboard site" I want to popup a modal from bootstrap which is a form to complete the second phase of registration, and that popup I do it with :
<script type="text/javascript">
$(window).on('load',function(){
$('#exampleModal3').modal('show');
});
</script>
I've tried to use "include_once" PHP function , or with JS use some tricks like: if(!stuffdone){doSomething ... stuffdone=true;}, but it's not working, when I load the dashboard the popup appears again and I cant make it show only once. My idea is to make it appear only once on the first login of the user and then it won't appear anymore and instead, it will be a button to change the user data which will call the modal popup. Also sorry for my English, is terrible.
Thank you

You could try localstorage to get the registration modal going. But you will have to store it in db and write a function in php that checks users registration progress. and keep in mind that localstorage is just clientside on that particular browser. Something like this pseudocode:
var hasRegged = localstorage.getItem('hasreg');
function checkReg(){
if (hasRegged===null){
$('#exampleModal3').modal('show');
localstorage.setItem('hasreg','1');
}
}
$(window).on('load',function(){
checkReg();
});
$(document).on('click','.finishedregbutton', function(){
//Save the clickdata to db
});
you could also do this with ajax:
function checkReg(){
$.ajax({
"url":"regcheck.php",
"data":"uuid=<?php echo $_SESSION['uuid'];?>",
"type":"POST",
"dataType":"JSON",
"success": function(data){
if(data.status=='completed'){
$('#exampleModal3').modal('show');
}
});
}
$(window).on('load',function(){
checkReg();
});

Related

Converting a button that executes PHP to jQuery/Ajax

I'm trying to write a feature for my Fantasy Football league that allows players to trade with each other. Functionally it all works fine, but as I've coded it all in PHP I have an annoying problem where any time a button is pressed the page is effectively refreshed twice. I've read that I can get around this with jQuery and Ajax but sadly I don't really have any experience with either.
Here's a small section of the code that allows logged in users to withdraw a trade offer they have made:
echo "<input type='submit' id='btn-danger' name='withdraw".$trade_id."' value='Withdraw'>";
if($_POST && isset($_POST['withdraw'.$trade_id])) {
$withdraw = $link->prepare("DELETE FROM trade_id_offers_out WHERE trade_id_offer_id = ".$trade_id);
$withdraw->execute();
}
This creates a "Withdraw" button for each trade offer they have sent out and has a unique name of "withdraw" plus whatever number the offer is in the SQL table.
As I say functionally it works perfectly fine. But it refreshes the page twice and I'm wondering how I can take this code and turn it into something a little more practical?
Many thanks for your time.
First you should make sure you have included jQuery into your page html before any other jQuery (there are plenty of tutorials out there).
Second you need to give the submit button a class so you can select it using a jQuery selector. Change the php code of the button to this:
echo "<input type='submit' id='btn-danger' class='withdrawTradeBtn' name='withdraw".$trade_id."' value='Withdraw'>";
Finally you would make a ajax post request to your url (same url as your page in this case). The js would look something like this and would need to be placed before the end of the html body tag or after all your buttons are rendered:
(Note: I have not tested this but it should be pretty close to what you are after)
<script>
//we need to wait for the page to be loaded in the users browser
$(document).ready(function(){
//we are selecting all the buttons with the class withdrawTradeBtn
//we are binding to the click event so whenever any of the buttons are pressed the code will be ran.
$('.withdrawTradeBtn').on('click', function(e){
//we need to prevent the button from actually reloading the page
e.preventDefault();
//now we need to make a ajax post request to the url
$.post(
'/your/url', //the url to make the post
{$(this).attr('name'):'Withdraw'}, //the submitted data
function(data, status, jqXHR) {// success callback
//here is were you would delete the button or whatever
}
);
});
});
</script>
Most likely you would want to delete the trade entry from the html. You would do that in the success callback of the ajax post. I cant really add anything here because I don't know what your html structure looks like.
Hope this helps, let me know if you need any more help!

Refresh Page with URL Hash after Submitting Form with jQuery Tabs

I'm a long time self taught user, just never had an issue that wasn't already answered in some form or another. Awesome community thank you all!
So I am dumbfounded as to why javascript will not properly refresh my page.
I have a very large page that I use with jquery and vertical tabs tagged with url hashes. This is a new function I recently added after updating to the newest version.
Upon clicking submit the form refreshes and if $_POST[update] is set it will run a set of queries. Then I have a javascript timeout that refreshes the page (ideally to the correct tab ex: home/database.php?file=101#tab3)
an excerpt of my messy code:
if(isset($_POST['update']))
{ do a bunch of sql stuff
....
<pre>
<?PHP
//unset update variable
$_POST = array();
//print_r(get_defined_vars());
?>
</pre>
</br>
<script type="text/javascript">
function Redirect() {
$('#redirect').trigger('click');
}
var currenturl = window.location.href;
document.write("<form action=" + currenturl +"><input type=submit name=redirect value=Redirect></form>");
document.write("</br>You will be redirected back to the file in 2 seconds.");
setTimeout('Redirect()', 2000);
</script>
<?php
mysql_close($conn);
}
else
{ display usual data....check boxes etc
Now I've tried refreshing in every conceivable way. I clear out the $_POST array so the page should reload displaying information, but it doesn't. However my confirmation of queries being ran show that 0 rows updated, so its not triggering the sql but also isn't properly refreshing still.
I found a function that stored the last clicked tab in the browsers session, however when you switch files, it would skip to that tab. Instead I would want to show the default tab.
I even tried made a button that on click it goes to the proper url which is shown above. It works when I click it manually but does not work when I trigger it via javascript. Even goes to the appropriate tab.
I am updating the url in the address bar using the below function. Also using the latest version of chrome.
<script>
$( "#tabs" ).tabs({
activate: function(event, ui) {
window.location.replace('#' + $(ui.newPanel).attr('id'));
var curTab = $(ui.newPanel).attr('id');
console.log(curTab);
}
});
</script>
Why don't you instead of sending that number after <form_url>?<params>#3 send that number as a request param in the url, for example like this <form_url>?tab=3?

My script is causing infinite loop

To begin with: I'm a total newb. These functions are the first I have ever written. I use Wordpress (and the most important plugin used on the site is called BuddyPress). What I essentially want the script to make is delete something from my database and then reload the page one time when pressing a certain link. Nothing more.
I have an issue with Internet Explorer where my page gets stuck in an infinite loop. This problem doesn't occur on Chrome at all. I have a PHP containing the following:
<li><a id="edit" href="#" onclick="runUpdateForm();">Uppdatera profil</a></li>
When pressing the link the following script is run:
<!--Javascript runUpdateForm-->
<script type="text/javascript">
function runUpdateForm() {
$.post ( ajaxurl, {
action:'resetUser',
user_id:jQuery("#user_id").val()
});
window.location.reload();
}
</script>
<!--End Javascript runUpdateForm-->
In my functions-file the following is found:
function resetUser() {
$user_id=get_current_user_id();
global $wpdb;
$wpdb->query("DELETE FROM wp_profile_updates WHERE user_id='".$user_id."'");
die(); // close the connection
}
add_action('wp_ajax_resetUser', 'resetUser'); // add action for logged users
add_action( 'wp_ajax_nopriv_resetUser', 'resetUser' ); // add action for unlogged users
After Googling a bit I found the following piece of code which I put right above location.reload():
history.pushState("", document.title, window.location.pathname + window.location.search);
This made the infinite-loop go away but still it reloads one time to much in Internet Explorer, in comparision to Chrome and what I actually want to happen.
Sorry for my poor English. I'm a Swede :-)
I appreciate the help. I need someone with knowledge to tell me if they see anything right away which looks crazy and should be changed. My problem maybe is related to other stuff happening on my site.
Regards.
Your code does: start the ajax, then reload. as ajax is async, it will never post to the server, its interrupted by the reload. So you need to await the ajax:
<script type="text/javascript">
function runUpdateForm() {
$.post ( ajaxurl, {
action:'resetUser',
user_id:jQuery("#user_id").val()
},function(){
// executed on success
window.location.reload();
});
}
</script>
also, im wondering where ajaxurl is defined...

Passing php variables on click without refresh

The problem:
I have a series of 'accept' buttons, on click it opens a lightbox (a modal- using bootstrap), of course this is done without refreshing the page.
On the lightbox I need to show information regarding what is being accepted (therefore I need to pass a PHP variable to the lightbox). So the problem is how can I pass on a variable on click without refreshing the page? I tried using javascript, but the thing is once I set up a variable in JS I can't get that variable to PHP without refreshing the page.
The button has this code.
<button class="btn btn-acceptColor m-t-lg">Accept</button>
The other code isn't relevant for the purpose of this question. I just need the concept of how to actually do it.
Any help!?
there are many examples.
I provides some links, you can use them in your code as you suitability..
1). Ajax Tutorial
2). jQuery Ajax POST example with php
3). jQuery Ajax POST example with php
4). show data in lightbox
5). How to add jquery lightbox to content added to page via ajax?
I hope above links helpful for you
$(".btn-acceptColor").click( function (){
var person = {
name: $("#id-name").val(),
address:$("#id-address").val(),
phone:$("#id-phone").val()
}
$.ajax({
type: "POST",
url: "exaple.php",
data: person,
success: function(msg) {
var msg = $.parseJSON(msg);
if(msg.success=='yes')
{
return true;
// fill you light-box form get value from example.php page
}
else
{
alert('Server error');
return false;
}
}
});
});

jQuery hide form on submit?

I have a form setup where a user can register, and on submittal, a PHP script runs which validates the user, and once that is done, it echoes a messagebox which jQuery quickly hides and then fades in over the course of 1 second. What I now want to do is to be able to hide that form on submittal, and I thought this might do it:
$(document).ready(function() {
$('div.mainsuccess,div.mainerror').hide(0).fadeIn(1000);
$('form.register').submit(function() {
$(this).hide(1000);
});
});
Where div.mainsuccess is the success message, and form.register is the form (with a class of register). Now the first line works, which tells me the script is being called, but the form is not being hidden at all. I'm doing something stupid here, but I cannot figure out what?
I've tried to look through the jQuery API documentation for submit(), but I cannot understand what is being said. Thanks.
I think the reason it may not work is because the form is submitting it's data and waiting for page to refresh... which means, it will stop all of it's javascript stuff coz it's pointless ... I could be wrong but hey, your hide would take 1 second to hide but your page could reload quicker.
$(document).ready(function() {
$('div.mainsuccess,div.mainerror').hide(0).fadeIn(1000);
$('form.register').submit(function(e) {
e.preventDefault();// will stop the form being submited...
$(this).hide(1000);
// do ajax here...
return false;
});
});
Updated
here is a list of tutorials
http://viralpatel.net/blogs/2009/04/jquery-ajax-tutorial-example-ajax-jquery-development.html
http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
http://www.sitepoint.com/ajax-jquery/
Videos ....
http://www.youtube.com/watch?v=0CMTQtnZ0G0
Try this:
$("form").submit(function(e){
e.preventDefault();
$(this).hide(1000);
});
You'd want to incorporate an ajax call (I'm taking post) to call the php instead of reloading the page
$('form.register').submit(function(e) {
e.preventDefault();
url = $(this).attr('action');
$.post(url,$(this).serialize(), function(data) {
alert('success');
// data will return source code of the URL so you can grab that data and put it somewhere on the script like so.
$('#result').html($(data).find('form'));//form can be replaced with anything
// #result is the id of an element you wish to return the info to
});
$(this).hide(1000);
});
And you'd be done.
More info here
Well, seems that the form refreshes after submission, so it is still there.
I suggest using something like jQuery form: http://jquery.malsup.com/form/
Read up on it and you will find how to use it, and when it is submitted, it won't refresh, and using hide() you will be able to hide it.
N.B you will need jQuery referenced in your code to use jQuery form.
Enjoy.

Categories

Resources