prototype ajax updater div with different buttons - ajax

i'm learning it, but i cant find what's wrong in this!
i want the div2 to get data from the form in div1, called formulario.
i would like to know which item is selected and which button was clicked.
main html file:
<script src="utils/Scripts/prototype.js" type="text/javascript"></script>
<script type="text/javascript">
function sendf(formul, divi, php)
{
var params = Form.serialize($(formul));
new Ajax.Updater(divi, php, {method: 'post', parameters: params, asynchronous:true});
}
</script>
</head>
<body>
<div id="div1">
contenido div1
<form id="formulario" method="POST">
<select size="3" id="lista" onchange="sendf('formulario', 'div2', 'prodiv1.php');">
<option>elemento 1</option>
<option>elemento 2</option>
<option>elemento 3</option>
</select>
<input type="button" id="b1" value="bot1" onclick="sendf('formulario', 'div2', 'prodiv1.php');" />
<input type="button" id="b2" value="bot2" onclick="sendf('formulario', 'div2', 'prodiv1.php');" />
</form>
<div id="div2" style="background: blue;">
contenido div2
</div>
</div>
</body>
</html>
the php file, prodiv1.php:
<?
echo 'exec: prodiv1.php<br>';
print_r($_POST);
echo serialize($_POST);
if (isset($_POST))
{
foreach ($_POST as $key=>$value)
{
echo $key.'=>'.$value."<br>";
}
}
echo "select: ".$_POST['lista'];
if (isset($_POST['b1'])) {echo 'click: boton1';} else {echo 'click: boton2';}
?>
i've tried a lot of things, and seen that it could be done with event observers, httprequests and such, but what i need is quite easy, and probably there's an elegant way to solve it...
i thank in advance any help!
have a nice day.
guillem

if you dont need to actually process the form contents in some way then you have no need to use Ajax to pass to a PHP script. Depending on what exactly you wanted to display in div 2 you could do something as simple as this:
function sendf()
{
var listvar = $('lista').value;
$('div2').update('select menu value was ' + listvar);
}
This is obviously missing quite a lot of detail and can be massively improved but it should highlight the fact that AJAX is not required.

Edit Looking at the rest of the code you have posted, is AJAX really required for this? surely you are just updating the existing page with data already present on the page, the server has no real part to play in this?
Sorry to dive into jQuery again, but this should allow you to get the values into "div2" without an ajax request.
$(document).ready(function() {
$("input").click(function(e) {
$("#div2").html($(this).attr("id")+" clicked<br />");
updateList();
});
});
function updateList() {
$("#div2").append($("#lista").val() + " selected");
}
In plain English this code says "if an input element is clicked, update the value of div2 with the input variables id, and append the selected value from the list to the result". Hopefully that makes sense to you :)
If you need an easy, elegant way to solve this with AJAX, use the jQuery library's ajax and post methods. For more information take a look here, it will significantly cut down on the size and complexity of your code.

Related

iCheck - Checkboxes not reseting after form reset

