HTML button not displaying on success of ajax - javascript

I need to display an input button on the success message in my view. I am working in MVC 3 application using razor views. This button will allow the user to navigate to another view.
Controller.
var successfull = new string[]
{
"All " + builder.Data.Count.ToString() + " work items were added successfully."
};
return new JsonResult
{
Data = new { success = true, msg = successfull}
};
JavaScript.
var jsonText = JSON.stringify(json);
$.ajax({
url: '/Builder/CreateWork',
type: 'POST',
dataType: 'json',
data: jsonText,
contentType: 'application/json; charset=utf-8',
success: function (result) {
// clear table
$('#instruments-data').empty();
resultMessage(result);
},
complete: function () {
// hides the loading gif
$('.loading').hide();
}
});
View
<div id="resultMessage"></div>
Is there a way to add to the ajax code to include the following input button.
<input type="button" class="styledbutton" value="Some text" onclick="window.location.href='Url.Action("action", "controller")';" />
EDIT ---
The problem lies with this piece of code - but can't see the problem.
onclick="window.location.href = '#Url.Action("actionName", "controllerName")'"/>');
Please advise.

The button is static so you can hide it
<input style="display:none" type="button" class="styledbutton" value="Some text" onclick="window.location.href='Url.Action("actionName", "controllerName")';" />
And then in success callback show it
success: function (result) {
// clear table
$('#instruments-data').empty();
resultMessage(result);
//show button
$(".styledbutton").show();
},

