Link to home
Start Free TrialLog in
Avatar of Brian Sammis
Brian Sammis

asked on

AJAX RESPONSE TO DIV OR ALERT

I am using the following AJAX POST script. When I get a response back from the post, I want that response
to show on an alert or div box that shows on the middle of the screen.

I also have this page working using a normal post (non ajax option). I currently have the response appearing
in a popup *target and that works for that earlier post method, but I am not sure how to do this with ajax/jquery.
I've seen some methods, but have not gotten anything to work.

Here is my current working script. (except the response portion that is not working, and the URL, is omitted (JSP page)

The goal of this page is too collect a punch from an employee and post that punch to a JSP script. If I use an iframe
on my earlier post method (form) it says, the JSP page denies the information from posting there.. but a Popup
does work fine.


<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>EE // 29185693</title>

<script
  src="https://code.jquery.com/jquery-3.5.1.min.js"
  integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
  crossorigin="anonymous"></script>


<script>
        $(function() {
            $('button.submit').click(function(e) {
                e.preventDefault()

                $('input[name=T1]').val( $(this).val() )

                $.ajax({
                    method : 'post',
                    url : 'URL.JSP',
                    data : $('#formID').serialize(),
                }).done((response) => {
                    $('#response').html(response);
                })
            })
        });
        </script> 

<script>
function getTime() {
    var dateObject = new Date();
    var dateString = dateObject.toLocaleString();
    document.getElementById("clock").value = dateString;
}
var repeatedTime = setInterval(getTime, 1000);

</script>
</head>
    
<script>
window.onload = function() {
  var input = document.getElementById("BadgeID").focus();
}
</script>
    
    <body>

        <form id='formID'>
            <input type='hidden' name='ACTION' value='IMP'>
            <input type='hidden' name='CompName' value='HTA'>    
            <input type='hidden' name='CompPassword' value='123456'>
            <input type='hidden' name='T1'>

            <label for='demo-numpad-1'>Badge #</label>
            <input type='text' name='BadgeId' id='BadgeID'>

            <label for='clock'>Date/Time</label>
            <input class='editFormText' type='text' id='clock' name='DateTime' value=''>

            <button class='submit' value='In'>Punch In</button>
            
            
            
            <button class='submit' value='Out'>Punch Out</button>
        </form>

        <div id='response'></div>

    </body>
</html>

Open in new window

Avatar of leakim971
leakim971
Flag of Guadeloupe image

nothing wrong with the Ajax part.
maybe the other code, this timer running before the DOM is fully loaded
some cleaning, should work perfect or you URL.JSP don't want to talk :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EE // 29185693</title>
    <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
    <script>
        $(function() {
            $("#BadgeID").focus();
            setInterval(() => $("#clock").val(new Date().toLocaleString()), 1000);
            $('button.submit').click(function(e) {
                e.preventDefault()
                $('input[name=T1]').val($(this).val());
                $.post('URL.JSP', $('#formID').serializeArray()).done((response) => {
                    $('#response').html(response);
                });
            });
        });
    </script>
</head>
<body>
<form id='formID'>
    <input type='hidden' name='ACTION' value='IMP'>
    <input type='hidden' name='CompName' value='HTA'>
    <input type='hidden' name='CompPassword' value='123456'>
    <input type='hidden' name='T1'>
    <label for='demo-numpad-1'>Badge #</label>
    <input type='text' name='BadgeId' id='BadgeID'>
    <label for='clock'>Date/Time</label>
    <input class='editFormText' type='text' id='clock' name='DateTime' value=''>
    <button class='submit' value='In'>Punch In</button>
    <button class='submit' value='Out'>Punch Out</button>
</form>
<div id='response'></div>
</body>
</html>

Open in new window


Hey Brian,

For a popup, you might want to look at the Modal options available in either the Bootstrap framework or the jQuery UI plugin. Both of these offer you an easy way to create pop-ups (modal dialogs), but they do involve adding additional libraries.

https://getbootstrap.com/docs/4.0/components/modal/

https://jqueryui.com/dialog/

There are other popup libraries available, or you could do this with your own Javascript and CSS if you don't want to add additional libraries.

Whichever route, you take, you'd want to initiate the popup dialog from within the success handler of your AJAX request (the done method)

}).done((response) => {
    // init your dialog here
    $('#response').html(response)   
})

Open in new window

Avatar of Brian Sammis
Brian Sammis

ASKER

Thanks for all the feedback.. I'll review, test and respond soon.. 
A popup works on the Non Ajax Post method, but a Div Response no go.. so maybe the JSP
has some limits on what it'll post a response to.. I'll plug away at it more tomorrow.

I am getting this error on the console.

Access to XMLHttpRequest at URL.jsp' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
jquery-3.5.1.min.js:2 POST URL.jsp net::ERR_FAILED  

Chris, Thanks for the options. I will really look into that. Looks really good for some of what I need.

