Load Dojo form from ajax call - ajax

I am trying to implement something like this.
http://app.maqetta.org/mixloginstatic/LoginWindow.html
I want the login page to load but if you click the signup button then an ajax will replace the login form with the signup form.
I have got this to work using this code
dojo.xhrGet({
// The URL of the request
url: "'.$url.'",
// The success callback with result from server
load: function(newContent) {
dojo.byId("'.$contentNode.'").innerHTML = newContent;
},
// The error handler
error: function() {
// Do nothing -- keep old content there
}
});'
the only problem is the new form just loads up as a normal form, not a dojo form. I have tried to return some script with the phaser but it doesnt do anything.
<div id="loginBox"><div class="instructionBox">Please enter your details below and click <a><strong>signup</strong>
</a> to have an activation email sent to you.</div>
<form enctype="application/x-www-form-urlencoded" class="site-form login-form" action="/user/signup" method="post"><div>
<dt id="emailaddress-label"><label for="emailaddress" class="required">Email address</label></dt>
<dd>
<input 0="Errors" id="emailaddress" name="emailaddress" value="" type="text"></dd>
<dt id="password-label"><label for="password" class="required">Password</label></dt>
<dd>
<input 0="Errors" id="password" name="password" value="" type="password"></dd>
<dt id="captcha-input-label"><label for="captcha-input" class="required">Captcha Code</label></dt>
<dd id="captcha-element">
<img width="200" height="50" alt="" src="/captcha/d7849e6f0b95cad032db35e1a853c8f6.png">
<input type="hidden" name="captcha[id]" value="d7849e6f0b95cad032db35e1a853c8f6" id="captcha-id">
<input type="text" name="captcha[input]" id="captcha-input" value="">
<p class="description">Enter the characters shown into the field.</p></dd>
<dt id="submitButton-label"> </dt><dd id="submitButton-element">
<input id="submitButton" name="submitButton" value="Signup" type="submit"></dd>
<dt id="cancelButton-label"> </dt><dd id="cancelButton-element">
<button name="cancelButton" id="cancelButton" type="button">Cancel</button></dd>
</div></form>
<script type="text/javascript">
$(document).ready(function() {
var widget = dijit.byId("signup");
if (widget) {
widget.destroyRecursive(true);
}
dojo.parser.instantiate([dojo.byId("loginBox")]);
dojo.parser.parse(dojo.byId("loginBox"));
});
</script></div>
any advice on how i can get this to load as a dojo form. by the way i am using Zend_Dojo_Form, if i run the code directly then everything works find but through ajax it doesnt work. thanks.
update
I have discovered that if I load the form in my action and run the __toString() on it it works when i load the form from ajax. It must do preparation in __toString()

Firstly; You need to run the dojo parser on html, for it to accept the data-dojo-type (fka dojoType) attributes, like so:
dojo.parser.parse( dojo.byId("'.$contentNode.'") )
This will of course only instantiate dijits where the dojo type is set to something, for instance (for html5 1.7+ syntax) <form data-dojo-type="dijit.form.Form" action="index.php"> ... <button type="submit" data-dojo-type="dijit.form.Button">Send</button> ... </form>.
So you need to change the ajax contents which is set to innerHTML, so that the parser reckognizes the form of the type dijit.form.Form. That said, I urge people into using a complete set of dijit.form.* Elements as input fields.
In regards to:
$(document).ready(function() {});
This function will never get called. The document, youre adding innerHTML to, was ready perhaps a long time a go.
About Zend in this issue:
Youre most likely rendering the above output form from a Zend_ Dojo type form. If the renderer is set as programmatic, you will see above html a script containing a registry for ID=>dojoType mappings. The behavior when inserting <script> as an innerHTML attribute value, the script is not run under most circumstances (!).
You should try something similar to this pseudo for your form controller:
if request is ajax dojoHelper set layout declarative
else dojoHelper set layout programmatic

Related

Make browsers remember input fields without submitting (or having at all) a form?