After wasting like 2 days with this problem i finally decided to post this here and hope someone can help me. I work with "iCheck" (http://icheck.fronteed.com/) but also tried similar libraries that work roughly the same way. I try to achieve fancy checkboxes in form of a button - a pretty common thing i guess.
Now with iCheck and the other libraries i tested i always have one problem: I build my code to send an AjaxRequest to work with the data provided in a form and then reset the form. That works pretty neat, except for these chechboxes. If i change them to the other state they are not initialized with (like from FALSE to TRUE) and reset the form the button visually stays on that state until you click it once again. I works like it should with "normal" checkboxes.
I rebuild a small testpage and put it into jsfiddle. Is this a bug or am i totally overseeing something there? Can someone explain to me why that happens and how to engage with this?
HTML:
<form id="form">
<input type="checkbox" class="check_test" name="test" value="1"><label>Checkbox 1</label>
<input type="checkbox" name="test2" value="1"><label>Checkbox 1</label>
<br/>
<button type="reset" onClick="this.form.reset"> Reset </button>
</form>
Javascript:
$(document).ready(function(){
$('.check_test').each(function(){
var self = $(this),
label = self.next(),
label_text = label.text();
label.remove();
self.iCheck({
checkboxClass: 'icheckbox_line-blue',
radioClass: 'iradio_line-blue',
insert: '<div class="icheck_line-icon"></div>' + label_text
});
});
});
https://jsfiddle.net/p80dctkv
Thank you in advance.
You can add js like this to remove checked ichek
$(":radio").prop('checked', false).parent().removeClass('checked');

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

angularjs $scope.$apply() doesnt update select list on ajax IE9

So to keep it simple, im trying to update my select list with a new list of items that i get from an ajax-call. The list has the items. I set the model to the new list and do a $scope.$apply(). This works great in firefox, but not in IE. What am I doing wrong? Is there some IE9-thing that I'm missing? (I've been looking for a few hours now and am ready to give up). Appreciate all the help I can get.
HTML:
<select
ng-model="SelectedParameter"
ng-options="Parameter.Name for Parameter in AllParameters">
</select>
JS:
$.getJSON("/Cont/GetList", {id: id},
function (result) {
var allParameters = result.Data.AllParameters;
$scope.AllParameters = allParameters;
$scope.$apply();
}
);
You'd be way better off doing this the "Angular way". No JQuery required! In fact, if you find yourself doing things the "JQuery way" you're probably doing it wrong. Mark Rajcok had a really good question (and answer) about this same thing on StackOverflow a while ago:
app.js
//declare your application module.
var app = angular.module('myApp', []);
//declare a controller
app.controller('MainCtrl', function($scope, $http) {
//function to update the list
$scope.updateList = function () {
$http.get('/Cont/GetList', function(data) {
$scope.allParameters = data;
});
};
//initial load
$scope.updateList();
});
index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="angular.js"></script>
<script src="app.js"></script>
</head>
<body>
<div ng-controller="MainCtrl">
<button ng-click="updateList()">Update</button>
<ul>
<li ng-repeat="parameter in allParameters">{{parameter | json}}</li>
</ul>
<!-- EDIT: Because you requested a select.
or if you wanted to do a select list
assuming every object in your array had a "name" property
you wanted to display in the option text, you could do
something like the following:
(NOTE: ng-model is required for ng-options to work)
-->
<select ng-model="selectedValue" ng-options="p as p.name for p in allParameters"></select>
<!-- this is just to display the value you've selected -->
<p>Selected:</p>
<pre>{{selectedValue | json}}</pre>
</div>
</body>
</html>
EDIT: A common problem in IE
So first of all, if you're having a problem in IE, I'd recommend hitting F12 and seeing what errors you're getting in the console.
The most common issue I've seen that breaks things in IE relate to commands such as console.log() which don't exist in IE. If that's the case, you'll need to create a stub, like so:
//stub in console.log for IE.
console = console || {};
console.log = console.log || function () {};
I think it's an IE issue. Try setting display:none before you update, then remove the display setting after you update.
I believe it is this bug that is ultimately the problem. I've been pulling my hair out for a couple of days on something very similar, a select filtered off of another.
At the end of the day OPTIONS are being added dynamically and IE9 just chokes on it.
<div class="col-lg-2">
<div class="form-group">
<label>State</label>
<select data-ng-model="orderFilter.selectedState"
data-ng-options="s.StateAbbr for s in states"
data-placeholder="choose a state…"
class="form-control">
<option value=""></option>
</select>
</div>
</div>
<div class="col-lg-2">
<div class="form-group">
<label>County</label>
<select data-ng-model="orderFilter.selectedCounty"
data-ng-options="c.CountyName for c in filteredCounties | orderBy:'CountyName'"
data-ng-disabled="orderFilter.selectedState == null"
data-placeholder="Choose a county…"
class="form-control">
<option value=""></option>
</select>
</div>
</div>
Regards,
Stephen

Load Dojo form from ajax call

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

Ajax form perfect until inside another page

I have a page which uses ajax to submit a comment form, add it to a db, then redisplay the page, hopefully without reloading the page its on.
If I access the script on it's own it works great, yet when I load it into another page it doesn't add the data and also refreshes the page on submit, which I want to avoid, which is the whole point of doing things this way.
Anyway, here's how I load the page:
<div id="wall_comments" class="msgs_holder"></div>
<script type="text/javascript">
$('#wall_comments').load('/pages/comment.php', { wl_id:"<?=$wl_id?>" });
</script>
and then the page itself with jquery code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<div style="width:100%; overflow:auto;">
<form method=post>
<input type="text" class="inp" name="comment" id="comment">
<input type=submit value="do it" name="action" onclick="update()">
<input type=hidden name="wl_id" value="<?=$_REQUEST[wl_id]?>" id="wl_id">
<input type=hidden name="user_id" value="<?=$userfromcookie?>" id="user_id">
</form>
</div>
<script type="text/javascript">
function update(){
var wl_idVal = $("#wl_id").val();
var commentVal = $("#comment").val();
var user_idVal = $("#user_id").val();
$.ajax({
type: "POST",
url: "/pages/comment.php",
cache: false,
data: { submit: "", wl_id: wi_idVal, comment: commentVal, user_id: user_idVal }
});
}
</script>
And finally enter info into db (I know this should be mysqli and it will be)
if(isset($_POST['action'])){
$wl_id = mysql_real_escape_string($_POST['wl_id']);
$comment = mysql_real_escape_string($_POST['comment']);
$user_id = mysql_real_escape_string($_POST['user_id']);
$addcomment = mysql_query("insert into list_wall (
event_id,
user_id,
comment
) VALUES (
'$wl_id',
'$user_id',
'$comment'
) ",$db);
if(!$addcomment) { echo 'result error add comment'; echo mysql_error(); exit; } // debug
}
The problem is when you click the submit button, the page is submitted and the function update couldn't work. You have to cancel the default submit mechanism by using return false;
<input type=submit value="do it" name="action" onclick="update() return false;">
Another thing.
The onclick on the submitbutton will not work as excpected if the submit is caused without clicking the button.
For example mobile safari on iPhone can submit forms directly without triggering the button.
If you add UmairP's version of the onclick to the form element as an onsubmit method you should get the same result on every platform as far as I know.
You can see more details on iPhone forms in my own question on another issue.
How can I prevent the Go button on iPad/iPhone from posting the form

Resources