LeaKim971, the code revision really works well, simplified.. very cool. Thank you!

I'll check in tomorrow after I work more on this.. perhaps I'll get this to work.. I wonder why I can get a popup using a Target=Popup on the non ajax Post Method. I use a script of what is below.. and it works and I get a good response back from the JSP server script. I run this script below and it gets the popup and I target the post to the popup.. so I get the response there, but not yet with the DIV..

onmousedown="window.open('about:blank','popup','menubar=no,scrollbars=no,resizable=no,width=350,height=300,left=800,top=300')

I am more experienced with older methods html 4.. Have not done this in a while.

Thank you. 
A popup is a very simple thing to implement - you can read about how to do it here https://www.experts-exchange.com/articles/28838/Create-a-responsive-confirmation-popup-using-HTML-CSS-jQuery-and-Promises.html

An alternative method is given below. This method creates the popup from scratch rather than using a template and is presented as a function that can be invoked to display an alert type dialog.

CSS
.overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0,0,0,.85);
  z-index: 100000;
}
.popup-dialog {
  background-color: white;
  display: inline-block;
  left: 50%;
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  padding: 0 15px;
}
.popup-title {
  border-bottom: 2px solid #aaa;
  margin-left: -15px;
  margin-right: -15px;
  padding-left: 15px;
  padding-top: 10px;
  padding-bottom: 10px;
  margin-top: 0;
  margin-bottom: 0;
  font-size: 21px;
}
.popup-body, .popup-footer {
  padding-top: 15px;
  padding-bottom: 15px;
}
.popup-footer {
  margin-left: -15px;
  margin-right: -15px;
  padding-left: 15px;
  padding-right: 15px;
  text-align: right;
}

Open in new window

JavaScript
function Popup(title, message) {
  var overlay = document.createElement('div');
  overlay.classList.add('overlay');
  
  var popup = document.createElement('div');
  popup.classList.add('popup-dialog');
  overlay.appendChild(popup);
  
  var dlgTitle = document.createElement('h2');
  dlgTitle.classList.add('popup-title');
  dlgTitle.innerHTML = title;
  popup.appendChild(dlgTitle);
  
  var dlgBody = document.createElement('div');
  dlgBody.classList.add('popup-body');
  dlgBody.innerHTML = message;
  popup.appendChild(dlgBody);
  
  var dlgFooter = document.createElement('div');
  dlgFooter.classList.add('popup-footer');
  
  var closeBtn = document.createElement('button');
  closeBtn.innerHTML = 'Close';
  
  dlgFooter.appendChild(closeBtn);
  document.body.appendChild(overlay);
  
  popup.appendChild(dlgFooter);
  return new Promise(function(res, rej) {
      closeBtn.onclick = function() {
        overlay.remove();
        res(true);
      }  
  })
}

Open in new window

HTML
<div class="w-50">
<input class="form-control" id="title" placeholder="title">
<input class="form-control" id="message" placeholder="message">
<button class="btn btn-primary" id="showDialog">Open</button>
</div>

Open in new window


Invoking the Dialog
$(function() {
  Popup('Title of the dialog', 'This is the message that will be displayed');
  var title = document.getElementById('title');
  var message = document.getElementById('message');
  
  $('#showDialog').click(function() {
    Popup(title.value, message.value).then(function() {
        title.value = '';
        message.value = '';
    });
  });
});

Open in new window

Working sample here


Hi Julian,

Thanks for this feedback. I am looking also at your post below.. because I am trying to have the response from the server show up in a DIV. I'll review both what you gave here and that additional post. The URL.JSP does respond in a Regular Post Method, but I am having trouble with the Ajax Post Method and directing the response to a Div. 

/AJAX-form-submission-with-customized-server-field-validation.html
replace :
$('#response').html(response);
by :
$('#response').html("<h1>MY RESPONSE START HERE</h1>" + response + "<h1>ENDS HERE</h1>");

now if you don't see anything between start and end don't look up on the script of your page but on your server code.
Hi Chris, I am still looking at what you mentioned..LeaKim971 provided a great adjustment to my script and it's helped, but I am unsure of the script that is needed to have a popup from the server response. I can do it with a regular post (non-ajax because I can set a target= popup and call the popup window as I get the response. I don't know the code so well with ajax (still learning)

        $(function() {
            $("#BadgeID").focus();
            setInterval(() => $("#clock").val(new Date().toLocaleString()), 1000);
            $('button.submit').click(function(e) {
                e.preventDefault()
                $('input[name=T1]').val($(this).val());
                $.post('https://Punch.jsp',
                $('#formID').serializeArray()).done((response) => {
                    $('#response').html(response);
                });
            });
        });
    </script>
Hi Leakim971, I am reviewing and applying your guidance.. I'll test now.
Hey Brian,

