My script is causing infinite loop - javascript

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...

Related

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

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();
});

How to run a Javascript program automatically after page refresh?

I am wondering if it is possible to have my program which ends with a page refresh, automatically run again after the page refreshes.
call the function(s) you want to run.
function doBusiness() {
// the business
}
doBusiness(); // leave the program where it is but make sure this is outside of any function that isn't called right away
If you don't want to do business the first time the page loads, look into sessionStorage, good starting point is mozilla doc. cheers
You can use:
<body onload="yourLoadingFunction()">
or
document.onload = function(){
//your code here
}
Any of these functions should be included in your tag in your page.

How do I change URL without reloading page? - WITH A TWIST

I am looking to remove a certain amount of a page URL without reloading.
I have looked on StackOverflow for the answer and there are a few close answers but not what I'm looking for really.
I do not want to use the hash function and if possible, avoid using the HTML5 version because HTML5 isn't the ratified standard yet and for the website this will be used on, I wouldn't be at all surprised is some of the clients used IE6.
I would prefer if it wasn't an extremely complicated solution with 400 lines of code (at that cost I'd rather just reload the page to be honest).
I forgot to mention this, critical, part of the question
The user is directed from a different page with this string via PHP. So for example:
user submits a form with errors. Let's say the form is on /myform.php
The user gets headed to /index.php?string
carry on as normal
What I have:
This is an example URL that I wish to edit without reloading:
http://www.mywebsite.com/index.php?string
Wait! ?string has a use on /index.php
index.php will use $_GET['string']; and display a message to the user
I have used JQuery to remove the message after 4 seconds like this:
<div id="pagemsg"><?php echo $string; ?></div>
<script language="javascript">
setTimeout( "$('#pagemsg').fadeOut();", 4000);
</script>
This works all well and the message disappears after 4 seconds. However I'm left with this URL:
http://www.mywebsite.com/index.php?string
I don't want this string anymore because ?string has done its job!
I would like to remove the ?string without reloading the while page.
Is there any solution that can help me?
Also,
I don't mind if I have to use the HTML5 push function but is there a fall-back solution for the browsers that don;t support HTML5?
Why did I put WITH A TWIST in the title? Well, my requirements are different to the questions I have seen so far. Correct me if I'm wrong and I will change it.
Thanks for your help in advance!
The simple answer is no. That's why they added pushState.
However, it looks like you are trying to accomplish a fairly common scenario known as flash messaging. This is often done using the user's session to store a message to show on the next request (and then delete it).
Example:
function doImportStuff() {
// ...
$_SESSION['message'] = 'important stuff was done';
// ...
}
function showBoringPage() {
// ...
if (isset($_SESSION['message']) {
echo '<b>' . $_SESSION['message'] . '</b>';
unset($_SESSION['message']);
}
// ...
}
The only method I know of is this:
if (history && history.pushState){
history.pushState(null, null, '/new/url');
}
But this is HTML5 and won't work in your case..
For old browsers - and you: History.js

php echo javascript function after an ajax call doesnt work?

So I ran into a problem and I couldn't really find a good solution anywhere. And I'm sure more people run into this problem.
I tried to have an Ajax script call to a php-script which echoes a JavaScript function again but this function wont run or activate. It however does show up in the code if you do inspect element.
So the html and Ajax is as follows. Its dummy code since my own is a bit more complicated. so any syntax errors I made here are not the solution since this works for other parts of my code.
<html><headbodyetc>
<div id='change'>
//is supposed to alert or call another js function after
//verifying something with a database for instance.
<button type='button' onclick='ajaxbelow();'>alert</button>
</div>
<script type='text/javascript'>
function ajaxbelow(){
//AJAX code as found on w3schools.com/php/php_ajax_php.asp
//calls the change.php
</script>
</etc></html>
The php code that gets called is very simple.
//This shows up in the html-code after clicking the button but doesnt run.
echo"<script type='text/javascript'>alert('doenst work?')</script>";
So I am looking for a solution which makes me able to run a JavaScript or jquery function after an Ajax call, or the main reason why this doesn't work. Since I couldn't find it.
Inb4 why call the alert via php? Because I need to verify something first with the db on the server-side in my actual code.
So after combining and testing some of the comments I figured out my own answer.
You cant create new javascript within the php echo. You can however echo an onload that calls an existing function. Onload only works for the following tags:
"body", "frame", "frameset", "iframe", "img", "input type="image", "link", "script", "style".
However in this case after testing some of them like "script" and "img" it still didn't work with all tags, but it did with the "style" tag. I didnt test all other tags though.
So that changed my code to:
<html><headbodyetc>
<div id='change'>
//is supposed to alert or call another js function after
//verifying something with a database for instance.
<button type='button' onclick='ajaxbelow();'>alert</button>
</div>
<script type='text/javascript'>
//function to be called
function test(){
alert("now it works");
}
function ajaxbelow(){
//AJAX code as found on w3schools.com/php/php_ajax_php.asp
//calls the change.php
</script>
</etc></html>
and the php-code will then become
echo"<style onload='test();'></style>";
and now it does run the function.
edit this doesn't seem to work for IE, looking for a solution right now.
^
EDIT: By default, IE Browsers "DENY" the ability of scripts to throw prompts. So to enable this functionality, you must go to [Tools/ Internet Options/ Security / Custom Level / "Allow websites to prompt for information using scripted windows"] and enable that... Once you refresh, you will see your alert in IE :)
Just add slashes before single quote as given below
<?php echo '<script type="text/javascript">alert(\'doenst work?\')</script>'; ?>
You could use eval() to evaluate the returned javascript. The script tags wont be required if this method is used.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval
Try this:
http://www.webdeveloper.com/forum/showthread.php?184830-Ajax-echo-script-problem
Basically the reason why nothing happens is because you are just sticking content in the DOM. Javascript is an event driven language and since nothing is telling the javascript to run at this point, its just sitting there doing nothing. If that code were there when the browser loaded the page, then the browser parsing the code is what would tell it to run. So, what you need to do is evaluate any scripts that come back

Reloading a Page (or part of a page) using JavaScript

The client I am working for is trying to make it so that his page never has to reload. Instead he just wants to use AJAX. Now I realize that the way im doing it is not a very efficient way to do it but it is the easiest and you would understand why if you would see his site..
I'm trying to get it to work so that AJAX will refresh only parts of the page or the whole page.
My code is:
<!doctype html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script>
function refresh (update) {
$.get(location.href, function (data) {
console.log(data);
var EL = $(data).find(update);
var HTML = $('<div>').append(EL.clone()).html()
alert(HTML);
$(update).replaceWith(HTML);
});
}
</script>
</head>
<body>
<div style="font-size: 64px;">The current timestamp is <b class="time"><?php echo rand(999, 9999999); ?></b></div>
<br><br>
<button onclick="refresh('.time')">Refresh Time</button>
</body>
</html>
When you first load the page PHP generates a random number. Hitting the refresh button is suppose to refresh this number. However, the same number stays there. The request returns the exact same page instead of return a page with a new number.
And again, people note that I know this is not a very efficient way to do this, but its the way i'm trying to get it to work
Am I doing something wrong? (besides requesting the whole page when only actually using part)
EDIT
You can try it out here: http://methods.x10.mx/projects/refreshPageParts.php
Change your call to this, to break the caching:
function refresh (update) {
$.ajax({
type: "get",
cache: false,
url: location.href,
success: function (data) {
$(update).replaceWith($(data).find(update));
}
});
}
See the notes on caching in the documentation: http://api.jquery.com/jQuery.ajax/
By default, requests are always issued, but the browser may serve results out of its cache. To disallow use of the cached results, set cache to false. To cause the request to report failure if the asset has not been modified since the last request, set ifModified to true.
I tested your example on my local wamp stack and it is working fine!
btw: you forgot semicolon after the following line (It is not necessary though)
var HTML = $('<div>').append(EL.clone()).html();
EDIT: your code is working... also on the url you provided. The strange thing is you have to wait a few minutes before it is working. So when you visit the page and press the button, the time won't be updated... however if you wait few minutes it will... only once then you have to wait again. I bet your server is caching the page. So your problem is server side... disable the cache and it will work!!
EDIT:
you also could try to make the get url dynamic with a dummy parameter like so
http://methods.x10.mx/projects/refreshPageParts.php?v=dummy
maybe you don't have to make dummy dynamic, it might work with a static variable also. i'm curious, let me know ;-)

Categories

Resources