Yes you can generate html in ajax call as given below :
<div id="div1"><div>
success: function (result) {
// clear table
$('#instruments-data').empty();
resultMessage(result);
$('#div1').html('<input type="button" class="styledbutton" value="Some text" onclick="window.location.href='#Url.Action("actionName", "controllerName")'/>')
}
Above Code will work fine,just generate html in ajax call as above.

You can do this in a simple way. As you have been advised, you can hide the button initially using css.
<input type="button" class="styledbutton" style="display:none;" value="demo" onclick="window.location.href='Url.Action("actionName", "controllerName")';"/>
you just need little bit tweak in your js code if everything behind the scenes is working fine (i mean model and controllers).
use done() instead of success and likewise always() instead of complete if you are using jQuery v 1.8 or higher. Check the deprecation notice in docs. success and complete are no longer in use as of jQuery 1.8+
$.ajax({
url: '/Builder/CreateWork',
type: 'POST',
dataType: 'json',
data: jsonText,
contentType: 'application/json; charset=utf-8'
}).done(function(result){
// clear table
$('#instruments-data').empty();
resultMessage(result);
//just show the button
$(".styledbutton").show();
}).always(function(){
// hides the loading gif
$('.loading').hide();
});
Note: Place your button exactly where you want to see it on view and make it display:none. Ajax will handle the rest. Let me know if it doesn't work.

None of the previous answers were allowing for re-direct, so I found a work around.
success: function (result) {
// clear table
$('#instruments-data').empty();
resultMessage(result);
$('#resultMessage').append('<input type="button" id="MultiStatus"class="styledbutton" value="Button text" />');
$('#MultiStatus').click(function (e) {
location.href = "/Controller/Action";
});

If you want advice, i would suggest you to try anchor button with bootstrap styling to reflect the feel of a button.
can you please try this if that doesn't hurt your intention.
example:
#Html.ActionLink("ButtonText", "ActionName", "ControllerName", null, new { #id = "Query", #class = "btn btn-inverse styledButton" })
i have included a jsbin demo about how to use the button for your specific need, please follow this link: Demo
Feel free to comment if you need any explanation

Related

jquery-modal keeps last input

I want to use the jquery-modal plugin to make comments for several form elements. Its working fine, as long there is no keyboard input. Otherwise it remembers the last input and keeps that in the textarea, even if I empty it before.
This is the form that is shown in the modal window.
<a title="" href="#" onclick="getRechKomm('12345'); return false;" class="edit_komm">Kommentar</a>
<form id="RechKommForm" class="none">
<h3></h3>
<p><textarea name="kommentar" id="ptrRechKomm"></textarea></p>
<p><input type="hidden" name="rechid" id="ptrRechKommID" value=""></p>
</form>
<script>
function getRechKomm(rechnr){
$('#ptrRechKomm').html('');
$.ajax({
type: "POST",
url: "ptr_getrechkomm.php",
data: {rechnr: rechnr},
success: function(data){
readSession();
$('#ptrRechKomm').html(data);
$('#ptrRechKommID').val(rechnr);
$('#RechKommForm').modal({
escapeClose:false,
clickClose: false,
fadeDuration:500
});
}
});
}
$('#RechKommForm').on($.modal.BEFORE_CLOSE, function(event, modal) {
$.ajax({
type: 'POST',
url: 'ptr_putrechkomm.php',
cache: false,
data: $("#RechKommForm").serialize(),
success: function (data) {
$('#ptrRechKomm').html('');
$('#ptrRechKommID').val('');
}
});
});
</script>
So if call the comment for the ID 12345 and write a comment "Komm 12345", everything is fine. After that I call the comment for ID 23456, that may be already "Komm 23456". It is loaded from the database and put into the textarea #ptrRechKomm, but the first text is still there. So in the textarea is "Komm 12345Komm 23456".
Where is the old content coming from and how to delete it?
Update: Forget that all! Don't know why, but I thought that a textarea has to be filled by html(). Thats working, but only once. Filling it by val() is the correct way!

jQuery not working after Ajax post

I'm currently working with an MVC page where I'm using Grid.Mvc table. I also have some search fields where I can update the table via Ajax Post, once I use the search fields and submit for sorting the html gets replaced on post-back, once replaced, the grid rows can NOT be clicked like before the Ajax call, is like the ajax call is killing the javascript or Jquery or both,
here is code for the Ajax call for the grid:
$(function() {
$(document) on.("click", "#buscar", function() {
$.ajax({
url: '/MainPage/Grid',
type: 'POST',
async: false,
datatType: 'html',
processData: true,
data: {
url: $('#url').val(),
isInternal: ('#isInternal').val()
},
success: function(data) {
$('#grid').html(data);
}
})
});
});
Here is the code for when I click the rows I send another Ajax call, but after the first code post the grid becomes unclickable;
$(function() {
pagesGrids.linksgrid.onRowSelect(function() {
$.ajax({
url: '/mainpage/getlinkdetails',
type: 'POST',
async: false,
dataType: 'html',
processData: true,
data: {
id: e.row.BrokenId
},
success: function(data) {
$('#linkdetails').html(data);
},
error: function() {
alert('something went wrong')
}
})
});
})
Any help or hint that can point me in the right direction will greatly appreciated, thanks
UPDATE
The the grid it self is a partial view rendering at Index on MVC
<div id="grid">
#Html.Action"Grid"
</div>
Your partial view is rendering new elements into the page rather than altering the existing elements.
You will need to rebind the javascript events (click) to the new elements after the partial postback.
Although this is an old post, I found a solution that worked for me, and hope it works for someone else.
AJAX forms have a data dash attribute called data-ajax-complete, to which you can pass the name of a javascript function to run. That javascript function can contain the code you need to rebind the click events to all your elements.
<form asp-controller="Home" asp-action="SaveForm" data-ajax-complete="onComplete" data-ajax="true" data-ajax-method="POST">
<input type="submit" value="Save" class="btn btn-primary" />
<div id="Results"></div>
</form>
<script>
var onComplete = function(){
results.html("");
};
</script>
More details here.

Toggle div depending on controller variable value

EDITED
I have a "Save Changes" button that I want to click and toggle a div with the message "Changes saved". I do it like this:
HTML:
<input type="submit" id="savebtn" name="save" value="Save Changes"/>
<input type="hidden" id="res" name="res" value="#ViewBag.result"/>
<div class="success">Changes saved</div>
JQuery
$('#saveButton').click(function () {
var aux = res.value.toString();
if ($('#res').val() == "OK")
$(".success").show();
alert(aux);
});
However, I need the button to actually save the changes and, if the operation was successful, then show the message div. So, in my cshtml file I have a result variable that contains the success or failure of the operation.
CSHTML:
ViewBag.result = result;
Now, I need to show that message div depending on the result variable: I need to somehow make it a parameter for the JQuery function. I'm passing it in a ViewBag.
NOTE: when the page loads, the viewbag is empty. It only gets its value after the button click. And after that, the viewbag is filled and I wanted it to be used in the jQuery function but I'm not getting any luck.
Pass that result in a viewbag,
Acces that viewbag value in jquery and show/hide your div accordingly
Assuming you can store the result in input hidden field, use below query to access result and initially success div is hidden :
<input type="hidden" id="result" value"success"/>
jQuery :
$(function(){
if($('#result').val()=="success")
$(".success").show();
});
you can check it in a simple if condition
if($('#result').val()=="success")
$(".success").toggle();
or You can use Ajax method
function Save() {
$.ajax({
url: "Your Url", // Current Page, Method
data: Your data // better if you parameter map as JSON
type: "POST",
contentType: "application/json", // posting JSON content
dataType: "JSON", // type of data is JSON (must be upper case!)
timeout: 100000, // AJAX timeout
success: function (result) {
$(".success").toggle();
},
error: function (xhr, status) {
alert("An error occurred while processing");
}
});
}
Now call this save() in your button click

Unable to pass my Model from my Controller to my View using Jquery.Ajax

I'm relatively new to web app development, javascript and MVC so please bear with me.
I want to use the Jquery.Ajax command to post my Model to my controller.
My View:
#model MVC_Interface_May21.Models.DataValuesViewModel
...
<form method="post" id="testForm">
<input type="submit" class="subButton" value="Add New.." />
</form>
...
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'>
$(document).ready(function () {
$('#testForm').submit(function (e) {
e.preventDefault();
#{var val = Json.Encode(Model);}
var check = '#Html.Raw(val)';
$.ajax({
url: 'Results/AddNew',
type: 'POST',
//data: JSON.stringify(check),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
});
}
...
</script>
I haven't included the code for my Model or Controller because I don't believe they are a part of the problem. Currently, my code simply posts back to the same page. As far as I can tell the ajax command is not being executed. The debugger doesn't help me in tracing the behavior, and I am assuming that the form is simply doing it's post submit and ignoring my function.
Any help is much appreciated, and I'm sorry if this has been answered in the past. I developed my code by looking at other solutions, but I can't identify what's making mine dysfunctional.
You have to read more about it MVC, im not even sure what you are trying to do serializing the Razor Model like that, but that is what you are getting from the server, not your HTML Form with whatever the user input is.
You can use this js function to submit a form with Ajax.
$(function () {
$('#myForm').submit(function () {
if ($(this).valid()) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
$('#result').html(result);
}
});
}
return false;
});
});
And use the Create Form and imput helpers/
#Html.BeginFor
#Html.EditorFor

jQuery submit doesn't handle "success"

I've gone through all of the solutions I could find on Stack Overflow and Google but none of them seem to help.
I have a function in Clojure (Noir framework) that takes two keys, "text" and "day-of-note" and inserts the values into a database. Regardless of whether or not that works, the function returns a JSON response with {"result":true} (for testing purposes).
(defpage [:post "/newpost"] {:keys [text day-of-note]}
[]
(println "newpost called")
(post text)
(response/json {:result true}))
My form is a simple form with one textarea, a checkbox and a button.
<form action="/newpost" id="new-post" method="post">
<textarea id="entry" name="text">Insert todays happenings</textarea>
<br />
<input checked="checked" name="day-of-note" type="checkbox" value="true">
<input type="submit" value="Add entry">
</form>
When submitting the form I have added a call to alert to show me the contents of dataString and they are formatted correctly ("text=lalala&day-of-note=true").
$(function () {
$("#new-post").submit(function (e) {
e.preventDefault();
var dataString = $("#new-post").serialize();
alert(dataString);
$.ajax({
url: "/newpost",
type: "POST",
dataType: "json",
data: dataString,
success: function () {
alert("Success!");
};
});
return false;
});
});
What happens here when the code is as it is above, there is a HTML call to /newpost when the user click on the button and the page shows {"result":true}. If I comment out the "$.ajax"-part the message box pops up with the correct content, but if I remove the comments -- no message box, just goes straight to /newpost.
What I thought was supposed to happen was that the /newpost page would never be rendered but a call with the dataString would be put to it by Ajax and a message box with "Success!" would be shown.
Where am I taking the wrong turn?
Remove the semi-colon after the success function declaration:
success: function () {
alert("Success!");
}
The success function declaration is part of an object, which separates declarations by comma.

Categories