Solved

javascript from code behind or button

Posted on 2014-10-07
8
251 Views
Last Modified: 2014-10-08
I'm using some code I found here to be able to reorder a list in asp.net. Users pick items and add to list then reorder them.

Everything works great but I need to change it for my situation. Currently it doesn't reorder my list in the DB until an item is dragged and resorted.

I want to be able to add a "save" button that will force this script to run and reorder everything even if the user never reorders it themselves manually by dragging.

I googled like crazy how to run javascript from codebehind or a button and found hundreds of examples but none of them work for me. I'm 99% sure that it's me who is the problem here, not the solutions I've tried so I don't know where else to turn to except here.

Here is the javascript.

<script type="text/javascript">

         $(function () {
             $('#sortable').sortable({
                 placeholder: 'highlight',
                 update: OnSortableUpdate
             });
             $('#sortable').disableSelection();

             var progressMessage = 'Saving changes... <img src="loading.gif"/>';
             var successMessage = 'Saved successfully!';
             var errorMessage = 'There was some error in processing your request';
             var messageContainer = $('#message').find('p');

             function OnSortableUpdate(event, ui) {
                 var order = $('#sortable').sortable('toArray').join(',').replace(/id_/gi, '')
                 //console.info(order);

                 messageContainer.html(progressMessage);

                 $.ajax({
                     type: 'POST',
                     url: 'Sortable.asmx/UpdateItemsOrder',
                     data: '{itemOrder: \'' + order + '\'}',
                     contentType: 'application/json; charset=utf-8',
                     dataType: 'json',
                     success: OnSortableUpdateSuccess,
                     error: OnSortableUpdateError
                 });
             }

             function OnSortableUpdateSuccess(response) {
                 if (response != null && response.d != null) {
                     var data = response.d;
                     if (data == true) {
                         messageContainer.html(successMessage);
                     }
                     else {
                         messageContainer.html(errorMessage);
                     }
                 }
             }

             function OnSortableUpdateError(xhr, ajaxOptions, thrownError) {
                 messageContainer.html(errorMessage);
             }

         });

    </script>

Open in new window

0
Comment
Question by:someonenamedbrendan
  • 3
  • 3
  • 2
8 Comments
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
The code you are showing looks like jQuery to me.  To use jQuery code, you must load the jQuery library first.  And that has to be done in the page that is running the javascript because all that is done in the browser, not on the server.
0
 

Author Comment

by:someonenamedbrendan
Comment Utility
I just snipped the script I need run out of the .aspx page. The script runs fine and is doing everything it's supposed to do. I just want to be able to run it on command... like via a button on the page or in code behind.

But I guess I should change my question to how to run this jquery from code behind.
0
 
LVL 82

Expert Comment

by:Dave Baldwin
Comment Utility
As far as I know, to run it "on command" it would have to be a 'named' function that can be called by that name.  Then you could put 'onclick()' in an element like a button on that page.  What you are showing is a 'generic' function that runs when the web browser encounters it on page load.
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
Try adding this
  $('#sortable').on('sortupdate', OnSortableUpdate);
	
  $('#save').click(function() {
    $('#sortable').trigger('sortupdate');
  });

Open in new window

0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:someonenamedbrendan
Comment Utility
either i'm using that incorrectly or it didnt work and broke the drag and drop. :(
0
 
LVL 51

Accepted Solution

by:
Julian Hansen earned 500 total points
Comment Utility
Can you post your code - I managed to get it to work see below
<!doctype html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<script type="text/javascript">
$(function() {
  $('#sortable').sortable({
    placeholder: 'highlight',
    update: OnSortableUpdate
  });
  
  $('#sortable').on('sortupdate', OnSortableUpdate);
  
  $('#save').click(function() {
    $('#sortable').trigger('sortupdate');
  });
  
  $('#sortable').disableSelection();

  var progressMessage = 'Saving changes... />';
  var successMessage = 'Saved successfully!';
  var errorMessage = 'There was some error in processing your request';
  var messageContainer = $('#message').find('p');

  function OnSortableUpdate(event, ui) 
  {
    var order = $('#sortable').sortable('toArray').join(',').replace(/id_/gi, '')
    //console.info(order);

    messageContainer.html(progressMessage);

    $.ajax({
      type: 'POST',
      url: 'e002.php',
      data: '{itemOrder: \'' + order + '\'}',
      contentType: 'application/json; charset=utf-8',
      dataType: 'json',
      success: OnSortableUpdateSuccess,
      error: OnSortableUpdateError
    });
  }

  function OnSortableUpdateSuccess(response) 
  {
    if (response != null && response.d != null) {
      var data = response.d;
      if (data == true) {
        messageContainer.html(successMessage);
      }
      else {
        messageContainer.html(errorMessage);
      }
    }
  }

  function OnSortableUpdateError(xhr, ajaxOptions, thrownError) {
    messageContainer.html(errorMessage);
  }
});
</script>
<style type="text/css">
</style>
</head>
<body>
<div class="ui-widget" id="message">
  <div class="ui-state-highlight ui-corner-all" style="margin-top: 20px; padding: 0 .7em;">
    <p>
      Reorder Items
    </p>
  </div>
</div>
<ul id="sortable">
  <li class="ui-state-default" id="a_1"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 1</li>
  <li class="ui-state-default" id="a_2"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 2</li>
  <li class="ui-state-default" id="a_3"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 3</li>
  <li class="ui-state-default" id="a_4"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 4</li>
  <li class="ui-state-default" id="a_5"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 5</li>
  <li class="ui-state-default" id="a_6"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 6</li>
  <li class="ui-state-default" id="a_7"><span class="ui-icon ui-icon-arrowthick-2-n-s"></span>Item 7</li>
</ul>
<input type="button" value="Save" id="save"/>
</body>
</html>

Open in new window

0
 

Author Comment

by:someonenamedbrendan
Comment Utility
I tried a bunch of different things and kept getting errors in the javascript debugger. "uncaught typeerror" for example. So, for fun a removed all my jquery references:
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>

    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.8/jquery-ui.min.js" type="text/javascript"></script>


     <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>
     <script src="../Scripts/jquery.ui.touch-punch.min.js"></script>

Open in new window


and replaced them with yours and the errors went away and the save button works.

Thanks.
0
 
LVL 51

Expert Comment

by:Julian Hansen
Comment Utility
You are welcome - thanks for the points.
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Having worked on larger scale sites, we found out that you are bound to look at more scalable solutions to integrating widgets, code snippets or complete applications and mesh them into functional sites, in any given composition. To share some of…
This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now