Executing Javascript functions from an AJAX - HTML response - ajax

I have a web page that displays comments, and users can click a 'Flag' link to report an inappropriate comment.
When they click the Flag link, I use AJAX and innerHTML to display a dropdown box underneath the comment with a reason code, e.g. Spam, Offensive, Unrelated to topic, etc., as well as a Cancel button.
If the user clicks Submit, I want to use another AJAX request to send their response to a PHP file, where the database is updated, and they receive a "Thank you" on their end (without reloading the page). I essentially want the DIV that displays the dropdown box to be replaced with "Thank you" using another AJAX request.
That's where the problem is. It seems that I cannot execute an AJAX request from within the HTML response from the first AJAX request. The JavaScript functions fail -- even a simple Alert('hello world') doesn't work. I tried placing the JavaScript functions in the main page that calls the first AJAX request, as well placing it in the PHP file that displays as the HTML response from the first AJAX request, but I did not have any luck -- the functions just do not run when they are called.
Everything works fine if I load the PHP file externally, so I know the JavaScript is correct. It just doesn't work when I load the PHP file into the HTML response DIV and then call the JavaScript from there.
So to sum everything up, how do you execute JavaScript functions from the HTML response of an AJAX request?
EDIT: here is a sample of what I want to do:
This is the AJAX part that populates the DIV when the person clicks the Flag link:
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4)
{
document.getElementById(whichdiv).innerHTML=xmlhttp.responseText;
}
};
The value of xmlhttp.responseText comes from this external file:
<input type="hidden"/>
<script type="text/javascript" language="javascript">
function displayalert()
{
alert ('Hello World!');
}
</script>
<form name="myform" id="myform">
<input type="text" name="myfield" value="teststring"/><br/>
<input type="button" name="button" value="Submit"
onclick="displayalert();"/>
</form>
Note: the <input type="hidden"/> above comes from a suggestion I found off of http://msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx.
When the user clicks the button, the javascript displayalert() function doesn't run. The alert box never pops up. If I load the file externally instead of calling it with innerHTML, the script works fine.
Can the xmlhttp.responseText contain JavaScript code?

depends on the browser:
IE doesnt support scriptEval on html that is loaded with ajax, which means that if you have script blocks in your html, they wont be called.
Firefox supports script eval.
What i usually do is shove some json into an input, then check if the browser supports scriptEval, if it doesnt, pull the json, eval it, and call some method passing json.
if the browser supports scriptEval, i also include a script block that contains a call to the same method with the json.
you may also want to read this:
http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html

Related

codeignighter redirect issues to refresh

I have a registration page.after completing the registration the user will redirect to a new page. In new page when I click the back button I redirect to last page with last data filled up.how to refresh the page to delete form data. The framework is codeignighter.
To refresh or redirect page in codeigniter there is function redirect(YOUR_URL).
Have a Look in Helper class for more details
If you are referring to browser back button keep autocomplete off for the form fields in your first form
You can use autocomplete for the complete form
<form action="/action_page.php" autocomplete="off">
Or specifically to each control as
<input type="email" name="email" autocomplete="off">
You can also make it on for specific controls/entire form if you need it
if your problem still persists you could use
<body onload="document.refresh();">
This shall refresh the page on loading for the first time
include this in your page if required to force reset the form on load if you need you can bind this with a javascript onload function
<script type="text/javascript">
document.getElementById("myForm").reset();
</script>
in case of application back button {if used with href or redirect()}
Shall keep form clean even if autocomplete is not set unless the user takes from browser autofill or you fill them with code

Radbutton Onclick mozilla bug

When i click a radbutton then postback changing page url as /blabla.aspx?btnMsg_ClientState=&btnCarDetails=Sorgula&btnCarDetails_ClientState=&btnPrice_ClientState=&btnReject_ClientState=# ..
First pop-up work but then break.
There are 5 extra buttons and seems all in page url. Where is coming these query strings ?
Ie Developer tools says:
ScriptResource.axd...
I cant find solution, please help.
It appears that the form on your page is configured to use a GET request when submitted.
<form id="form1" runat="server" method="get">
In this case all parameters on the page are specified as part of the URL, which includes the input elements that are used for rendering the button, as well as the other input elements on your page.
You can change this behavior by setting the method attribute of the form to post, so that a POST request is utilized for submitting the form.
<form id="form1" runat="server" method="post">
In this case the parameters will be passed in the message body of the HTTP request.

Grails formRemote redirects rather than to just call method

