view not refreshing after zend redirect - zend-framework

so what i am trying to do, is after the user submit some information, i make a call to a action call saveronda, to save the information on the database, after saving i want to redirect to another page, according to the firebug the html is correct, but the view isnt refreshing.
so here is the code
so in my /rondas/chooseronda ive got this
<span class="st-labeltext">Tags da ronda:</span>
<table id="toolbar2"></table>
<div id="ptoolbar2"></div>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Nome da ronda:</span>
<input type="text" name="nomeronda" id="nomeronda">
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Tag Inicial:</span>
<select id="tagini" name="tagini">
</select>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Tag Final:</span>
<select id="tagfim" name="tagfim">
</select>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="st-form-line" style="z-index: 680;">
<span class="st-labeltext">Ordem:</span>
<select id="ordem" name="ordem">
<option value="Sim">Sim</option>
<option value="Não">Não</option>
</select>
<div class="clear" style="z-index: 670;"></div>
</div>
<div class="button-box" style="z-index: 460;">
<input id="button" class="st-button" type="submit" value="Submit" name="button">
<input id="button2" class="st-clear" type="reset" value="Cancel" name="button">
</div>
when the user press the button submit i am making an ajax call to /rondas/saveronda and send some data, here is the code:
<script language = "Javascript">
$(document).ready(function() {
$("#button").click(function () {
/*
$.ajax({
url: '/rondas/saveronda',
type: 'POST',
data: {param1: param1, param2:param2 },
datatype: "json"
*/
//buscar o nome
/*var nomeronda=$("#nomeronda").val();
//buscar a ordem
var ordem=$("#ordem").val();
//tag inicial e tag final
var taginicial=$("#tagini").val();
var tagfinal=$("#tagfim").val();
if(taginicial==tagfinal)
{
alert("a tag inicial não pode ser a mesma que a tag final");
}
else
{
var tags="";
//var allRowsOnCurrentPage = $('#toolbar2').getDataIDs();
var ids = $("#toolbar2").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++)
{
var rowId = ids[i];
var rowData = $('#toolbar2').jqGrid ('getRowData', rowId);
tags=tags+rowData.id_tag.toString()+' ';
}*/
$.ajax({
url: '/rondas/saveronda',
type: 'POST',
data: {param1: "sasa"},
datatype: "json"
});
//}
});
});
</script>
in this case i am sending param1 with the value "sasa", and through firebug i am detecting the post to the /rondas/saveronda.
after saving the data i want to redirect the user to /rondas/list, so i have been trying different solution
public function saverondaAction()
{
// action body
/*
if($this->_request->isXmlHttpRequest())
{
$param1 = $this->_request->getParam('param1');
$param2 = $this->_request->getParam('param2');
$param3 = $this->_request->getParam('param3');
$param4 = $this->_request->getParam('param4');
$param5 = $this->_request->getParam('param5');
$rondasModel= new Application_Model_Ronda();
$this->_forward('list', 'rondas');
}
*
*/
$this->_helper->redirector->gotoRoute(
array(
'controller' => 'rondas',
'action' => 'list'
)
);
}
or using redirect or forward..
none have worked, the view is still the /rondas/choosetags and not /rondas/list
what is my error...
thanks in advance..

Your initial view is /rondas/chooseronda when user press submit you make ajax call to /rondas/saveronda and send some data to it. Now if this is successful you want to redirect from the initial page (/rondas/chooseronda) to /rondas/list.
If the redirect code written in action /rondas/saveronda is not working, then you could return a success message back to initial view (/rondas/chooseronda), there you'll need to detect the success message in jQuery ajax code. If successful, put the redirect jQuery code, that will redirect it to /rondas/list.

Related

How to create mysql table entry on form submission in CodeIgniter

