www.webdeveloper.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 19

Thread: prevent page refresh on <form> submit?

  1. #1
    Join Date
    May 2010
    Posts
    12

    prevent page refresh on <form> submit?

    Hi all,

    Let me start by saying I am not a programmer, so please don't answer with something like "well, you just need to plug the AJAX query into the PHP structure with a circular reference to the wimblebobble", because I will have no clue what that means I'm hoping for answers that even a Bear of Very Little Brain like myself will be able to decipher.

    I have a navbar containing the days of the week in the central part of my Joomla website. When a visitor clicks one of the days, a PHP script submits a hidden HTML form, and retrieves and displays a list of radio shows that are scheduled to take place on that day.

    The problem I'm trying to solve is that the entire page refreshes when the user clicks one of the days. I'd rather that just the schedule refresh, not the entire page.

    Here's the relevant portions of the page:

    The hidden form:
    Code:
        <div class="date-input-form">
        	<form action="" method="post" id="ddateform">
            	<input type="hidden" name="ddate" id="ddate" size="11" maxlength="10" value="" />
    			<?php echo JHTML::_( 'form.token' ); ?>
            </form>
        </div>
    and the navbar containing the days of the week:

    Code:
    <div id="navcontainer">
    	
    	<ul id="navlist">
    	<?php if($currentday=="Monday") : ; ?>
    	<li class="currentday"><?php echo $currentday; ?></li>
    	<?php else : ?>
    	<li><a href="#" onclick="document.getElementById('ddate').value = '<?php echo date('Y-m-d', strtotime('monday')); ?>'; document.getElementById('ddateform').submit(); ">Monday</a></li>
    	<?php endif; ?>
    	
    	<?php if($currentday=="Tuesday") : ; ?>
    	<li class="currentday"><?php echo $currentday; ?></li>
    	<?php else : ?>
    	<li><a href="#" onclick="document.getElementById('ddate').value = '<?php echo date('Y-m-d', strtotime('tuesday')); ?>'; document.getElementById('ddateform').submit(); ">Tuesday</a></li>
    	<?php endif; ?>
    
    ....etc for each day of the week.
    Now, I've searched the web for days, and tried things like adding "onSubmit='return false;" to the form element, and tried adding "return false;" to the onClick statement belonging to each day of the week. Nothing seems to work--the entire page still refreshes.

    Does anyone have any insight into what might work in this situation?

    Thanks so much!

  2. #2
    Join Date
    Feb 2012
    Location
    Tallahassee, FL
    Posts
    280
    You are going to have to either use AJAX or you could iframe it (I recommend AJAX) If the form is submitted and AJAX is not used, the page has no choice but to refresh. This is what I used when I was first learning AJAX, maybe it will help you: http://www.tizag.com/ajaxTutorial/

  3. #3
    Join Date
    May 2010
    Posts
    12
    I see, thanks--I'm not averse to using AJAX or something else, if that's what's needed. I had a look at the AJAX tutorial (thanks for the link), but as I said I'm really not a programmer, and this looks like gobbledygook to me

    Based on the code snippet I posted above, would anyone be able to write out the appropriate code to prevent the page from refreshing? I'm sure it's just a line or two, but again--I'm not a programmer

  4. #4
    Join Date
    Feb 2012
    Location
    Tallahassee, FL
    Posts
    280
    Perhaps, is there anyway I could actually see the site as it is now?

  5. #5
    Join Date
    May 2010
    Posts
    12
    Sure (my bad, I should've posted the link to begin with). It's at http://qccr.dyndns.org:82/on-air-schedule.

  6. #6
    Join Date
    Feb 2012
    Location
    Tallahassee, FL
    Posts
    280
    A few tweaks to make this work:
    Give the main div that has class="cmschedule" the ID of "viewSchedule"
    Change your link generation to look like this: <a href="#" onclick="getPrograms();" rel="<?php echo date('Y-m-d', strtotime('monday')); ?>">
    (See how much cleaner that is?)
    include this in the header or footer:
    (jQuery would have been better but Im lazy and this is for free. XD)
    Code:
    function getPrograms(){
        var ajaxRequest;
        try{
            ajaxRequest = new XMLHttpRequest();
        } catch (e){
            try{
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try{
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e){
                    alert("Your browser does not support AJAX!");
                    return false;
                }
            }
        }
        var qstring = "date="+document.getElementById(this).rel;
        ajaxRequest.open("POST", "programs.php", true);
        ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajaxRequest.setRequestHeader("Content-length", qstring.length);
        ajaxRequest.setRequestHeader("Connection", "close");
    
        ajaxRequest.onreadystatechange = function(){
            if(ajaxRequest.readyState == 4){
                document.getElementById("viewSchedule").innerHTML = ajaxRequest.responseText;
            }
        }
        ajaxRequest.send(qstring);
        return false;
    }
    And programs.php needs to contain the script that gets the schedule.

  7. #7
    Join Date
    May 2010
    Posts
    12
    Wow, thank you for taking the time to come up with that! It didn't work, unfortunately, but I'm sure that's more due to something on my end than any fault in the code.

    I'm embedding the getPrograms function in a PHP script; does that make a difference?

    Right now this is how my default.php looks in my Joomla component (I just changed the Mon Tues Wed links to test):

    Code:
    <?php
    // Valid execution check
    defined('_JEXEC') or die('Restricted Access');
    
    /*
     * Filename: 	default.php (Part of CM Broadcast Scheduler, Joomla Component)
     * Author: 		Athanasios Theodorou
     * Version: 	2.1.4
     * License: 	GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
     * Support: 	http://forum.computerman.gr/
     * Copyright (C) 2009-2012, Computerman.gr. All Rights Reserved.
     */
     
    // Get the API
    $doc = JFactory::getDocument();
    $language = &JFactory::getLanguage();
    $language->load('com_cmbroadcastscheduler');
    
    // Include Scripts
    $baseURI = JURI::base()."components/com_cmbroadcastscheduler";
    $doc->addStylesheet( $baseURI.'/css/cmbroadcast_style_modified.css' );
    
    
    // Start Rendering
    if( $this->params->get('show_page_heading', 1)) : ?>
    	<div class="item-page<?php echo $this->escape($this->params->get('pageclass_sfx')); ?>">
    		<h2 class="item-page-title"><?php echo $this->escape($this->params->get('page_heading')); ?></h2>
        </div>
        
    <?php endif; ?>
    
    function getPrograms(){
        var ajaxRequest;
        try{
            ajaxRequest = new XMLHttpRequest();
        } catch (e){
            try{
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try{
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e){
                    alert("Your browser does not support AJAX!");
                    return false;
                }
            }
        }
        var qstring = "date="+document.getElementById(this).rel;
        ajaxRequest.open("POST", "schedule.php", true);
        ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajaxRequest.setRequestHeader("Content-length", qstring.length);
        ajaxRequest.setRequestHeader("Connection", "close");
    
        ajaxRequest.onreadystatechange = function(){
            if(ajaxRequest.readyState == 4){
                document.getElementById("viewSchedule").innerHTML = ajaxRequest.responseText;
            }
        }
        ajaxRequest.send(qstring);
        return false;
    }
    <div class="cmschedule-wrapper">
    <?php
    // With a component parameter, the user will
    // be able to choose to display the day form
    // on the TOP or on the BOTTOM of the component.?>
    
    <?php
        if (!empty($_POST['ddate'])) {
            $currentday = (date("l", strtotime($_POST['ddate'])));
        } else {
            $currentday = date("l");
        }
    ?>
    <?php $currenttime = (date("H")); ?>
    
    <?php if($this->items): ?>
    
    
    
    
        <div class="date-input-form">
        	<form action="" method="post" id="ddateform">
            	<input type="hidden" name="ddate" id="ddate" size="11" maxlength="10" value="" />
    			<?php echo JHTML::_( 'form.token' ); ?>
            </form>
        </div>
    
    
        <div id="navcontainer">
    	
    	<ul id="navlist">
    	<?php if($currentday=="Monday") : ; ?>
    	<li class="currentday"><?php echo $currentday; ?></li>
    	<?php else : ?>
    <li><a href="#" onclick="getPrograms();" rel="<?php echo date('Y-m-d', strtotime('monday')); ?>"></a></li>
    <?php endif; ?>
    	
    	<?php if($currentday=="Tuesday") : ; ?>
    	<li class="currentday"><?php echo $currentday; ?></li>
    	<?php else : ?>
    <li><a href="#" onclick="getPrograms();" rel="<?php echo date('Y-m-d', strtotime('tuesday')); ?>"></a></li>
    	<?php endif; ?>
    	            
    	<?php if($currentday=="Wednesday") : ; ?>
    	<li class="currentday"><?php echo $currentday; ?></li>
    	<?php else : ?>
    <li><a href="#" onclick="getPrograms();" rel="<?php echo date('Y-m-d', strtotime('wednesday')); ?>"></a></li>
    	<?php endif; ?>
    	
    	<?php if($currentday=="Thursday") : ; ?>
    	<li class="currentday"><?php echo $currentday; ?></li>
    	<?php else : ?>
    	<li><a href="#" onclick="document.getElementById('ddate').value = '<?php echo date('Y-m-d', strtotime('thursday')); ?>'; document.getElementById('ddateform').submit();">Thursday</a></li>
    	<?php endif; ?>
    
    	<?php if($currentday=="Friday") : ; ?>
    	<li class="currentday"><?php echo $currentday; ?></li>
    	<?php else : ?>
    	<li><a href="#" onclick="document.getElementById('ddate').value = '<?php echo date('Y-m-d', strtotime('friday')); ?>'; document.getElementById('ddateform').submit();">Friday</a></li>
    	<?php endif; ?>
    	
    	<?php if($currentday=="Saturday") : ; ?>
    	<li class="currentday"><?php echo $currentday; ?></li>
    	<?php else : ?>
    	<li><a href="#" onclick="document.getElementById('ddate').value = '<?php echo date('Y-m-d', strtotime('saturday')); ?>'; document.getElementById('ddateform').submit();">Saturday</a></li>
    	<?php endif; ?>
    	
    	<?php if($currentday=="Sunday") : ; ?>
    	<li class="currentday"><?php echo $currentday; ?></li>
    	<?php else : ?>
    	<li><a href="#" onclick="document.getElementById('ddate').value = '<?php echo date('Y-m-d', strtotime('sunday')); ?>'; document.getElementById('ddateform').submit();">Sunday</a></li>
    	<?php endif; ?>
    	
    	</ul>
    </div>
        
        <div class="show-item-black">
       </div>
       
    
        <div class="cmschedule" id="viewSchedule">
        	<?php if($this->items)  : ?>
        	<ul>
        	<?php foreach($this->items as $item) : ?>
        		<?php
        		// Create Slugs
    ....etc etc.

    Maybe you can tell something from that, I don't know. I sure can't!

  8. #8
    Join Date
    Feb 2012
    Location
    Tallahassee, FL
    Posts
    280
    Wrap that function in script tags
    So it looks like:

    Code:
    <script type="text/javascript">
    function getPrograms(){
        var ajaxRequest;
        try{
            ajaxRequest = new XMLHttpRequest();
        } catch (e){
            try{
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try{
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e){
                    alert("Your browser does not support AJAX!");
                    return false;
                }
            }
        }
        var qstring = "date="+document.getElementById(this).rel;
        ajaxRequest.open("POST", "schedule.php", true);
        ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        ajaxRequest.setRequestHeader("Content-length", qstring.length);
        ajaxRequest.setRequestHeader("Connection", "close");
    
        ajaxRequest.onreadystatechange = function(){
            if(ajaxRequest.readyState == 4){
                document.getElementById("viewSchedule").innerHTML = ajaxRequest.responseText;
            }
        }
        ajaxRequest.send(qstring);
        return false;
    }
    </script>

  9. #9
    Join Date
    May 2010
    Posts
    12
    Ah, right Forgot that. I've added the script tags.

    Still doesn't seem to work, strangely enough It sure LOOKS like it should work! (you can see the results on the page if you visit it)

  10. #10
    Join Date
    Feb 2012
    Location
    Tallahassee, FL
    Posts
    280
    Ok, then the Jquery way, remove that function, replace with:
    Code:
    jQuery(document).ready(function(){
    jQuery("#navlist li").click(function(){
        var clicked = $(this).attr('rel');
        $.post(
            'programs.php',
            {date: clicked},
            function(responseText){
                $("#viewSchedule").html(responseText);
            },
            "html"
        );
    });
    });
    Make you a Tags look like: ( do this for Sunday-Saturday)
    Code:
    <a href="#" rel="<?php echo date('Y-m-d', strtotime('monday')); ?>">

  11. #11
    Join Date
    Feb 2012
    Location
    Tallahassee, FL
    Posts
    280
    HAHA, I also just noticed I put: document.getElementById(this).rel
    that is wrong.
    shold simply be: this.rel

  12. #12
    Join Date
    May 2010
    Posts
    12
    Hmmm...still doesn't work. The default.php file looks like this now:

    Code:
    <?php
    // Valid execution check
    defined('_JEXEC') or die('Restricted Access');
    
    /*
     * Filename: 	default.php (Part of CM Broadcast Scheduler, Joomla Component)
     * Author: 		Athanasios Theodorou
     * Version: 	2.1.4
     * License: 	GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
     * Support: 	http://forum.computerman.gr/
     * Copyright (C) 2009-2012, Computerman.gr. All Rights Reserved.
     */
     
    // Get the API
    $doc = JFactory::getDocument();
    $language = &JFactory::getLanguage();
    $language->load('com_cmbroadcastscheduler');
    
    // Include Scripts
    $baseURI = JURI::base()."components/com_cmbroadcastscheduler";
    $doc->addStylesheet( $baseURI.'/css/cmbroadcast_style_modified.css' );
    
    
    // Start Rendering
    if( $this->params->get('show_page_heading', 1)) : ?>
    	<div class="item-page<?php echo $this->escape($this->params->get('pageclass_sfx')); ?>">
    		<h2 class="item-page-title"><?php echo $this->escape($this->params->get('page_heading')); ?></h2>
        </div>
        
    <?php endif; ?>
    
    <script type="text/javascript">
    jQuery(document).ready(function(){
    jQuery("#navlist li").click(function(){
        var clicked = $(this).attr('rel');
        $.post(
            'programs.php',
            {date: clicked},
            function(responseText){
                $("#viewSchedule").html(responseText);
            },
            "html"
        );
    });
    });
    </script>
    
    <div class="cmschedule-wrapper">
    <?php
    // With a component parameter, the user will
    // be able to choose to display the day form
    // on the TOP or on the BOTTOM of the component.?>
    
    <?php
        if (!empty($_POST['ddate'])) {
            $currentday = (date("l", strtotime($_POST['ddate'])));
        } else {
            $currentday = date("l");
        }
    ?>
    <?php $currenttime = (date("H")); ?>
    
    <?php if($this->items): ?>
    
    
    
    
        <div class="date-input-form">
        	<form action="" method="post" id="ddateform">
            	<input type="hidden" name="ddate" id="ddate" size="11" maxlength="10" value="" />
    			<?php echo JHTML::_( 'form.token' ); ?>
            </form>
        </div>
    
    
        <div id="navcontainer">
    	
    	<ul id="navlist">
    	<?php if($currentday=="Monday") : ; ?>
    	<li class="currentday"><?php echo $currentday; ?></li>
    	<?php else : ?>
    <li><a href="#" rel="<?php echo date('Y-m-d', strtotime('monday')); ?>"></a></li>
    <?php endif; ?>
    	
    	<?php if($currentday=="Tuesday") : ; ?>
    	<li class="currentday"><?php echo $currentday; ?></li>
    	<?php else : ?>
    <li><a href="#" rel="<?php echo date('Y-m-d', strtotime('tuesday')); ?>"></a></li>
    	<?php endif; ?>
    	            
    	<?php if($currentday=="Wednesday") : ; ?>
    	<li class="currentday"><?php echo $currentday; ?></li>
    	<?php else : ?>
    <li><a href="#" rel="<?php echo date('Y-m-d', strtotime('wednesday')); ?>"></a></li>
    	<?php endif; ?>
    	
    	<?php if($currentday=="Thursday") : ; ?>
    	<li class="currentday"><?php echo $currentday; ?></li>
    	<?php else : ?>
    <li><a href="#" rel="<?php echo date('Y-m-d', strtotime('thursday')); ?>"></a></li>
    	<?php endif; ?>
    
    	<?php if($currentday=="Friday") : ; ?>
    	<li class="currentday"><?php echo $currentday; ?></li>
    	<?php else : ?>
    <li><a href="#" rel="<?php echo date('Y-m-d', strtotime('friday')); ?>"></a></li>
    	<?php endif; ?>
    	
    	<?php if($currentday=="Saturday") : ; ?>
    	<li class="currentday"><?php echo $currentday; ?></li>
    	<?php else : ?>
    <li><a href="#" rel="<?php echo date('Y-m-d', strtotime('saturday')); ?>"></a></li>
    	<?php endif; ?>
    	
    	<?php if($currentday=="Sunday") : ; ?>
    	<li class="currentday"><?php echo $currentday; ?></li>
    	<?php else : ?>
    <li><a href="#" rel="<?php echo date('Y-m-d', strtotime('sunday')); ?>"></a></li>
    	<?php endif; ?>
    	
    	</ul>
    </div>
        
        <div class="show-item-black">
       </div>
       
    
        
        
        <div class="cmschedule" id="viewSchedule">
        	<?php if($this->items)  : ?>
        	<ul>
        	<?php foreach($this->items as $item) : ?>
        		<?php
        		// Create Slugs
        		$item['slug'] = $item['alias'] ? ($item['s_id'].'-'.$item['alias']) : $item['s_id'];
        		?>
            	<?php if(empty($item['onair'])) : ?>
                    <li class="show-item-grey">
    I had a look for that "this(rel)" bit you mentioned, but I don't see it anywhere in anything you typed

  13. #13
    Join Date
    May 2010
    Posts
    12
    I'm wondering if there's some special bit I have to do in Joomla to get these scripts to work properly I've no clue unfortunately.

  14. #14
    Join Date
    Feb 2012
    Location
    Tallahassee, FL
    Posts
    280
    Sorry, forgot noConflict was on, try this:
    Code:
    jQuery(document).ready(function(){
    jQuery("#navlist li").click(function(){
        var clicked = jQuery(this).attr('rel');
        jQuery.post(
            'programs.php',
            {date: clicked},
            function(responseText){
                jQuery("#viewSchedule").html(responseText);
            },
            "html"
        );
    });
    });
    And what happened to all your days?

  15. #15
    Join Date
    May 2012
    Location
    St. Helens, UK
    Posts
    74
    I've just spent some time knocking together an example of how you might do it using AJAX and jQuery;
    it took me slightly longer than I thought it would, as I had to re-acquaint myself with how jQuery handles AJAX and JSON.

    I've put what I come up with up on CodePen, here: http://codepen.io/anon/pen/Blgth

    Note the commented out bit at the top:
    Code:
    /*var __myNamespace = [];
    $.getJSON("showdata.json").done(function(data) {
      __myNamespace['showdata'] = data;	
    })
    }*/
    Assuming that the information about your various shows is going to be dynamic - i.e. subject to change week on week - it makes sense to have the data stored in an external file on your server - in this case 'showdata.json'. JSON is essentially an information interchange format using JavaScript's object notation. (Apologies if this is already turning into unreadable gobbledygook for you...)

    However for the purpose of this demo I just created an object with data for Monday and Tuesday:
    Code:
    var __myNamespace = [];
    __myNamespace['showdata'] = {
      "monday":"Insert content for Monday here",
     "tuesday":"Insert content for Tuesday here"};
    
    $(document).ready(function() { 
    	$('.weekday').click(function() {
    		weekday = $(this).attr('id');
    		$('#shows').html(__myNamespace['showdata'][weekday]);
    	})
    });
    And the jQuery function triggers when an element of class 'weekday' is clicked, ascertains the unique id of the element, fetches the corresponding data from our data object and adds it to the 'shows' div.

    For further info on what's going on here, have a read of the jQuery tutorials at http://docs.jquery.com/Tutorials; Wikipedia has a fairly good explanation of what JSON is: http://en.wikipedia.org/wiki/JSON

    Hope this helps.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles