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.
Related
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!
I'm sure there's a simple explanation for this but I haven't been able to find the right words to use when searching for answers.
When users fill out the form .InvoiceForm it submits via Ajax. After it's submitted remove the .InvoiceForm class and add .UpdateInvoice. When a user submits a .UpdateInvoice form it explains that they are about to make a change and they have to click to say "Yes I want this to be updated".
The issue is that unless I refresh the page so that the form is loaded with the .UpdateInvoice form, I don't get the confirmation which means it's still submitting as a .InvoiceForm form. Is there anything I can do to fix this?
Edit to show code:
Code that runs if there's no record
$('.InvoiceForm').submit(function(e) {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
cache: false,
dataType: 'json',
context: this,
data: $(this).serialize(),
beforeSend: function() {
$(".validation-errors").hide().empty();
},
success: function(data) {
$(this).removeClass('InvoiceForm');
$(this).addClass('UpdateInvoice');
$(this).find('.btn').val('Update');
$(this).find('.id').val(data.invoice_id);
$(this).find('.btn').removeClass('btn-default');
$(this).find('.btn').addClass('btn-danger');
$(this).find('.AddRow').removeClass('hide');
$(this).find('.invoiceDetails').html(data.returnedData);
$(this).parent().next().find('.grade').focus();
}
});
return false;
};
Code that runs if there is a record being updated
$('.UpdateInvoice').submit(function(){
var r = confirm("Are you sure you want to make this update?");
if (r == true) {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
cache: false,
dataType: 'json',
context: this,
data: $(this).serialize(),
beforeSend: function() {
$(".validation-errors").hide().empty();
},
success: function(data) {
alert('This row has been updated');
$(this).find('.total').html(data);
}
});
} else {
}
return false;
});
The function for .UpdateInvoice doesn't run unless I refresh the page.
Thanks for your help.
You bind a click event on '.UpdateInvoce' before it even being created, hence it'll not work. I think you need to use .live() in order to make it works. See document here: jQuery's live()
HTML:
<button id="click_me" class="new">Click Me</button>
<div class="result" />
Script:
$(function () {
$('.new').click(function (e) {
$('.result').text("Im new !");
$(this).removeClass("new");
$(this).addClass("update");
// Bind UpdateInvoice's click event on the fly
$('.update').live(bindUpdate());
});
function bindUpdate() {
$('.update').click(function (e) {
$('.result').text("Update me !");
});
}
});
jsfiddle's demo
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
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
Firstly, there have some tag links in my main page. click each one, post value to b.php with jquery.ajax and turn back value in div#result.
b.php have a search box. when search something in it. the result data will still show in the div#result.
my problem is: I know if I will do jQuery ajax in the b.php, I shall write the jQuery code in the first success part. but this only can control one time, when I continue search in the search box, the jQuery not work. I think I met a loop problem. How to solve it?
a.php
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.click').click(function(){
var value1 = $(this).text();
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data=" + value1,
success: function(data){
$("#result").html(data);
$('#search').click(function(){
var value = $('#search1').val();
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data=" + value,
success: function(data){
$("#result").html(data);
}
});
});
}
});
});
});
</script>
<a rel="aa" class="click">aa</a>
<a rel="aa" class="click">bb</a>
<div id="result"></div>
b.php
<?php
echo $_POST['data'];
?>
<form name="form">
<input type="text" value="" id="search1">
<a name="nfSearch" id="search">search</a>
</form>
When a new element is introduced to the page the jQuery .click() method becomes useless because it can only see elements that were part of the original DOM. What you need to use instead is the jQuery .live() method which allows you to bind events to elements that were created after the DOM was loaded. You can read more about how to use it at the below link.
.live() – jQuery API
$('#search').live('click', function(e) {
// Prevent the default action
e.preventDefault();
// Your code here....
});
First of all i think you should attach the ajax call to the click on the link: the way you are doing right now just execute an ajax call as soon as the page is loaded.
$(document).ready(function(){
//when you click a link call b.php
$('a.yourclass').click(function(){
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data = something",
success: function(data){
$("#result").html(data);
var value = $('#search').val();
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data =" + value,
success: function(data){
$("#result").html(data);
}
});
}
});
});
});
In this way, each time a link with the class of "yourclass" is clicked an ajax call to b.php is sent and if it succed, another call is made (always to b.php). I don't understand if this is what you are looking fo, if you post your html my answer can be better.
In b.php of course you need to echo some html that can be used in the callback
It's strange how your attempting to do two ajax requests like that, surely one is enough. If you need to support multiple text boxes then you just adjust your selectors.
Your whole code can be shortended down to something like this:
$(document).ready(function() {
$('#result').load('b.php', { data: $('#search').val() });
});
So if you wanted to search for the value when clicking on a link (for links within #container):
$('#container').delegate('a', 'click', function() {
// .text() will get what's inside the <a> tag
$('#result').load('b.php', { data: $(this).text() });
});