I just need to insert data to table on form submission with the entered inputs.
my Controller,
function create_wish() {
$data = array(
'user_name' => $this->input->post('uname'),
'user_email' => $this->input->post('uemail'),
'user_message' => $this->input->post('umessage')
);
$this->model_wishes->createWish($data);
}
model,
function createWish($data) {
$sql = "INSERT INTO wishes (user_name, user_email, user_wish) VALUES (".$data.user_name.", ".$data.user_email.", ".$data.user_message.")";
$this->db->query($sql);
echo $this->db->affected_rows();
}
view,
<form method="post" action="<?php echo base_url() . "index.php/Welcome/create_wish"?>">
<div class="row">
<div class="form-group col-md-6">
<label for="post-name">Name</label>
<input autocomplete='name' type="text" class="form-control" id="uname" name="uname" required />
</div>
<div class="form-group col-md-6">
<label for="post-email">Email</label>
<input autocomplete='email' type="email" class="form-control" id="uemail" name="uemail" required/>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 margin-b-2">
<label for="post-message">Message</label>
<textarea class="form-control" id="umessage" rows="5" name="umessage"></textarea>
</div>
</div>
<div class="row">
<div class="form-group col-md-12 text-left mb-0">
<button id="btn-create" type="submit" class="button-medium btn btn-default fill-btn">Post Wish</button>
</div>
</div>
</form>
Ajax,
$(document).ready(function () {
$('form').submit(function (event) {
var formData = {
'user_name': $('input[name=uname]').val(),
'user_email': $('input[name=uemail]').val(),
'user_wish': $('input[name=umessage]').val()
};
$.ajax({
type: 'POST',
url: 'http://localhost/CodeIgniterProj/index.php/create_wish',
data: formData,
dataType: 'json',
encode: true
})
.done(function (data) {
console.log(data);
});
event.preventDefault();
});
});
execution of above codes displays an error in console
POST http://localhost/CodeIgniterProj/index.php/create_wish 404 (Not Found)
XHR failed loading: POST "http://localhost/CodeIgniterProj/sender.php".
I tried to fix this and failed. Someone please let me know how to fix this issue, help me on this.
Your URL is missing the controller segment
you should call index.php/[controller]/[method]. Regarding the sender.php i cannot see any call to it. Maybe there are other forms in the markup.
Besides that, the model will not work as expected. Since you are dealing with an array you should change:
... VALUES (".$data.user_name.", ...)
to
...(VALUES (".$data["user_name"].", ...)
If you don't want to use the active record class, you should escape the values in your query.
https://www.codeigniter.com/user_guide/database/queries.html#escaping-queries
I hope it helps.
Use site_url in your ajax url , should be like this
$(document).ready(function () {
$('form').submit(function (event) {
var formData = $(this).serialize();
alert(formData);
$.ajax({
type: 'POST',
url: '<?=site_url('Welcome/create_wish');?>',
data: formData,
dataType: 'json',
}).done(function (data) {
console.log(data.id);
});
event.preventDefault();
});
});
Your controller should be like this :
function create_wish() {
$data = array(
'user_name' => $this->input->post('uname'),
'user_email' => $this->input->post('uemail'),
'user_message' => $this->input->post('umessage')
);
$insert_id = $this->model_wishes->createWish($data);
if($insert_id)
{
$response = array('status' => 'success');
}
else
{
$response = array('status' => 'error');
}
echo json_encode($response);
exit;
}
Your model method createWish should be like this ;
function createWish($data)
{
$this->db->insert('wishes', $data);
return $this->db->insert_id();
}

SharpSpring - Prevent form from automatically appearing if user has filled out form (without relying on cookies)

Ok, this is related to the question I asked a short while ago: Silverstripe/PHP/jQuery - Once form has been filled out by user, prevent it from automatically appearing for each visit
Something has changed since then. Per request of the client, the form must not automatically appear if the user has already filled it out and has thus been placed into SharpSpring. Originally, I was creating a cookie on successful form submission using JavaScript. However, the latest concern is that it's not effective enough as cookies are registered only to certain devices and browsers, and users can clear their cookies at any time.
Essentially, the desired result is to prevent the form from automatically appearing if the user has been registered in SharpSpring (a separate domain) without having to rely on cookies.
Has anyone ever attempted something like this, checking to see if a user has submitted a form to another domain?
For reference, here is the form code I have setup:
<?php
/*
Plugin Name: SharpSpring Form Plugin
Description: A custom form plugin that is SharpSpring-compatible and uses HTML, CSS, jQuery, and AJAX
Version: 1.0
*/
define('SSCFURL', WP_PLUGIN_URL . "/" . dirname(plugin_basename(__FILE__)));
define('SSCFPATH', WP_PLUGIN_DIR . "/" . dirname(plugin_basename(__FILE__)));
function sharpspringform_enqueuescripts()
{
wp_enqueue_script('jquery-src', SSCFURL . '/js/jquery.js', array('jquery'));
wp_enqueue_script('jquery-ui', SSCFURL . '/js/jquery-ui.js', array('jquery'));
wp_enqueue_script('boootstrap', SSCFURL . '/js/bootstrap.js', array('jquery'));
wp_localize_script('sharpspringform', 'sharpspringformajax', array('ajaxurl' => admin_url('admin-ajax.php')));
}
add_action('wp_enqueue_scripts', 'sharpspringform_enqueuescripts');
function sharpspringform_show_form()
{
wp_enqueue_style( 'boilerplate', SSCFURL.'/css/boilerplate.css');
wp_enqueue_style( 'bootstrapcss', SSCFURL.'/css/bootstrap.css');
wp_enqueue_style( 'bookregistration', SSCFURL.'/css/Book-Registration.css');
wp_enqueue_style( 'formstyles', SSCFURL.'/css/styles.css');
?>
<div class="mobile-view" style="right: 51px;">
<a class="mobile-btn">
<span class="glyphicon glyphicon-arrow-left icon-arrow-mobile mobile-form-btn"></span>
</a>
</div>
<div class="slider register-photo">
<div class="form-inner">
<div class="form-container">
<form method="post" enctype="multipart/form-data" class="signupForm" id="browserHangFormPV">
<a class="sidebar">
<span class="glyphicon glyphicon-arrow-left icon-arrow arrow"></span>
</a>
<a class="closeBtn">
<span class="glyphicon glyphicon-remove"></span>
</a>
<h2 class="text-center black">Sign up for our newsletter.</h2>
<p class="errors-container light">Please fill in the required fields.</p>
<div class="success">Thank you for signing up!</div>
<div class="form-field-content">
<div class="form-group">
<input class="form-control FirstNameTxt" type="text" name="first_name" placeholder="*First Name"
autofocus="">
</div>
<div class="form-group">
<input class="form-control LastNameTxt" type="text" name="last_name" placeholder="*Last Name"
autofocus="">
</div>
<div class="form-group">
<input class="form-control EmailTxt" type="email" name="email" placeholder="*Email"
autofocus="">
</div>
<div class="form-group">
<input class="form-control CompanyTxt" type="text" name="company" placeholder="*Company"
autofocus="">
</div>
<div class="form-group submit-button">
<button class="btn btn-primary btn-block button-submit" type="button">SIGN ME UP</button>
<img src="/wp-content/plugins/sharpspring-form/img/ajax-loader.gif" class="progress" alt="Submitting...">
</div>
</div>
<br/>
<div class="privacy-link">
<a href="[privacy policy link]" class="already" target="_blank"><span
class="glyphicon glyphicon-lock icon-lock"></span>We will never share your information.</a>
</div>
</form>
<input type="hidden" id="gatewayEmbedID" value="<?php echo get_option( 'pv_signup_sharpspring_ID' ); ?>" />
<script type="text/javascript">
var embedID = document.getElementById("gatewayEmbedID").value;
var __ss_noform = __ss_noform || [];
__ss_noform.push(['baseURI', 'https://app-3QNAHNE212.marketingautomation.services/webforms/receivePostback/[redacted]']);
__ss_noform.push(['form', 'browserHangFormPV', embedID]);
__ss_noform.push(['submitType', 'manual']);
</script>
<script type="text/javascript" src="https://koi-3QNAHNE212.marketingautomation.services/client/noform.js?ver=1.24" ></script>
</div>
</div>
</div>
<?php
}
function sharpspringform_shortcode_func( $atts )
{
ob_start();
sharpspringform_show_form();
$output = ob_get_contents();
ob_end_clean();
return $output;
}
add_shortcode( 'sharpspringform', 'sharpspringform_shortcode_func' );
The form submission code with generates a cookie using JS:
;
(function ($) {
$(document).ready(function () {
var successMessage = $('.success');
var error = $('.errors-container');
var sharpSpringID = $('#gatewayEmbedID').val();
var submitbtn = $('.button-submit');
var SubmitProgress = $('img.progress');
var formdata = {};
function setCookie(cname, cvalue, exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/";
}
submitbtn.click(function (e) {
resetErrors();
postForm();
});
function resetErrors() {
$('.signupForm input').removeClass('error-field');
}
function postForm() {
$.each($('.signupForm input'), function (i, v) {
if (v.type !== 'submit') {
formdata[v.name] = v.value;
}
});
submitbtn.hide();
error.hide();
SubmitProgress.show();
$.ajax({
type: "POST",
data: formdata,
url: '/wp-content/plugins/sharpspring-form/sharpsring-form-submission.php',
dataType: "json"
}).done(function (response) {
submitbtn.show();
SubmitProgress.hide();
if (response.errors) {
error.show();
var errors = response.errors;
errors.forEach(function (error) {
$('input[name="' + error + '"]').addClass('error-field');
})
}
else {
__ss_noform.push(['submit', null, sharpSpringID]);
setCookie('SignupSuccess', 'NewsletterSignup', 3650);
$('#browserHangFormPV')[0].reset();
$('.form-field-content').hide();
successMessage.show();
$('.button-submit').html("Submitted");
}
});
}
});
}(jQuery));
The jQuery code that sets up the form sliding animation and popup feature, as well as checks for the existence of the JS cookie created on successful form submit:
jQuery.noConflict();
(function ($) {
$(document).ready(function () {
//This function checks if we are in mobile view or not to determine the
//UI behavior of the form.
checkCookie();
window.onload = checkWindowSize();
var arrowicon = $(".arrow");
var overlay = $("#overlay");
var slidingDiv = $(".slider");
var closeBtn = $(".closeBtn");
var mobileBtn = $(".mobile-btn");
//When the page loads, check the screen size.
//If the screen size is less than 768px, you want to get the function
//that opens the form as a popup in the center of the screen
//Otherwise, you want it to be a slide-out animation from the right side
function checkWindowSize() {
if ($(window).width() <= 768) {
//get function to open form at center of screen
if(sessionStorage["PopupShown"] != 'yes' && !checkCookie()){
setTimeout(formModal, 5000);
function formModal() {
slidingDiv.addClass("showForm")
overlay.addClass("showOverlay");
overlay.removeClass('hideOverlay');
mobileBtn.addClass("hideBtn");
}
}
}
else {
//when we aren't in mobile view, let's just have the form slide out from the right
if(sessionStorage["PopupShown"] != 'yes' && !checkCookie()){
setTimeout(slideOut, 5000);
function slideOut() {
slidingDiv.animate({'right': '-20px'}).addClass('open');
arrowicon.addClass("glyphicon-arrow-right");
arrowicon.removeClass("glyphicon-arrow-left");
overlay.addClass("showOverlay");
overlay.removeClass("hideOverlay");
}
}
}
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user = getCookie("SignupSuccess");
if (user != "") {
return true;
} else {
return false;
}
}
/*
------------------------------------------------------------
Functions to open/close form like a modal in center of screen in mobile view
------------------------------------------------------------
*/
mobileBtn.click(function () {
slidingDiv.addClass("showForm");
slidingDiv.removeClass("hideForm");
overlay.addClass("showOverlay");
overlay.removeClass('hideOverlay');
mobileBtn.addClass("hideBtn");
});
closeBtn.click(function () {
slidingDiv.addClass("hideForm");
slidingDiv.removeClass("showForm");
overlay.removeClass("showOverlay");
overlay.addClass("hideOverlay")
mobileBtn.removeClass("hideBtn");
sessionStorage["PopupShown"] = 'yes'; //Save in the sessionStorage if the modal has been shown
});
/*
------------------------------------------------------------
Function to slide the sidebar form out/in
------------------------------------------------------------
*/
arrowicon.click(function () {
if (slidingDiv.hasClass('open')) {
slidingDiv.animate({'right': '-390px'}, 200).removeClass('open');
arrowicon.addClass("glyphicon-arrow-left");
arrowicon.removeClass("glyphicon-arrow-right");
overlay.removeClass("showOverlay");
overlay.addClass("hideOverlay");
sessionStorage["PopupShown"] = 'yes'; //Save in the sessionStorage if the modal has been shown
} else {
slidingDiv.animate({'right': '-20px'}, 200).addClass('open');
arrowicon.addClass("glyphicon-arrow-right");
arrowicon.removeClass("glyphicon-arrow-left");
overlay.addClass("showOverlay");
overlay.removeClass("hideOverlay");
}
});
});
}(jQuery));
I'm confused by the WordPress code here, rather than SilverStripe, it's not clear in your question which platform you're using.
Basically, if you want something more robust than cookies, you'll need to store the registration in the database and check it there (assuming the registration form is on your site). This means you handle the form submission on your site, send the data to the remote site and check the responses, and if all goes well, save the fact that the user has registered remotely into your database where you can check when deciding whether to show the form or not, next time.
If you don't have access to the registration form, or you want to also notice registrations made independently of your site, then you need to have an API you can query on the remote site in order to see if the user is registered.
I found a sharpspring API, but I'm not sure if it's relevant.

My form is not populating when there is some validation error in the input data. Laravel Collective

Hope yo are all doing great.
I am using Laravel 5.3 and a package LaravelCollective for form-model binding.
I have subjects array that I want to validate and then store in database if there is no error in the input data.
The following snippets show the partial view of form, other views, rules for validations and controller code.
UserProfile.blade.php
<!-- Panel that Adds the Subject - START -->
<div class="col-md-12">
<div class="panel panel-default" id="add_Subject_panel">
<div class="panel-heading">Add Subject(s):</div>
<div class="panel-body">
{!! Form::open( array('method'=>'post', 'url'=>route('user.store.subject', 1)) ) !!}
#include('user.partials.subjects', ['buttonText'=>'Add Subject(s)'])
{!! Form::close() !!}
</div>
</div>
</div>
<!-- Panel that Adds the Subject - END -->
subjects.blade.php
#if (count($errors) > 0)
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<div class="subject-list">
<div class="input-group subject-input">
<input type="text" name="name[]" class="form-control" value="" placeholder="Subject" />
<span class="input-group-btn">
<span class="btn btn-default">Primary subject</span>
</span>
</div>
</div>
<div class="text-right">
<br />
<button type="button" class="btn btn-success btn-sm btn-add-subject"><span class="glyphicon glyphicon-plus"></span> Add Subject</button>
</div>
<div class="form-group">
<div class="col-md-6 col-md-offset-4 text-right">
<button type="submit" class="btn btn-primary">
{{ $buttonText }} <i class="fa fa-btn fa-subject"></i>
</button>
</div>
</div>
#push('scripts')
{{-- <script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script> --}}
<script src="{{ asset('scripts/jquery-2.2.4.min.js') }}" type="text/javascript" charset="utf-8" async defer></script>
<script>
$(function()
{
$(document.body).on('click', '.btn-remove-subject', function(){
$(this).closest('.subject-input').remove();
});
$('.btn-add-subject').click(function()
{
var index = $('.subject-input').length + 1;
$('.subject-list').append(''+
'<div class="input-group subject-input" style="margin-top:20px; margin-bottom:20px;">'+
'<input type="text" name="name['+index+']" class="form-control" value="" placeholder="Subject" />'+
'<span class="input-group-btn">'+
'<button class="btn btn-danger btn-remove-subject" type="button"><span class="glyphicon glyphicon-remove"></span></button>'+
'</span>'+
'</div>'
);
});
});
</script>
#endpush
I want to validate all the subjects passed as an array to the controller using a custom created form request. the following is the code for that form request
SubjectRequest.php
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class SubjectRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* #return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* #return array
*/
public function rules()
{
// dd("Rules Area");
foreach($this->request->get('name') as $key => $val)
{
$rules['name.'.$key] = 'required|min:5|max:50';
}
// dd($rules);
return $rules;
}
public function messages()
{
// dd('Message Area. . .');
$messages = [];
foreach($this->request->get('name') as $key => $val)
{
$messages['name.'.$key.'.required'] = ' Subject Name '.$key.'" is required.';
$messages['name.'.$key.'.min'] = ' Subject Name '.$key.'" must be atleast :min characters long.';
$messages['name.'.$key.'.max'] = ' Subject Name '.$key.'" must be less than :max characters.';
}
// dd($messages);
return $messages;
}
}
the following is the code for controller method I am using to store inputted array data to database.
public function storeSubjects(SubjectRequest $request)
{
$data = $request->all();
// save logic
dd($data);
}
Problem:
My form is not populating when there is some validation error in the input data.
After getting validation errors, my input fields are blank.
Problem
In subject.blade.php, your code looks like
<input type="text" name="name[]" class="form-control" value="" placeholder="Subject" />
Your fields are not populating because you have left value attribute blank.
Solution:
Pass the old value to solve your problem.
<input type="text" name="name[]" class="form-control" value="{{old('name[]')}}" placeholder="Subject" />
Use Form Model Binding instead
https://laravelcollective.com/docs/5.3/html#form-model-binding
{{ Form::model($user, [....]) }}
{{ Form::text('firstname', null, [...]) }}
{{ Form::close() }}

