I really want to know if there is a shorter alternative to writing this code. I have attempted to shorten it to 2 or 1 functions and achieved miserable failure. I'm seeking constructive feedback!
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
function f_solar_1() {
$.get("f_solar_1.php");
return false;
}
</script>
<script type="text/javascript">
function refresh(){
location.reload(true);}
</script>
<script type="text/javascript">
function both(){
f_solar_1()
setTimeout(refresh, 5);
}
</script>
Activate
Details:
This code is an excerpt from my php page that displays a table from my mysql database (I'm using wamp).
The "Activate" text at the bottom is supposed to UPDATE a variable on that table, and does so via the f_solar_1.php file.
The issue is the table reflecting the database does not automatically reflect this change.
So I made a "reload()" function to refresh the page, and the "both()" function to time the refresh after updating the database.
I have known basic html for a while, but I am new to mysql, ajax, and php as of this morning, and this is my attempt to dive into it.
My code works fine, it just bothers me not knowing if I can accomplish the same thing within one function.
Thank you in advance!
UPDATE: Thankyou to Dat Pham for pointing me in the right direction!
<script type="text/javascript">
function newfunc(){
$.get( "f_solar_1.php", function( data ) {
location.reload(true);
});}
</script>
<span onclick="newfunc();">newfunc</span>
The code is all in one function (well...) and without causing a refresh and php recall timing conflict.
Making 1 function do all the thing is considered bad practice, a function should do and only do an atomic task. Your code is fine except some minor points:
ajax call $.get() and location.reload should not be used with each other as this destroy the meaning of ajax call. You can pass a callback function to handle data from backend server like
$.get( "f_solar_1.php", function( data ) {
alert( "Load was performed." );
});
Combine all your script tags into 1 with all your function declare
Regards,
Have you checked the database through the backend (phpmyadmin for example) and verified if the changes are being made even though it's not displaying?
i'm wondering if your page isn't really refreshing, and simply going to "#". Check the "return false" - it's not really applying to the "A" link, you would have to put "return false" in the 'both' function for that to cancel the link. But you might not want to do it that way after taking a minute to read this: The return false onclick anchor not completely working
additionally, I'd recommend using the jquery add event listener to trigger your function calls, and get the onClick out of your html tag. Bonus if you learn how to do it without jquery. Read this real quick jquery href and onclick separation
Related
I have a page with JS functions (which are called on mouse click) within <script> ... </script> tags. While I was testing I had encountered problems with .click method not working many times. Therefore I decided to simply call that function manually. However I found no source on the Internet which taught to do this.
I want to avoid clicking the links and simply call for doSumbit('5').
Thank you!
The JS functions are:
<script language="javascript">
function doSubmit(infoTypeId) {
document.forms[1].INFOTYPEID.value = infoTypeId;
document.forms[1].action = document.forms[1].action + "#" + infoTypeId;
document.forms[1].submit();
document.forms[0].INFOTYPEID.value = infoTypeId;
document.forms[0].submit();
}
function doSubmitOne(infoTypeId) {
document.forms[0].INFOTYPEID.value = infoTypeId;
document.forms[0].submit();
}
</script>
and the on-click links are:
<a href="javascript:doSubmit('11')" >Engine News<br></A>
<a href="javascript:doSubmit('5')" >Parts Identification<br></A>
You can run arbitrary JS with execute_script
page.execute_script("doSubmit('5')")
if you expect a return value use evaluate_script - it's all documented here - http://www.rubydoc.info/gems/capybara/Capybara/Session#evaluate_script-instance_method
Of course if you're actually testing an app, you'd be much better off figuring out why click isn't working for you and fixing that, since by just calling JS functions you're not actually testing that your app works.
EDIT: typo doSubit changed to doSubmit
I'm attempting to get some jquery code to run after a sharepoint page loads, the code being:
$(".ms-commentcollapse-icon").click();
I've been using the following to load the code after the page loads, but it does not seem to be very reliable (it will work sometimes and other times it wont):
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script type="text/javascript">
$(window).load(function () {
$(".ms-commentcollapse-icon").click();
});
</script>
are there any other good methods for achieving this? I'm not sure what's going on, sharepoint could be at fault, but I figured I would try fiddling around with the script a bit more first.
You could use an auto-executing function:
<script type="text/javascript">
(function () {
$(".ms-commentcollapse-icon").click();
} ());
</script>
If this is SharePoint 2010 or above, you can use ExecuteOrDelayUntilScriptLoaded(yourfunction,"SP.JS") to keep your code from firing until after the SP.JS library has loaded (or you can put any other library in the second parameter for a similar effect).
If this is in a web part and you don't want it to execute until other web parts on the page are fully loaded, make sure the web part containing the script is below the other web parts.
As a last resort, you could execute it on a delay using setTimeout or setInterval, but that's ugly.
You can prevent the default behaviour by using e.preventDefault(); within the function.
<script type="text/javascript">
$(".ms-commentcollapse-icon").click(function(e) {
// We're going to stop the default behavior
e.preventDefault();
//some code here
});
</script>
some info
I'm working on a webpage that can load data on multiple layouts, so user can choose which one is best. It can be loaded in a list or a cards like interface, and the data is loaded using ajax.
In this page I also have a notifier for new messages that the user received. The ajax function is new, and when page was loaded by the php scripts, the js script (that add a badge with the number of unread messages to a link on a menu item) was working ok.
I'm using HTML5, PHP, jQuery and a mySQL DB.
jQuery is imported onto the HTML using
<script src="https://code.jquery.com/jquery.js"> </script>
So it's a recent version.
the problem
Now, when I load the data onto the page using ajax, the js script won't work anymore. I had the same issue with another js script and I managed to solve it by using the delegate event binder.
But my unread messages updater runs on a time interval, using
<body onload="setInterval('unread()', 1000)">
the unread() js is quite simple:
function unread() {
$(document).ready(function(){
$('#menu_item').load('ajax_countNewMsgs.php');
});
}
it calls a php script which grabs the unread msgs count from the DB and echo into a element that jQuery will point. Hope I'm being clear.
The problem is that I cannot figure out how I would call a timed event using delegate. Without much hope I've tried
$(document).on('ready()','#menu_item', function () {
$(this).load('ajax_countNewMsgs.php');
});
That didn't work.
I read many posts about js stop working after changes in the DOM, but, again, I couldn't figure out a way to solve that, nor found a similar question.
Any help or tips would be highly appreciated.
EDITED to change second php script's name
2nd EDIT - trying to make things clearer
I tried the way #carter suggested
$(document).ready(function(){
function unread(){
$.ajax({
url: 'ajax_countNewMsgs.php',
type: 'GET',
dataType: 'html',
success: function(response){
$('#menu_item').html(response);
},
error: function(response){
//no error handling at this time
}
});
}
setInterval(unread(), 1000);
});
the ajax_countNewMsgs.php script connects to the DB, fetch the unread messages, and echoes the number of unread messages.
If I try to apply the ajax reponse to another element, say, the <body> the results are as expected: at each 1 sec , the body html is changed. So the function is working.
As I said, none of my JS changes the #menu_item. Actuallly this element is part of another php scritp (menu.php) which is imported to the top of the page.
the page structure is this way:
<html>
<head>
some tags here
</head>
<body>
<?php include (php/menu.html); ?>this will include menu with the #menu_item element here
<div id='wrapper'>
<div id='data'>
here goes the data displayed in two ways (card and list like). Itens outside div wrapper are not being changed.
</div>
</div>
</body>
</html>
Even though the elemente is not being rewritten js cannot find it to update it's value.
It's not the full code, but I think you can see what is being done.
$(document).on('ready()','#menu_item', function () {
is an invalid event listener. If you wanted to be made aware of when the DOM is ready you should do this:
$(document).ready(function () {
However I don't think that is actually what you want. Your function unread will fire repeatedly but it attaches an event listener everytime. Instead if you want to make an ajax call every so many seconds after initial page load, you should do something like this (dataType property could be html, json, etc. pick your poison):
$(document).ready(function(){
function makeCall(){
$.ajax({
url: 'ajax_countNewMsgs.php',
type: 'GET',
dataType: 'html',
success: function(response){
//handle your response
},
error: function(response){
//handle your error
}
});
}
setInterval(makeCall, 1000);
});
remove that on your unread function:
$(document).ready(function(){
WHY?
The Document is already "ready" and this document state will only fired 1x - After that the "ready state" will never ever called. Use follwing syntax:
jQuery(function($){
Here's what's happening.
My page loads. Then jQuery loads a feed which is injected into a contentCol div...
in that feed is:
Comment
There is also:
<div class="storyItemComments" id="storyItemComments_66" style="display:none;">....
For some reason this is not working:
$(".commentWrite").live("click",function(){
cmt2open = $(this).attr('name');
$("#" + cmt2open).show();
return false;
});
Any ideas? The only thing I can think of is that it has something to do with the fact that I am using jQuery AJAX to load in the content which the LIVE statement above is referencing....
thanks
on most occasions people should use the die() function before the live... so that will clear any previews instructions and that function is only triggered once...
another thing could be that the instructions are called before the contents are retrieved from the ajax. therefore you should use .success to check if the ajax was successfully loaded and then trigger the click instructions.
as it seems that the <div id="storyItemComments_66" has not been picked up from the DOM.
Following from your comment to this answer
Can you try the following instead of show()?
$("#" + cmt2open).attr('display', 'block');
Can you place your javascript inside;
$(document).ready(function(){
//your code here
});
Not sure this will fix it but it's good practice I find.
Also have you alerted out your variables to see what you get?
What is the error you are getting if any?
Have you tried putting an alert at the top of the function to see if the click event works?
edit
let me know if the above does not fix it and I'll remove this answer to clear out the noise
I have a page that has multiple links with various attributes (these attributes will be pulled in from a database):
index.php
<html>
<head>
<script type='text/javascript' src='header.js'></script>
</head>
<body>
My_Link_1
My_Link_2
<div id='my_container'> </div>
</body>
</html>
My header.js file has:
$(document).ready(function(){
$('.link_click').click(function(){
$("#my_container").load("classes/class.project.php", {proj: $(this).attr('id')} );
return false;
});
});
class.project.php is pretty simple:
<?php
echo "<div id='project_container'>project = ".$_POST['proj']." : end project</div>";
?>
This loads and passes the ID variable (which actually comes from a database) to class.project.php. It works fine for the first link click (either link will work). Once one link is clicked no other links with this div class will work. It feels like javascript loads the class.porject.php and it will not refresh it into that #my_container div.
I tried running this as suggested by peterpeiguo on the JQuery Fourm, with the alert box for testing wrapped inside .each:
Copy code
$(document).ready(function() {
$('.link_click').each(function() {
$(this).click(function() {
alert($(this).html());
});
});
});
This seems to work fine for the alert box. But when applying it to .load() it does not reload the page with the new passed variable. As a matter of fact, it doesn't even reload the current page. The link performs no function at that point.
The example site can be viewed here: http://nobletech.net/gl/
I looked at the link you posted, and the problem is that when you're doing load you're replacing the elements on the page with new ones, thus the event handlers don't work anymore.
What you really want to do is target the load. Something like:
$("#project_container").load("classes/class.project.php #project_container", {proj: $(this).attr('projid')} );
This only loads stuff into the proper container, leaving the links and other stuff intact.
Ideally, the php script should only return the stuff you need, not the whole page's markup.
BTW- Caching shouldn't be an issue in this case, since .load uses POST if parameters are passed. You only have to worry about ajax caching with GETs
Sounds like the request is getting cached to me.
Try this:
$.ajaxSetup ({
// Disable caching of AJAX responses */
cache: false
});
Sorry but this might be completely wrong but after examining your XHR response I saw that you are sending back html that replaces your existing elements.
So a quick fix would be to also send the following in your XHR response (your php script should output this also):
<script>
$('.link_click').each(function() {
$(this).click(function() {
alert($(this).html());
});
</script>