I have a web application based on bootstrap (so, using jquery), and I'm trying to convert a classic html form-based search form to an ajax search form (to avoid page reload).
In the classic form-based, the button sends the html form as post, and the action page returns a table of results below the same form.
something like:
<form action="/search" method="post">
<input type="text" name="searchterms">
<button type="button" onclick="submit();">Search!</button>
</form>
In the ajax version, there is no form, but just a text field and the button calls a dosearch() function which makes an ajax request to a back end script which return search results, which are then used in a target DIV, showing a table of results, below the search input+button.
<input type="text" name="searchterms">
<button type="button" onclick="dosearch();">Search!</button>
Both work fine, but the second way avoid the browser to "collect" previously used search terms - I guess because there's no "submit".
My users like this "previous search terms" suggestion, and I would like to add it back, if possible, in the search "ajax" form.
I also tried to create an html form anyway, which encloses the input and the button, adding this event to its tag:
onSubmit='dosearch();return false;'
(if I don't return false, the form is submitted and action page loaded), like:
<form onsubmit='dosearch();return false;'>
<input type="text" name="searchterms">
<button type="button" onclick="dosearch();">Search!</button>
</form>
but even this seems not to work: new search terms are not "remembered" and suggested typing in the field...
I thought maybe my dosearch() function could add (most recent) search terms into a session/cookie but then I would need to read those stored values and create, each time, a sort of "dropdown" list for the input field, just as browsers usually do automatically... it should be not complicated but probably overkill...
Is there any way to make browsers "remember" inserted values even without submit? If not, what workaround is best/easiest?
edit: I've just found this
input remembered without using a form
but maybe after 5 years something changed?
I just tried to change the "button" type, to a "submit", and in this way it seems to work... page is not reloaded, ajax fills the results div and my new terms are remembered...
like:
<form onsubmit='dosearch();return false;'>
<input type="text" name="searchterms">
<button type="submit" >Search!</button>
</form>
it seems that if the "submit" is triggered through a "submit" button (even if it return false) the browsers stores input field values...
you need to do with ajax
<form onsubmit='dosearch();return false;'>
<input type="text" name="searchterms" id="searchTerm">
<button type="button" onclick="dosearch();">Search!</button>
<script type="text/javascript">
function dosearch(){
val = $("#searchTerm").val();
$.ajax({
url: "LoadProduct.php?val ="+val,
type: "GET",
processData: false,
contentType: false,
}).done(function(respond){
$("#LoadProductTd"+no).html(respond);
$(".chzn-select").chosen(); $(".chzn-select-deselect").chosen({allow_single_deselect:true});
});
}
</script>
so you can create LoadProduct.php file and in file you will get your search term n $_GET['val']
so you can use this for your query

send multipart form with ajax - send file and text

i need to send some data and an image file with ajax .
i know that must use multipart form and formdata but i don't know how - i googled it and i found some way for send file, but i need to send whole form.
this is my html form
<form id="formData" enctype="multipart/form-data">
<input type="file" id="uploader" name="image" accept="image/jpg, image/jpeg, image/png, image/bmp, image/raw"/>
<input type="hidden" name="action" id="action" value="receiver"/>
<input type="hidden" name="route" id="route" value="image"/>
</form>
thanks.
Hope something like this might do it for you mate... :)
html
//Include this script in head
<script src="http://malsup.github.com/jquery.form.js"></script>
The jQuery Form Plugin allows you to easily and unobtrusively upgrade HTML forms to use AJAX. The main methods, ajaxForm and ajaxSubmit, gather information from the form element to determine how to manage the submit process. Both of these methods support numerous options which allows you to have full control over how the data is submitted
<div id='preview'></div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
<input type="file" name="photoimg" id="photoimg" />
</form>
Script File
$('#photoimg').on('change', function()
{
$("#imageform").ajaxForm({target: '#preview', //Shows the response image in the div named preview
success:function(){
},
error:function(){
}
}).submit();
});
ajaximage.php
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
$tmp = $_FILES['photoimg']['tmp_name'];
$path = "uploads/";
move_uploaded_file($tmp, $path.$name) //Stores the image in the uploads folder
}
You could get the values of fields like action,route etc using $_POST inside the php file.For mare details check the below link mate.. :)
http://malsup.com/jquery/form/#ajaxForm

How to show flash.message in Grails after AJAX call

I want to show some flash message after completion of AJAX call. I am doing like this ..
Controller Action --
def subscribe()
{
def subscribe = new Subscriber()
subscribe.email = params.subscribe
if (subscribe.save())
{
flash.message = "Thanks for your subscribtion"
}
}
View Part --
Subscribe :
<g:formRemote onSuccess="document.getElementById('subscribeField').value='';" url="[controller: 'TekEvent', action: 'subscribe']" update="confirm" name="updateForm">
<g:textField name="subscribe" placeholder="Enter your Email" id="subscribeField" />
<g:submitButton name="Submit" />
</g:formRemote >
<div id="confirm">
<g:if test="${flash.message}">
<div class="message" style="display: block">${flash.message}</div>
</g:if>
</div>
My AJAX working fine but it is not showing me flash.message. After refresh page it displaying message. How to solve it ?
When you use ajax your page content isn't re-parsed, so your code:
<g:if test="${flash.message}">
<div class="message" style="display: block">${flash.message}</div>
</g:if>
will not run again.
So I agree with #James comment, flash is not the better option to you.
If you need to update your view, go with JSON. Grails already have a converter that can be used to this:
if (subscribe.save()) {
render ([message: "Thanks for your subscribtion"] as JSON)
}
And your view:
<g:formRemote onSuccess="update(data)" url="[controller: 'TekEvent', action: 'subscribe']" name="updateForm">
<g:textField name="subscribe" placeholder="Enter your Email" id="subscribeField" />
<g:submitButton name="Submit" />
</g:formRemote >
<script type='text/javascript'>
function update(data) {
$('#subscribeField').val('');
$('#confirm').html(data.message);
}
</script>
You have couple options,
First you can try to return the message from your controller in a form of json or a map and render it on the screen your self using javascript libraries, which is a bit different if you want to use Grails ajax tags.
The other option is using a plugin like one-time-data , which
Summary A safe replacement for "flash" scope where you stash data in
the session which can only be read once, but at any point in the
future of the session provided you have the "id" required.
Description
This plugin provides a multi-window safe alternative to flash scope
that makes it possible to defer accessing the data until any future
request (so long as the session is preserved).
more
Hope it helps