Meteor - Data saving issue

I have this template:
<Template name="nuevoEjercicio">
<div class="container-fluid">
<div class="form-group">
<input type="text" class="form-control input-lg" name="ejercicio" placeholder="Ejercicio?"/>
<input type="number" class="form-control" name="repeticiones" placeholder="Repeticiones?" />
<input type="number" class="form-control" name="peso" placeholder="Peso?" />
<button type="submit" class="btn btn-success" >
<span class="glyphicon glyphicon-plus"></span>
</button>
</div>
</div>
</Template>
that I use to capture and save to the database.
Then on my .js file I am trying to get the data and save it:
Template.nuevoEjercicio.events({
'click .btn btn-success': function (event) {
var ejercicio = event.target.ejercicio.value;
var repeticiones = event.target.repeticiones.value;
var peso = event.target.peso.value;
ListaRutina.insert({
rutina:"1",
ejercicio:ejercicio,
repeticiones:repeticiones,
peso:peso,
});
// Clear form
event.target.ejercicio.value = "";
event.target.repeticiones.value = "";
event.target.peso.value = "";
// Prevent default form submit
return false;
}
});
}
as I understand, when I click on any object that has the btn btn-success style....but is not the case. For some obscure reason -for me- is not working.
Can you check it and give me some advice?
Thanks!
First of all, there's an error in you selector. It's 'click .btn.btn-success', not 'click .btn btn-success'.
Also you can't do that event.target.ejercicio.value thing. event.target is the element that was clicked. You'll have to do something like this:
'click .btn.btn-success': function (event, template) {
var ejercicio = template.$('[name=ejercicio]').val()
...
OK
What after wasting hours and hours the solution is:
1- on the html file give your input an id:
<input type="number" class="form-control" **id="peso"** placeholder="Peso?" />
<button type="submit" class="btn .btn-success" id="**guardar**" />
so now you want to save data on the input when the button is clicked:
2- You link the button with the funcion via the id
Template.TEMPLATENAMEONHTMLFILE.events({
'click **#guardar**': function (event, template) {
var ejercicio = template.$("**#peso**").val();
and get the value linking using the input id.

Error submitting form data using knockout and mvc

#model NewDemoApp.Models.DemoViewModel
#{
ViewBag.Title = "Home Page";
}
#*<script src="#Url.Content("~/Scripts/jquery-1.9.1.min.js")" type="text/javascript"></script>*#
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="#Url.Content("~/Scripts/knockout-3.3.0.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<script type="text/javascript">
var viewModel;
var compViewModel, userViewModel;
$(document).ready(function () {
$(".wizard-step:visible").hide();
$(".wizard-step:first").show(); // show first step
$("#back-step").hide();
var result = #Html.Raw(Json.Encode(Model));
var viewModel = new DemoViewModel(result.userViewModel);
//viewModel.userViewModel.FirstName = result.userViewModel.FirstName;
//viewModel.userViewModel.LastName = result.userViewModel.LastName;
//viewModel.userViewModel.State = result.userViewModel.State;
//viewModel.userViewModel.City = result.userViewModel.City;
ko.applyBindings(viewModel);
});
var userVM = function(){
FirstName = ko.observable(),
LastName = ko.observable(),
State = ko.observable(),
City = ko.observable()
};
function DemoViewModel(data) {
var self = this;
self.userViewModel = function UserViewModel(data) {
userVM.FirstName = data.FirstName;
userVM.LastName = data.LastName;
userVM.State = data.State;
userVM.City = data.City;
}
self.Next = function () {
var $step = $(".wizard-step:visible"); // get current step
var form = $("#myFrm");
var validator = $("#myFrm").validate(); // obtain validator
var anyError = false;
$step.find("input").each(function () {
if (!validator.element(this)) { // validate every input element inside this step
anyError = true;
}
});
if (anyError)
return false; // exit if any error found
if ($step.next().hasClass("confirm")) { // is it confirmation?
$step.hide().prev(); // hide the current step
$step.next().show(); // show the next step
$("#back-step").show();
$("#next-step").hide();
//$("#myFrm").submit();
// show confirmation asynchronously
//$.post("/wizard/confirm", $("#myFrm").serialize(), function (r) {
// // inject response in confirmation step
// $(".wizard-step.confirm").html(r);
//});
}
else {
if ($step.next().hasClass("wizard-step")) { // is there any next step?
$step.hide().next().fadeIn(); // show it and hide current step
$("#back-step").show(); // recall to show backStep button
$("#next-step").show();
}
}
}
self.Back = function () {
var $step = $(".wizard-step:visible"); // get current step
if ($step.prev().hasClass("wizard-step")) { // is there any previous step?
$step.hide().prev().fadeIn(); // show it and hide current step
// disable backstep button?
if (!$step.prev().prev().hasClass("wizard-step")) {
$("#back-step").hide();
$("#next-step").show();
}
else {
$("#back-step").show();
$("#next-step").show();
}
}
}
self.SubmitForm = function (formElement) {
$.ajax({
url: '#Url.Content("~/Complaint/Save")',
type: "POST",
data: ko.toJS(self),
done: function (result) {
var newDiv = $(document.createElement("div"));
newDiv.html(result);
},
fail: function (err) {
alert(err);
},
always: function (data) {
alert(data);
}
});
}
self.loadData = function () {
$.get({
url: '#Url.Content("~/Complaint/ViewComplaint")',
done: function (data) {
debugger;
alert(data);
self.compViewModel(data);
self.userViewModel(data);
},
fail: function (err) {
debugger;
alert(err);
},
always: function (data) {
debugger;
alert(data);
}
});
}
}
</script>
<form class="form-horizontal" role="form" id="myFrm">
<div class="container">
<div class="row">
<div class="col-md-3">
</div>
<div class="col-md-6">
<div class="wizard-step">
</div>
<div class="wizard-step" >
<h3> Step 2</h3>
#Html.Partial("UserView", Model.userViewModel)
<div class="col-md-3"></div>
<div class="col-md-6">
<input type="submit" id="submitButton" class="btn btn-default btn-success" value="Submit" data-bind="click: SubmitForm" />
</div>
<div class="col-md-3"></div>
</div>
<div class="wizard-step">
<h3> Step 3</h3>
</div>
<div class="wizard-step confirm">
<h3> Final Step 4</h3>
</div>
</div>
<div class="col-md-3"></div>
</div>
<div class="row">
<div class="col-md-3"></div>
<div class="col-md-6">
<input type="button" id="back-step" class="btn btn-default btn-success" value="< Back" data-bind="click: Back" />
<input type="button" id="next-step" class="btn btn-default btn-success" value="Next >" data-bind="click: Next" />
</div>
<div class="col-md-3"></div>
</div>
</div>
</form>
I am able to get the data from controller and bind it using knockout. There is a partial view that loads data from controller. But when submitting the updated data, I do not get the data that was updated, instead getting error that "FirstName" property could not be accessed from null reference. I just need to get pointers where I am going wrong especially the right way to create ViewModels and use them.
When you are submitting the form in self.SubmitForm function you are passing Json object which is converted from Knockout view model.
So make sure you are providing the data-bind attributes in all input tags properly. If you are using Razor syntax then use data_bind in Html attributes of input tags.
Check 2-way binding of KO is working fine. I can't be sure as you have not shared your partial view Razor code.
Refer-
http://knockoutjs.com/documentation/value-binding.html
In Chrome you can see what data you are submitting in Network tab of javascript developer console. The Json data that you are posting and ViewModel data structure you are expecting in controller method should match.
You can also change the parameters to expect FormCollection formCollection and check what data is coming from browser when you are posting.