I have a panel within a form that has 3 buttons save, edit and cancel.
When the user clicks on edit, the labels inside the panel change to textboxes wherein the user can edit the content. This part is done.
Now if the user has edited the content, but does not wish to save it, he clicks on cancel. When he does so, the edited text will be replace with the original content of the labels(data comes from the model).
I have followed the accepted answer given here
Controller:
[HttpPost]
public ActionResult Submit(int id, string actionType)
{
var model = new CustomerDetailsViewModel();
var custid = db.Customers.Find(id);
if(actionType == "Cancel")
{
model.Company = custid.Company;
model.Address = custid.Address;
model.FullName = custid.FirstName + " " + custid.LastName;
model.EMail = custid.EMail;
model.Phone = custid.Phone;
model.EntryDate = custid.EntryDate;
model.LastInterestShown = custid.LastInterestShown;
model.ID = custid.ID;
model.Status = custid.Status;
}
return PartialView(model);
}
View:
<input type="submit" value="Cancel" id="btncancel" name="actionType" class="btn btn-default" />
JS:
$("#btnCancel").click(function(e){
e.preventDefault();
$.ajax({
url: '/Client/Submit',
type: 'POST',
async: false
});
});
Can someone tell me where am I going wrong?
You are sending an ajax request with type: "GET" and to url: "/Client/Cancel"
If you don't have a seperate
public ActionResult Cancel() {...}
field in your controller, this ajax don't work.
What you need to do is;
var postdata = { "id": id-here, "actionType": actionType-here };
$("#btnCancel").click(function(e){
e.preventDefault();
$.ajax({
url: '/Client/Submit',
type: 'POST',
data: JSON.stringfy(postdata),
async: false
});
});
in your ClientController.
You don't need to use AJAX to reset the input fields to their original data. Assuming you've passed your model data to your view, you can use hidden inputs to store the original values and later on get them back when the user clicks on the cancel button (just use a regular button).
View:
<input type="hidden" name="tempCompany" id="tempCompany" value="#Model.Company">
<input type="hidden" name="tempAddress" id="tempAddress" value="#Model.Address">
<input type="hidden" name="tempFullName" id="tempFullName" value="#Model.FullName">
JS:
<script>
$("#btnCancel").click(function (e) {
$('#Company').val($('#tempCompany').val());
$('#Address').val($('#tempAddress').val());
$('#FullName').val($('#tempFullName').val());
});
</script>
Related
i'm trying to submit forms without post back via ajax ..my code doesn't work
whats wrong in my script?
i'm new to ajax..help me with ajax scripts..
below is my code
note: i have two submit buttons with in single view. I want to make ajax call for both submit actions
my view
#model AjaxEF.Models.Customer
#using (Html.BeginForm("Index", "Main", FormMethod.Post,new { id="idForm"}))
{
#Html.EditorForModel()
<br />
<input type="submit" name="save" value="Save" />
<input type="submit" name="cancel" value="Cancel" />
}
<script>
$("#idForm").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var url = "~/Main/Result"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function (data) {
alert(data); // show response from the php script.
}
});
});
</script>
my controller
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Customer obj, string save, string cancel)
{
if (!string.IsNullOrEmpty(save))
{
ViewBag.Message = "Customer saved successfully!";
}
if (!string.IsNullOrEmpty(cancel))
{
ViewBag.Message = "The operation was cancelled!";
}
return View("Result", obj);
}
public ActionResult Result()
{
return View();
}
Not sure why the other answer was deleted, but it was 100% correct. The URL you're hitting with your AJAX is your Result action, which does nothing but return a view. You need to post to your Index action, and since the form is already set to post there, the best way to get that URL for your AJAX is to select it from the form:
var url = $('#idForm").attr("action");
The code should work something like this...
https://jsfiddle.net/Harout360/yhqoadqx/7/
But instead the form post does get correctly processed, then it redirects to the "/" url given as the action url in ajax. I can't figure out why it is redirecting, and if I place a console.log in the ajax it doesn't print to console.
HTML
<form method="post">
<input type="hidden" name="title" value="${title}" />
<button type="submit" value="Submit" id="sub-button" data-loading-text="Loading..." data-complete-text="Submitted!">
Submit
</button>
</form>
Javascript
$(document).ready(function() {
$("button[id=sub-button]").click(function(e){
e.preventDefault();
var button = $(this);
var form = $(this.form);
var form_data = form.serialize();
var form_method = form.attr("method").toUpperCase();
console.log('subscribing...');
$.ajax({
url: "/",
type: form_method,
data: form_data,
success: function(){
button.button('complete');
}
});
});
});
Java Servlet
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String title = req.getParameter("title");
Database.addTitle(title);
}
UPDATE
The Javascript works now because my problem was assigning the function to buttons that didn't exist at the time that document.ready loaded. Instead I now assign the .click to the button when it was actually loaded onto the page. Also I changed button's type to button, removed the id and now use $(.movie) to identify the button by its class.
Updated fiddle to give slight understanding of new approach https://jsfiddle.net/Harout360/yhqoadqx/11/
New Issue
Now the problem is that button.button('complete') is not doing anything. Any guesses as to why?
UPDATE 2 (Solution to new issue)
setTimeout(function() { button.button('complete'); }, 500);
I am having a some problem in my java script and to get the request.
This is the HTML
<form method="post" id="searchform">
<div align="center" class="col-md-10">
<input type="text" id= "contentSearch" name="contentSearch" >
</div>
<div class="form-group"><button type="submit" class="btn btn-default" id="submitSearch">
<i class="fa fa-search"></i> Search
</button></div>
</form>
<----Scenario 1 ---->
This script works fine and post the value and as ajax it never reload the page
<script>
$(document).ready(function () {
$("#submitSearch").on('click', function (e) {
e.preventDefault();
e.stopPropagation();
var data = {};
data['contentSearch'] = $('#contentSearch').val();
// Submit data via AJAX§
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (data) {
// do i need to do something here !!
}
});
});
});
</script>
When i check the POST value i can see the value is been POST.
The Problem is when i try to get the request data from controller like ---
$post_value = $request->request->get('contentSearch');
print_r($post_value);
OUTPUT : empty
<----Scenario 2 ---->
This script have a problem i think, because it reload the page for returning the result and displaying the value ---
<script>
$(document).ready(function () {
$("#searchform").on('submit', function (e) {
e.preventDefault();
var data = {};
data['contentSearch'] = $('#contentSearch').val();
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (data) {
}),
return false;
});
});
</script>
than i am able to get the post value like so--
$post_value = $request->request->get('contentSearch');
But the problem is in the second script the page is always loading when return the request which is not a ajax behave.
And in the first script i think because of the **e.preventDefault();** i am not getting the POST value in my controller.
Expected result ---
Option 1 : Do something so i can get the POST value in my controller
Option 2 : Fix this script so the page do not load to return the result and display
I am working on symfony framework .
Can someone please help me to fix this problem, i am really getting sick of to solve this problem.
Thanks a lot on advanced.
Like I mentioned in the comments, you need to be targeting the submit on the form. Not a click event. When targeting the click you are firing both the click and submit events, hence the reload.
$(document).ready(function () {
$("#searchform").on('submit', function (e) {
var data = {};
data['contentSearch'] = $('#contentSearch').val();
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (data) {
}
});
return false;
});
});
I have a formRemote that calls a function in my controller when it is submitted like this:
<g:formRemote name="editIndivRecForm" url="[controller: 'customer', action:'saveEditedIndividualRecord']" onSuccess="doResult();">
This form is submitted by clicking on a button. Rather, a button that is clicked called 'save' will do other things among clicking the form's submit button via Javascript. Here is the click handler for this button:
$('#save').click(function () {
$("#uniqueId").prop('disabled', false); // Have to enable before form submission else it doesn't go back as a param to controller.
$("#secondaryId").prop('disabled', false);
$("#submit").trigger("click"); // formRemote's submit button
$('#editIndivRecForm').reset;
<g:remoteFunction controller="customer"
action="remediationSearch"
update="content_area"
params="{rerender: true}"/>
});
The problem I'm running into is that I need the function of my controller called by the click handler remediationSearch to run AFTER the function of the controller called by the formRemote's submission saveEditedIndividualRecord is done executing. But it is happening the other way around. And for some reason the function onSuccess="doResult();" doesn't even execute otherwise I was going to move the following code into its body to make things work the way I want:
<g:remoteFunction controller="customer"
action="remediationSearch"
update="content_area"
params="{rerender: true}"/>
here is how doResult is now:
function doResult() {
console.log("done.");
}
the formRemote is submitted but the doResult function prints nothing to the console.
Seeing as all of the Grails AJAX related tags have been deprecated, I would recommend trying it this way:
Markup:
<form id="editIndivRecForm" onsubmit="return false;">
<!-- add fields here -->
<input type="text" id="uniqueId" value="${something}">
<input type="text" id="secondaryId" value="${something}">
<button id="save" type="button">
</form>
JavaScript:
// Function to update your content_area div
function updateContentArea() {
var params = { rerender: true };
var url = "${createLink(controller: 'customer', action: 'remediationSearch')}";
$.get(url, params, function(data) {
$("#content_area").empty().append(data);
});
}
$("#save").on('click', function() {
// Collect values from form and submit ajax request
// Using name and description for example fields here:
var data = {
name: $("#name").val(),
description: $("#description").val(),
uniqueId: $("#uniqueId").val(),
secondaryId: $("#secondaryId").val()
};
var url = "${createLink(controller: 'customer', action: 'saveEditedIndividualRecord')}";
// Submit the (first) AJAX request
$.ajax({
type: "post",
url: url,
data: data,
success: function() {
doResult();
$('#editIndivRecForm').reset();
updateContentArea();
}
});
}
I have a login popup that will pop up on every page of my site. What I want to do is once the user clicks submit, to have a single JS file where the jQuery code for handling that request lives, and makes an AJAX call to validate the parameters in the DB.
I am able to get the pop up box to pop up. And the form loads. I am thinking my jQuery code will live in a separate imported file and look like this:
<script type="text/javascript" >
$(function()
{
$("input[type=submit]").click(function()
{
var some_params= $("#param").val();
var dataString = 'Some url to send to ajax';
if( params validated ok )
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "/problems/add_problem.php",
dataType: "json",
data: dataString,
success: function(json)
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
So my question is how do I make this get invoked only when the right form is submitted? The form would have some id="some_name" but I don't really understand how to make this jQuery code get executed only when that form element is called.
And here is the form I am calling to display in the popup:
<?php
echo '<div id="login_div">
<form id="login_form" method="post" action="">
<p>
<label for="name"><span>Your Email:</span></label> <input type="text" name="email" />
</p>
<p>
<label for="name"><span>Your Password:</span></label> <input type="password" name="user_pass">
</p>
<p>
<input type="submit" value="Log In" />
</p>
</form>
</div>
<p>
Create Account | Reset Pass
</p>
';
?>
and here is the problemio.js contents with the jQuery to handle the login form submit:
// javascript library
// login_form
$(function()
{
$("#login_form input[type=submit]").click(function()
{
console.log("test");
alert("1");
// var name = $("#problem_name").val();
// var problem_blurb = $("#problem_blurb").val();
// var dataString = 'problem_name='+ name + '&problem_blurb=' + problem_blurb;
// if(name=='' || problem_blurb == '')
// {
// $('.success').fadeOut(200).hide();
// $('.error').fadeOut(200).show();
/// }
// else
// {
// $.ajax({
// type: "POST",
// url: "/problems/add_problem.php",
// dataType: "json",
// data: dataString,
// success: function(json)
// {
// $('.success').fadeIn(200).show();
// $('.error').fadeOut(200).hide();
//
/// // Here can update the right side of the screen with the newly entered information
// //alert (json);
//
// new_string = "<h2>Most Recently Added Problems</h2>";
// Have to figure out how to make this work with the DOM.
// }
// });
// }
return false;
});
});
Two things. First, when you place the code above into a separate javascript file, be sure to remove the <script ..> and </script> HTML tags.
Next, alter the following line:
$("input[type=submit]").click(function()
To instead say:
$("#loginform input[type=submit]").click(function()
And then set id="loginform" on your <form> tag.
You can use .submit() to attach a handler to the form submit event. First you'll need to select your form via the id:
$("#some_form_id").submit(function() {
// the code you have in the click event above goes here.
});
You can specific the form you want to trigger the jquery. http://api.jquery.com/submit/
If you are not sure, just right-click this webpage and read its html code.
<script type="text/javascript" src="some.js"></script>
And also, binding the the function to form.submit is much better than to the submit button.
$('formid').submit(function(){blablabla;return false;})
If you would like to handle the click event for every submit on the page without using ids, you can always use the this keyword in the click event to find the sender and then find the parent form.