Jquery Mobile - search input has no value on post after AJAX loaded content

I am having an issue where when a page is loaded via Ajax, I don't have a value in my search input. Here is my HTML:
<form id="searchForm" action="javascript:;" method="post">
<div>
<input type="search" name="search-mini" id="search-mini" value="" data-mini="true" />
<input type="submit" data-mini="true" value="Search" />
</div>
</form>
The reason we have an input button is because of a request from the client as they found people having scenarios where they would click "Done" on the IOS keyboard rather than "Search" which wouldn't submit the form. here is my Javascript that handles the submit:
$(document).on('submit', '#searchForm', function () {
var text = $("#search-mini").val();
text = encodeURIComponent(text);
window.location.href = "/Mobile/Browse/Text?text=" + text;
return true;
});
This all runs fine if I refresh the page so the content is not loaded via AJAX. It only fails when linking between pages and they are loaded by AJAX. Alerting out "text" has a blank value in this scenario.
I have read about using JQM initialization events such as 'PageInit' instead of DOM ready() I just need an example implementing this with my code if this is the correct approach?
Regards,
Danny

Autofocus Attribute of HTML5 does not work only in FireFox when <Form><input> are loaded via Ajax. WHY?

Below is the form which i loaded via ajax. When i run the form page directly then autofocus on c_name works in firefox but when loaded with ajax it doesn't! It works fine with opera/safari/chrome though!
<form action="client_entry_action.php" method="post" id="client_entry_form" name="client_entry_form">
<fieldset id="client_info_1">
<label for="c_name">Name:</label>
<input type="text" name="c_name" required placeholder="Name" autofocus="autofocus" />
<label for="c_phone">Phone Number:</label>
<input type="tel" name="c_phone" required placeholder="Mobile/Phone Number" />
<label for="c_email">Email:</label>
<input type="email" name="c_email" required placeholder="email#example.com" />
<label for="c_address">Address:</label>
<textarea name="c_address" ></textarea>
</fieldset>
<fieldset id="client_info_2">
<label for="c_info">Additional notes:</label>
<textarea name="c_info" ></textarea>
<input type="submit" name="add_client" value="Add Client" />
</fieldset>
</form>
Autofocus is only done before onload has fired; it's meant to be a declarative way of specifying focus on initial page load.
use settimeout after ajax call on the div, or using jquery use .ajaxComplete, or .done
function theAjax(){
//after the ajax actions loaded......
//use settimeout to refocused on the input..
var t=setTimeout("focusMe()",500);
}
function focusMe(){
document.getELementById("theInput").focus(); //the new input
}
//using jquery use .ajaxComplete, or .done
$( document ).ajaxComplete(function() {
$("#focusOnMe").focus();
}
I know this is old, but I just had this problem and maybe it helps someone.
If you use jQuery this works:
$("input[name='c_name']").focus();
Javascript would be something like this (general example):
document.getElementById('element').focus();
But you have to call that function after your form is loaded via ajax!
This worked for me:
$.get("/url.html", function(html) {
var form = $("#form", html);// extract form with id=form from ajax response
if (window.InstallTrigger) {// Detect Firefox and add focus script
// place focus on first element containing autofocus attribute
form.append("<script>$('[autofocus]')[0].focus();<\/script>");
}
$("#element").replaceWith(form);// Replace element with id=element with form
});
This is different from other solutions posted here because the script that places focus on the autofocus element is added to the DOM at the same time as the autofocus element itself thus ensuring that the script runs after the DOM is finished updating.
Note that this solution requires jQuery. If you are not using jQuery you can still do this easily enough with querySelectorAll
document.getElementById("element").innerHTML = form+"<script>document.querySelectorAll('[autofocus]')[0].focus()<\/script>"

Resources