I'm new to Grails and got some problem with the g:formRemote command..
I want a g:textArea box send a message to my controller and save this messages.
After that the page should be updated via the formRemote Ajax, so that the messages appear on the page.
But instead of updating the page, the formRemote call assumes the given url to be a real link and wants me to redirect to this (non-existing) .jsp site.
The Method I want to start is called in my controller tho
I tried many solutions offered in similar problems, but it seems this problem is different from theirs
Heres the code:
<div id="history">
<g:render template="posts" collection="${ messages }" var="message" />
</div>
<div class="postMessageForm">
<g:formRemote name="postChatMessage" url="[controller: 'meetingRoom',
action: 'postMessage']" update="history">
<div class="msg_box">
<g:textArea name="message" value="" style="width: 630px"/><br/>
</div>
<div style="float: right;">
<g:submitButton name="Send" style="width: 90px; height: 40px;"/>
</div>
</g:formRemote>
</div>
and this is the Action which is called in my MeetingRoomController:
def postMessage() {
if (params.message != "") {
def thisUser = lookUpUser()
def thisRoom = thisUser.joinedRoom
def chatPost = new ChatPost(
message: params.message,
author: thisUser
)
thisRoom.addToChatHistory(chatPost)
}
// def messages = currentChatHistory()
// render template: 'posts', collection: messages, var: 'message'
I saw this kind of approach in Jeff Browns Twitter tutorial.
Possible failures i am seeing:
the out-commented render template command has something to do with the Ajax (When I do not comment it the only thing that happens is that the template posts will be rendered on the redirected page
usage of both Ajax and jQuery (But i dont believe that can be the point because I just have used g: and groovy stuff and havent even imported a jQuery lib)
this could be easier with remoteFunction (I dont really know how to get the remoteFunction work in this case tho)
I hope this information is enough to let someone see what I am missing
When the submit button is clicked on your form, the data is sent to the method listed in the url parameter of the formRemote tag. Then you are inside that method, you get to the commented out render tag that outputs data back to the gsp page in the div mentioned in the update tag of the formRemote tag.
formRemote relies upon a javascript library to handle the ajax stuff as mentioned in the grails documentation:
7.7.1 Ajax Support
By default Grails ships with the jQuery library, but through the
Plugin system provides support for other frameworks such as Prototype,
Dojo:http://dojotoolkit.org/, Yahoo UI:http://developer.yahoo.com/yui/
and the Google Web Toolkit. This section covers Grails' support for
Ajax in general. To get started, add this line to the tag of
your page:
You can replace jQuery with any
other library supplied by a plugin you have installed. This works
because of Grails' support for adaptive tag libraries. Thanks to
Grails' plugin system there is support for a number of different Ajax
libraries including (but not limited to):
jQuery Prototype Dojo YUI MooTools
So remove what is in the history div, uncomment the two lines in your postMessage method, and include one of the referenced javascript libraries.

How to store to browser auto-complete/auto-fill when using AJAX calls

I've noticed that browsers do not store form values until the form is submitted, which means that if you're using AJAX instead of a standard form submit, your browser's auto-fill is never populated. Is there a way to force populate your browsers auto-fill/auto-complete so that I can have this convenience with forms that are submitted via AJAX? It's annoying to go to my AJAX page and have to type in the same things in the form fields every time because the browser doesn't remember them.
My question is pretty much identical to the this one, except that only a work around in FireFox is provided as the accepted answer to that question. I'm looking for a solution that works in all major browsers (at least Chrome, FF, and IE), if there is one.
Note: I am not talking about AJAX auto-complete plugins, which is what almost always pops up when googling this question. I am talking about your browser's built-in auto-complete or auto-fill that helps you fill out forms by remembering what you entered in the past.
For anyone who's still trying to solve this, seem like I've found the answer.
Chromium tries to recognize the submit event, even if you preventDefault and handle the actual submission yourself.
That's it, you need to preventDefault the submit event, not the click event.
This worked on Chrome, Edge and IE 11 at the time of writing (I'm too lazy to download and test it on Firefox).
Here's your form:
<form method="POST" id="my-form">
<label>Email</label>
<input autocomplete="email" type="email" name="email">
<button type="submit">Subscribe</button>
</form>
Notice the autocomplete attribute. These are all the possible values that you can use for autocomplete.
In JavaScript, simply do this:
$("#my-form").on("submit", function (ev) {
ev.preventDefault();
// Do AJAX stuff here
});
The browser will remember whatever email you've entered on clicking subscribe button.
I have also come across this; there doesn't seem to be a great solution, certainly not a cross browser one, but here is one for IE I haven't seen anyone mention:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<SCRIPT>
function subForm()
{
window.external.AutoCompleteSaveForm(f1);
f1.submit();
}
</script>
</HEAD>
<BODY>
<FORM id=f1>
User ID : <input type=text name=id></input><br>
Password :<input type=password name=pw></input><br>
E-mail :<input type = text VCARD_NAME = "vCard.Email"> <br>
<input type=button value=submit onclick="subForm()">
</FORM>
</BODY>
</HTML>
From: http://support.microsoft.com/kb/329156
Use this Method:
AutoCompleteSaveForm = function(form){
var iframe = document.createElement('iframe');
iframe.name = 'uniqu_asdfaf';
iframe.style.cssText = 'position:absolute; height:1px; top:-100px; left:-100px';
document.body.appendChild(iframe);
var oldTarget = form.target;
var oldAction = form.action;
form.target = 'uniqu_asdfaf';
form.action = '/favicon.ico';
form.submit();
setTimeout(function(){
form.target = oldTarget;
form.action = oldAction;
document.body.removeChild(iframe);
});
}
Tested with ie10, ff latest, chrome latest
Test yourself: http://jsbin.com/abuhICu/1
Have you try the answer of my question that you mention?
The answer is using hidden iframe but seems he claim the idea is not working on IE and Chrome on that time.
Try to take the idea, and instead of using hidden iframe, just put the username/password/submit visible input element in a form POST, in an iframe. So user will enter login details directly into iframe. With proper Javascript you can put loading image, get success or denied from server and update the parent or the whole page. I believe it should work on any browser.
Or if you still want to use AJAX since you probably implemented the API on server side. You can make the iframe to just send a dummy POST at the same time send the real user/pass to AJAX URL.
Or back to use hidden iframe, not to hide it but move it to the invisible area like top: -1000px.
After several hours searching, I found a solution at Trigger autocomplete without submitting a form.
Basically, it uses a hidden iframe in the same page, set the action of your form to the 'src' of the iframe, and add a hidden submit button inside the form, when user clicks your button which triggers AJAX requests, you should programmatically click the hidden button before sending the AJAX request. see example below:
In your form page:
<iframe id="hidden_iframe" name="hidden_iframe" class="hidden" src="/content/blank"></iframe>
<form target="hidden_iframe" method="post" action="/content/blank" class="form-horizontal">
<input type="text" name="name">
<input type="text" name="age">
....
<button id="submit_button" type="submit" class="hidden"></button>
<button id="go_button" type="submit" class="hidden">Go</button>
</form>
Then java script:
$('#go_button').click(function(event){
//submit the form to the hidden iframe
$('#submit_button').click();
//do your business here
$.ajax(function(){
//whatever you want here
}})
);
Hope this helps.

firing href link for download and .click event with $.post() with jquery

im trying to have one link for a file download and at the same time submit a post form over ajax.
kinda looks like this:
<form action="" method="post" id="form">
<input type="text" name="email" id="email" value="" />
<input type="hidden" name="subscriber" id="subscriber" value="newsletter" />
trial download
</form>
<script type="text/javascript" src="jquery"></script>
<script type="text/javascript">
// prevent default submit action caused by enter key etc.
$("#form").bind('submit',function(event){event.preventDefault();});
$('#download').click(function(){
$.post(location.href, $('#form').serialize(), function(){
$('#form').hide();
});
});
</script>
problem is that the download fires and it shows the download dialog - which is correct - it also fires the click event and would even console log inside the click event function, it on top even fires the post request but the post request never ends up at the server. i had the access log file on tail -f and it only shows the GET on the application.exe but no POST from the $.post(). in firebug it shows the POST http://ip/folder/ given by the location.href and its marked in red with a little X and an empty response field. tough for firebug it looks like it got sent to the server...
my explanation for this is that the href takes the wind out of the $.post() and before it gets fired it redirects the browser to the download file. doesnt change the page itself but stops the action of posting over XHR...
does anyone know a good workaround for this? i really need the native href link to the application to not cause IE to bring up this stupid file download warning bar and at the same time i need the ajax to submit the form...
thanks!
Refactor as follows, returning false to prevent the default link click behavior:
$('#download').click(function(){
var href = $(this).attr('href');
$.post(location.href, $('#form').serialize(), function(){
$('#form').hide();
document.location.href= href;
});
return false;
});
to give one answer that works to my own question:
$('#download').click(function(){
setTimeout(function(){
$.post(location.href, $('#form').serialize(), function(){
$('#form').hide();
});
},1000);
});
the timeout fires the .post after the download request is fired... sortof works... but i dont know if thats a good solution or if that might fail 50% of the time & browser...

Resources