Out of interest, is the script you're POSTing to on a different domain. You mentioned a CORS error and this is usually an indication that you're trying a Cross Origin request (making a request from one server to a different one). If that is the case, then you'll need to sort that out before you even think about Modal Popups, otherwise you won't get a response from the remote server.
take a look to : https://jqueryui.com/dialog/ 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EE // 29185693</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" integrity="sha256-rByPlHULObEjJ6XQxW/flG2r+22R5dKiAoef+aXWfik=" crossorigin="anonymous" />
    <style>
        #response {
            display: none;
        }
    </style>
</head>
<body>
<form id='formID'>
    <input type='hidden' name='ACTION' value='IMP'>
    <input type='hidden' name='CompName' value='HTA'>
    <input type='hidden' name='CompPassword' value='123456'>
    <input type='hidden' name='T1'>
    <label for='demo-numpad-1'>Badge #</label>
    <input type='text' name='BadgeId' id='BadgeID'>
    <label for='clock'>Date/Time</label>
    <input class='editFormText' type='text' id='clock' name='DateTime' value=''>
    <button class='submit' value='In'>Punch In</button>
    <button class='submit' value='Out'>Punch Out</button>
</form>
<div id='response'></div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" integrity="sha256-KM512VNnjElC30ehFwehXjx1YCHPiQkOPmqnrWtpccM=" crossorigin="anonymous"></script>    <script>
    $(function() {
        $("#BadgeID").focus();
        setInterval(() => $("#clock").val(new Date().toLocaleString()), 1000);
        $('button.submit').click(function(e) {
            e.preventDefault()
            $('input[name=T1]').val($(this).val());
            $.post('URL.JSP', $('#formID').serializeArray()).done((response) => {
                $('#response').html(response);
                $("#response").dialog();
                // $('#response').html(response).dialog(); // short version of two previous lines
            });
        });
    });
</script>
</body>
</html>

Open in new window


Hi Chris.. Yes that is a problem I am dealing with. I don't have any control over that server or script (jsp).. I didn't realize that it's the reason I can't get a response. With the standard post method, a popup window (non-div) works great..

So, I have to somehow get over that hurdle first. emm.. I wish there was some client side code I could use on correcting that, but I only have seen some php/c# codes with regard to controling error. Maybe I could submit a ticket to the Developer of that jsp server script and see if there is anything they can do.   
Hi LeaKim971, now reviewing your new post.. Thanks.
Hi Chris,

When I am running this script.. I am running from my local PC/desktop. I use the form and submit a punch and it does send that punch to the database. A punch lands on the timesheet nicely.. but I still get that CORS error, although the punch goes through.

All of you have been so helpful. I hope to learn more. When I was on Experts Exchange and doing some development of Forms, etc.. Points were awarded differently. I could split up points, but now I am not sure how it works. I'll review that. I appreciate so much, all your help. It means a lot. I've make good progress with this, in having a working form at least. I'll just have to keep working on the response part. 

Using a normal Post this is what I have working (older HTML) and this works.. (Non-AJAX method)


<form method='POST' name='TheForm' id="formID" action='https://...Punch.jsp'  target="popup">

<input type='button' class='button' name='ImportPunch' value='Punch In'

onfocus="document.forms[0].elements['PunchType'].value = 'Out';return true;"
onmouseup="document.getElementById('BadgeID').value = '';document.getElementById('BadgeID').focus();"
onmousedown="window.open('about:blank','popup','menubar=no,scrollbars=no,resizable=no,width=350,height=300,left=800,top=300')
document.getElementById('formID').submit();"
Hmmm - if you don't have any control over the CORS policy of the remote sever, then you may struggle to get a simple AJAX request working. Often a way around this is to create your own server-side script (using PHP for example). Your AJAX code then calls your own server-side script (instead of the remote-server script), which in turn makes the request to the remote server (using curl for example) and receives a response. Your server script then sends that response back to your AJAX request. A bit more complicated because you're introducting a new step, but ultimately, you may not have a choice.
Yeah - normal POST requests are not subject to the same CORS policies as AJAX requests - if you look at your earlier error:

Access to XMLHttpRequest at URL.jsp' from origin 'null' has been blocked by CORS policy.

This is telling you that AJAX requests are blocked. My previous comment mentioned a curl request from your own server - this isn't an AJAX request - it's a standard POST request (similar to your original FORM submission) so that would work. Because you'd be doing the AJAX request to your own server, you wouldn't have the CORS issue.

Are you saying, it's possible to use a curl request actually as part of my script/Html vs. the Ajax request and get the job done that way ?  I just starting getting familiar with curl and did some basic tests/requests. Sorry that I am not very skilled in this yet. I appreciate your patience and the insights you've given.

Thanks,
it's so strange that Ajax requests are blocked, but then the punch still goes through.. maybe some things
are blocked, but the data is still allowed. 
ASKER CERTIFIED SOLUTION
Avatar of Chris Stanyon
Chris Stanyon
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks for all your help.