Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Perl AJAX jQuery, js file

by monx663 (Sexton)
on Jan 11, 2021 at 12:29 UTC ( [id://11126745]=perlquestion: print w/replies, xml ) Need Help??

monx663 has asked for the wisdom of the Perl Monks concerning the following question:

This is not exactly a Perl question but, I'm using Perl as the backend programming language that creates HTML so...

I am incorporating AJAX on a CMS written in Perl which has been stable for years. One of the backoffice pages of this CMS, shows a list of items that expose actions that can be carried out on this item. One of these actions is Activate/Inactivate. This is just an icon wrapped around that would call the right Perl script on the server and switch the items' status. I am trying to do this with AJAX/JSON jQuery inline, rather than enforcing a full page reload with the traditional href link to a CGI script.

I have written a script on the server that responds to AJAX called with jQuery and completes the desired action and returns dynamic results that update the corresponding hardcoded (div2log) DIV element of the page that called it. <DIV id="div2log"></DIV>

What I would like to do is include the JSON/jQuery stuff in a .js (Javascript) file on the server and only include references to this file where jQuery/AJAX is needed for any item.

I have created a js file that contains:

<script>
$(document).ready(function(){
   $("button").click(function(){
      $.ajax({url: "/cgi-bin/ajax.pl", success: function(result){
         $("#div2log").html(result);
      }});
  });
});
</script>

But I am not sure how to reference it, and pass it the params that I would have passed to a script using /cgi/script.pl?paramA=1&paramB=2&param3=3 and I am not sure how to pass it the HTML ID of the DIV that it must update with the visual result of its action on the server.

Does my question make sense?

Cheers,
Kostas

Replies are listed 'Best First'.
Re: Perl AJAX jQuery, js file
by haukex (Archbishop) on Jan 11, 2021 at 12:42 UTC
    I have created a js file that contains: ...

    .js files are not HTML files and should not contain tags, only pure JavaScript code. Also, if you want this to have maximum reusability, don't use jQuery's $(document).ready - only put JavaScript functions in the file.

    But I am not sure how to reference it

    That would be e.g. <script src="mycode.js"></script> (should be done after other dependencies like jQuery).

    pass it the params that I would have passed to a script using /cgi/script.pl?paramA=1&paramB=2&param3=3

    See jQuery's $.ajax function; I showed an example here - note that this example is regarding dynamic form submission, so the difference is that you don't have a <form>; the important part is the argument $.ajax({ data: ....

    I am not sure how to pass it the HTML ID of the DIV that it must update with the visual result of its action on the server.

    That would probably be easiest as a parameter to the JavaScript function that you define in your .js file Update: and this function is what you call from the <script> tags embedded in the HTML pages themselves.

      Useful input, Hauke! Thank you.
      -- Kostas
Re: Perl AJAX jQuery, js file
by Corion (Patriarch) on Jan 11, 2021 at 13:32 UTC

    If I remember jQuery correctly, you can extract the target element from the HTML, like the second response on Stackoverflow shows:

    $('#submitform').click(function() { $.ajax({ url: "getinfo.asp", data: { txtsearch: $('#appendedInputButton').val() }, type: "GET", dataType : "html", success: function (data){ $('#showresults').html($('#showresults',data).html()); // similar to $(data).find('#showresults') }, });

    For passing in the parameters, either pass them as the data key, or construct an URL-encoded query string and pass that to your call.

    Mojolicious may have "too much" for your current taste, but it brings a lot of convenient things to the plate.

Re: Perl AJAX jQuery, js file
by bliako (Monsignor) on Jan 11, 2021 at 21:25 UTC

    before you dive into code you perhaps need to define your requirement or rather decide how much you want to expand in the future. You show GET but surely some manager can tell you "hey POST is the way to go!". How about JSON (possibly nested) data? How about image uploads? What about the result from the ajax response? You specify result as HTML but what about when you want to indicate error? Is sending back an HTML error message enough or does your javascript success: need to act on an error code?

    To test ajax'ing back to site, what you wrote is enough. Just place it inside your HTML file which contains the button and div2log elements (I assume you don't want a js file, since you use the script tags).

    The good news is that you can skip jQuery completely because you can find pure-js ajax functionality (search for XHR) and satisfy your cheetah-fast requirement. And you can also on the back-end write something which takes in a JSON POST data and makes it perl data structure with images and all if needed. And also responds back by sending a JSON with error-code, data and html-content sections. And while you are at it, test it for unicode support too - don't leave that too late. Surely some manager will kink on the idea sooner or later.

    bw, bliako

      Great input, Bliako

      I know what you mean about jQuery not being essential and I had seen some examples of using XHR, which I understand is the Javascript way of handling AJAX and JSON.
      The reason I included jQuery in my question here, is that I was reading its documentation last night and I came across some very cool things one can do with jQuery. Like built-in HTML effects and some browser/form events handlers that would add a great "this CMS feels like a desktop app" feeling to my project

      I know I said that I like to streamline things, but... Nothing wrong with waiting for your friend to shave her armpits. :p

      Regarding your reference to GET/POST, I actually had that issue in my mind last night. I assume that the maximum GET data size of 750bytes(?) still applies to AJAX calls.
      So, yes, I am thinking of favouring POST, which would allow me to send images to the server as well. I already successfully uploaded some images over AJAX but JSON encapsulating an image seems so cruel! I mean, as if base64 wasn't bad enough!

        Actually XHR stands for XMLHttpRequest (and https://en.wikipedia.org/wiki/XMLHttpRequest). So I *guess* whatever you send, e.g. JSON, is wrapped inside an XML envelope.

        Also be advised that you do not need (depending on Browser+version) to have a Form created already in HTML in order to ajax images over. In your ajax'er function you can create the Form on the fly and add File objects (e.g. images) and JSON and all in a way similar to hash. But you definetely do not need to ASCII-fy your binary data as you can use a Blob . I do not know how they send that Blob. But, logically thinking, since they wrap it inside an XML envelope all will be ASCII-fied. Sorry for ... oh I am lost in all these zoological metaphors you used.

        This may also be of help https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data

        Just to drive my last post's point home: Create one js function to do all the ajax'ing you will ever need, with nested data structures (as JSON) and binary or other file uploads. Add all the error handling code there and of course, since it is all asynchronous you need to be prepared to supply function pointers to handling success and failure. On the server side, create a POST data "untangler" which will handle all that your ajax can send and return a complex (hash) data back with status code, data and html-or-text-or-both message. Make sure you test unicode support (e.g. for error messages or data-input or db-data-out-to-browser) through these two functions. I found Mojolicious helpful for the server-side. And as people say here, benchmark it before making any assumptions. And for the browser-side I prefered to build my AJAX function from pure-js in its own little library (js file) which now I use for all my needs. All I needed was online.

        BTW, AJAX is an acronym for Asynchronous JavaScript And XML but Ajax was the legendary greek hero maddened by some immature bunch of Gods and committed suicide out of shame, famously depicted by Exekias in this fine art specimen . And let's not go into football but Omonoia famously beat Ajax 4-0 in 1979 with a Bulgarian coach (another legend: Arsov) and all-native footballers. (allow me, oh fellow Monks, the post-festive, over-locked-down delirium).

        bw, bliako

Re: Perl AJAX jQuery, js file
by Anonymous Monk on Jan 11, 2021 at 12:36 UTC
      Looks promising...
      Thanks, dude!
      I certainly hope that spending my time to extract the logic from your Mojo code, won't force me to include Mojolicious in my CMS.
      Because the CMS is streamlined like a speeding cheetah. Even its CGI.pm and DBI.pm are written from scratch. We don't want no f^&%ing bloated code in these here, mod_perl parts! :D
      Cheers!
        I certainly hope that spending my time to extract the logic from your Mojo code, won't force me to include Mojolicious in my CMS.

        No, definitely not. Mojolicious does have its advantages though ;-P

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://11126745]
Front-paged by Corion
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others studying the Monastery: (3)
As of 2024-04-25 17:35 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found