I'm trying to Validate my form before it's being sent to the server. I tried couple of J/S plugins for regular validation and none of them seem to work.
I tried looking for getJSON validation method with jquerymobile but haven't seen anything related. Is using $.getJSON the right approach?
Here is a fiddle http://jsfiddle.net/Kimbley/kMsXK/2/
Thanks :D
Code Here:
function mAddBusiness() {
$.getJSON("API.php", {
command: "addBusiness",
bsnName: $("#mBsnName").attr("value"),
bsnCity: $("#mBsnCity").attr("value"),
bsnAddress: $("#mBsnAddress").attr("value"),
bsnMenu: $("#mBsnMenu").attr("value"),
bsnLat: bsnLat,
bsnLong: bsnLong
},
function () {
$("#mBsnName").attr("value", "");
$("#mBsnCity").attr("value", "");
$("#mBsnAddress").attr("value", "");
$("#mBsnMenu").attr("value", "");
alert("Business was added successfully ");
}
);
}
Inside your mAddBusiness() function you can just do your validation before sending the AJAX request. Something like:
function mAddBusiness() {
if ($("#mBsnName").val() !== '') {
$.getJSON("API.php", {
command: "addBusiness",
bsnName: $("#mBsnName").val(),
bsnCity: $("#mBsnCity").val(),
bsnAddress: $("#mBsnAddress").val(),
bsnMenu: $("#mBsnMenu").val(),
bsnLat: bsnLat,
bsnLong: bsnLong
},
function () {
$("#mBsnName").val("");
$("#mBsnCity").val("");
$("#mBsnAddress").val("");
$("#mBsnMenu").val("");
alert("Business was added successfully ");
}
);
} else {
alert('Please enter a business name.');
}
}
Note that you will have to add the data-ajax="false" attribute to the <form> tag in question so that jQuery Mobile does not attempt to submit the form itself.
Also, note that $('input').attr('value') will not return the current value of an input, it will return the initial value before the user had a chance to input anything. To get the current value of a form input, use .val(): http://api.jquery.com/val
Related
I'm struggling with the render() method in Laravel 5.
When $whatever->render() is runned, it takes the controller method name as the route by default.
Example:
When i run this command in DelasController#updateFilter, the pagination route is set to whatever.com/marketplace/updateFiler?page=2, which does not make a sense to me.
Problem:
I want to keep the route as simple as whatever.com/marketplace?page=2.
Question:
Can anybody gives me a hint on how to solve this?
Thank you for your time and a discussion.
Looking forward for a reply.
I have an application in which various paginated lists are displayed in "windows" on the page and are updated via AJAX calls to the server. Here's how I did it:
Set up a route to render the whole page, something like this:
Route::get('/marketplace', function ($arguments) {
....
});
Set up a route which will return the current page of the list. For example, it might be something like this:
Route::get('/marketplace/updateFiler', function ($arguments) {
....
});
In your Javascript code for the page, you need to change the pagination links so that, instead of loading the new page with the URL for the link, it makes the AJAX request to the second route. The Javascript could look something like this:
$('ul.pagination a').on('click', function (event) {
// stop the default action
event.stopPropagation();
event.preventDefault();
// get the URL from the link
var url = $(event.currentTarget).attr('href');
// get the page number from the URL
var page = getURLParameterByName(url, 'page');
$.get('marketplace/updateFiler', { page: page }, function (data){
// do something with the response from the server
});
});
The getURLParameterByName function is simply a helper that extracts the named parameter from a URL:
var getURLParameterByName = function (url, name, defaultValue) {
// is defaultValue undefined? if so, set it to false
//
if (typeof defaultValue === "undefined") {
defaultValue = false;
}
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(url);
return results === null ?
defaultValue :
decodeURIComponent(results[1].replace(/\+/g, " "));
};
I adapted this code from an answer I found here on Stack Overflow: https://stackoverflow.com/a/901144/2008384.
I have a form which contains a hidden field;
<input name="qsID" type="hidden" value="1368113958" />
This is a hidden field added by Concrete5.
When submitting the form its like the hidden field does not exist, Concrete5 (PHP) cannot see the hidden field so presumably CasperJS is not sending the hidden field.
Why is this happening?
Update
Using var_dump I can see that the whole $_POST array is empty
Update 2
It seems that this single piece of code is the difference between the form being posted correctly and failing;
casper.waitForSelector("#Question33",
function success() {
this.test.assertExists("#Question33");
this.click("#Question33");
},
function fail() {
this.test.assertExists("#Question33");
});
This code also breaks the posting of form data
casper.waitForSelector("form#miniSurveyView576 input[name='Question34']",
function success() {
this.test.assertExists("form#miniSurveyView576 input[name='Question34']");
this.click("form#miniSurveyView576 input[name='Question34']");
},
function fail() {
this.test.assertExists("form#miniSurveyView576 input[name='Question34']");
});
I basically had to scrap this code as it did not work at all.
What I ended up with was something like this
casper.test.begin('web site up', 4, function(test) {
casper.start(url).then(function() {
this.test.assert(
this.getCurrentUrl() === url, 'url is the one expected'
);
this.test.assertHttpStatus(200, url + ' is up');
functions.viewPortCapture(casper, viewports[0], "1001");
test.assertExists(x("//a[normalize-space(text())='ABC']"));
this.click(x("//a[normalize-space(text())='ABC']"));
this.waitForUrl(/abc\/$/, function(){
test.assertExists("input[type='submit']");
});
});
casper.run(function() {
test.done();
});
});
Is it available to set the value from javascript(Session / ViewState) and get the value in C# without using hidden field??
Its work to store the value from javascript , and available to get the value in C# (page.request["Token"]) , but its not working for me because there have a postback action " form.submit();"
function setToken(Token) {
try {
var form = document.createElement("form");
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'Token');
field.setAttribute("value", accessToken);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
} catch (err) {
}
}
If you want to submit a value from your clientside code to your serverside code, you'll need to submit it in some kind of request. A form post would be one way, but if you don't want the page to reload it could equally well be an AJAX request:
function setToken(accessToken) {
$.post('/SetToken', { Token: accessToken });
}
Using jQuery there as it'll save you a lot of the trouble involved in getting AJAX to work the same way across browsers.
In the example I'm posting a request to a page called /SetToken, which could be any url in your website where you have code that can update the token. Your own example submits a form without an action, which means it'll submit to the current page. You could easily do that as well
$.post(location.href, { Token: accessToken });
Using node.js and express (2.5.9) with express-form.
How should I repopulate form fields with the submitted values?
I have a get and a post route. If there are validation errors when the form is posted, I redirect the user back to the get, the problem is that the repopulated locals don't show up (I do have autoLocals: true, so I assume it's because I am redirecting and res is reset.)
So how do you guys repopulate and what's your application flow, do you res.send instead of res.redirect and set up the whole thing again? That seems repetitive.
Here's an example of my post route:
app.post(
'/projects/:id'
, form(field("title").required("title", "Title is required)
, function (req, res){
if (!req.form.isValid){
res.redirect('/project/'+req.params.id+'/edit');
}
else{
// save to db
}
});
I am working with expressjs4.0 to repopulate the forms fields after validation you do:
router.route('/posts/new')
.get(function(req, res) {
res.render('posts/new', new Post({}));
});
The second argument in res.render below will set some variables in the view.
res.render('posts/new', new Post({}));
In my view I then set my form fields as follows:
...
<input type="text" name="title" value="<%- post.title %>">
<textarea name="article"><%- post.article %></textarea>
...
When you submit this form, it should be caught by your router like so:
router.route('/posts')
.post(function(req, res) {
var post = new Post(req.body)
post.save(function(err) {
if (err) {
res.locals.errors = err.errors;
res.locals.post = post;
return res.render('posts/new');
}
return res.redirect('/posts');
});
...
})
This line of code, resets the form fields in your view
res.locals.post = post;
I hope someone finds this useful ;)
Not sure if it's best practice, but when I have validation failure, I don't redirect I just re-render the view (often by passing control to the 'get' callback). Somethign like this:
function loadProject(req,res, id){ /* fetch or create logic, storing as req.model or req.project */}
function editProject(req,res){ /* render logic */ }
function saveProject(req,res){
if(!req.form.isValid){
editProject(req,res);
}else{
saveToDb(req.project);
res.redirect('/project'+req.project.id+'/edit');
}
}
app.param('id', loadProject);
app.get('/projects/:id/edit', editProject);
app.post('/projects/:id', saveProject);
I had to work on similar problem recently and used two node modules: validator and flashify.
In the form view I configured my form fields as follows:
div.control-group
label.control-label Description
div.controls
textarea(name='eventForm[desc]', id='desc', rows='3').input-xxlarge= eventForm.desc
div.control-group
label.control-label Tag
div.controls
select(id='tag', name='eventForm[tag]')
tags = ['Medjugorje', 'Kibeho', 'Lourdes', 'Fatima']
for tag in tags
option(selected=eventForm.tag == tag)= tag
Notice the naming convention of the form fields. Then in my config file I set one global variable, which is really just a placeholder for when the form first loads:
//locals
app.locals.eventForm = []; // placeholder for event form repopulation
The validation logic is in my router file and looks like this:
app.post('/posts', function(req, res){
var formData = req.body.eventForm;
var Post = models.events;
var post = new Post();
post.text = formData.desc;
post.tag = formData.tag;
// run validations before saving
var v = new Validator();
var isPostValid = true;
// custom error catcher for validator, which uses flashify
v.error = function(msg) {
res.flash('error', msg);
isPostValid = false;
}
v.check(post.text, "Description field cannot be empty").notEmpty();
v.check(post.tag, "Tag field cannot be empty").notEmpty();
Then I check to see there are errors, and if so, pass the form data back to the view:
// reject it
res.render('Event.jade', {page: req.session.page, eventForm: formData});
Notice this evenForm data gets passed back to the view, which repopulates the default values.
The final step is to include the flashify component in your form view.
div(style='margin-top: 60px').container-fluid
include flashify
The code for the flashify view looks like this:
if (flash.error != undefined)
div.container
div.alert.alert-error
b Oops!
button(type='button', data-dismiss='alert').close ×
ul
each error in flash.error
li= error
if (flash.success != undefined)
div.container
div.alert.alert-success
b Success!
button(type='button', data-dismiss='alert').close ×
ul
each success in flash.success
li= success
i am trying to aggregate form elements into object and then send it via ajax here is the code that i start using but i cant figure out how to do the rest
$('.jcart').live('submit', function() {
});
Update 1:
html form
http://pasite.org/code/572
Update 2:
I have successfully submit the form using ajax but it still refreshes the page after submiting
this what i did
function adding(form){
$( "form.jcart" ).livequery('submit', function() {var b=$(this).find('input[name=<?php echo $jcart['item_id']?>]').val();var c=$(this).find('input[name=<?php echo $jcart['item_price']?>]').val();var d=$(this).find('input[name=<?php echo $jcart['item_name']?>]').val();var e=$(this).find('input[name=<?php echo $jcart['item_qty']?>]').val();var f=$(this).find('input[name=<?php echo $jcart['item_add']?>]').val();$.post('<?php echo $jcart['path'];?>jcart-relay.php',{"<?php echo $jcart['item_id']?>":b,"<?php echo $jcart['item_price']?>":c,"<?php echo $jcart['item_name']?>":d,"<?php echo $jcart['item_qty']?>":e,"<?php echo $jcart['item_add']?>":f}
});
return false;
}
jQuery has a method called .serialize() that can take all the form elements and put them into an array for just what you are trying to do. Without seeing your html, we really can't tell you much more though.
http://api.jquery.com/serialize/
Something like this might work:
$('.jcart').submit(function() {
$.ajax({
url : form.php,
type : "POST",
data : $(this).serialize(),
});
});
Obviously it would need a little more for full functionality, but that should get you started.
Depending on how many of the values you need (and whether you have things like radio buttons) you can start with the :input selector to grab the elements. Assuming .jcart is your form or container, something like this:
var data = {};
$('.jcart').find(':input').each(function (i, field) {
if ($(field).is('input:checkbox') {
if (field.checked) {
data[field.name] = true;
} else {
data[field.name] = false;
}
} else {
data[field.name] = $(field).val();
}
});
That should get you started.