How to access the global variable in Ajax sucess of kendo grid update? - ajax

Currently Developing web Application using AngularJS using with Kendo. When I save inline edit grid need to hide my save button and want to show back the Add button. For Show and Hide I use *ngIf. In this class I define public isAddEdit: Boolean; I cannot access the variable in success scope.
update: function (options) {
$.ajax({
url: HttpUrl.UpdateBlog,
contentType: "application/JSON",
type: "POST",
data: JSON.stringify(options.data.models),
success: function (result) {
options.success(result);
this.isAddEdit = false;
$('#save').remove();
$('#grid').data('kendoGrid').dataSource.read();
},
})
This is my view
<div id ="btndiv" class="col-sm-12">
<button *ngIf="!isAddEdit" id="addblog" class="k-button grid-top-button-override k-primary add-button page-name" (click)="addStock()">{{'Addblog' | translate}}</button>
<button *ngIf="isAddEdit" id ="save" class="k-button grid-top-button-override k-primary save-button page-name" (click)="clicksave()">{{'Save' | translate}}</button>
</div>
<div class="row grid-override">
<div id="grid"></div>
</div>

I think that the this is related to the AJAX callback function therefore you are not accesing the variable you want.
Try it with an arrow function:
success:(result) => {
options.success(result);
this.isAddEdit = false;
$('#save').remove();
$('#grid').data('kendoGrid').dataSource.read();
},

Related

On Ajax success, modal will only fire on second form submission

I have a simple form that shows a modal popup upon ajax success. It works great the 2nd time its used in same session. The modal will never show on the first form submission. What could be causing the modal not to fire the first time around? Maybe the page refresh or form reset?
$(document).ajaxSend(function(event, request, settings) {
$('#loading-indicator').show();
$("#submitbtn").prop('disabled', true);
});
$(document).ajaxComplete(function(event, request, settings) {
$('#loading-indicator').hide();
$("#output").fadeTo(4000, 500).slideUp(500, function(){
$("#output").slideUp(500);
});
$("#myform")[0].reset();
$("#submitbtn").prop('disabled', false);
setTimeout(function(){// wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 5000)
});
$(function () {
// init the validator
// validator files are included in the download package
// otherwise download from http://1000hz.github.io/bootstrap-validator
$('#myform').validator();
// when the form is submitted
$('#myform').on('submit', function (e) {
// if the validator does not prevent form submit
if (!e.isDefaultPrevented()) {
var url = "add_report.php";
var formData = new FormData($('#myform')[0]);
$.ajax({
url: 'add_report_do.php',
enctype: 'multipart/form-data',
type: 'POST',
data: formData,
success: function(response) {$("#successModal").modal("show");},
contentType: false,
processData: false,
cache: false
});
return false;
}
})
});
<div id="successModal" class="modal modal-blur fade" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-body">
<p>Fishing report successfully added.<br /></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn- btn-primary" data-dismiss="modal">OK</button>
</div>
</div>
</div>
Well I figured it out. require.js and jquery were stepping on each other. Added a line to require.config to isolate jquery. Works fine now
define('jquery', function () { return jQuery; });

Route [ ] not defined

i wan to be able to dlete a price whereby upon clicking the delete button a modal appears which then shows the yes or no delete buttons.here is the ajax function in the view which contains the delete button
function removeogFuelPriceModel(id)
{
$.ajax({
url: "{{route('industryfuelprice.edit.modal')}}",
type: 'post',
'headers': {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
},
data: {
'id': id,
},
success: function (response) {
$("#showEditInventoryModal").html(response);
$("#showMsgModal").modal('show');
},
error: function (e) {
console.log('error', e);
}
});
}
here is a div inside the modal which contains the id which redirects to the delete ajax function
<div class="row"
style="width: 100%; padding-left: 0px; padding-right: 0px;">
<div class="col col-m-12 text-center">
<button type="button"
class="btn bg-primary primary-button"
**onclick="deleteData({{$oilgas->id}})"**
data-dismiss="modal">Yes</button>
<button type="button"
class="btn btn-danger primary-button"
data-dismiss="modal">No</button>
</div>
</div>
here is the ajax function in the modal
function deleteData(id) {
const url = "{{ route('industryoilgas.destroyFuelprice', ['model_id' => "MODEL_ID"]) }}".replace("MODEL_ID", id);
$.ajax({
url: url,
method: "POST",
enctype: 'multipart/form-data',
success: function (response) {
$("#showMsgModal").modal('hide')
$("#showEditInventoryModal").html(response)
$('#showMsgModal').modal('show');
$("#addFuelPrice").attr("disabled", false);
$("#addFuelPrice").css({"cursor":"pointer;"});
loadFuelPrice();
}, error: function (e) {
console.log(e.message)
}
});
}
here are my routes
Route::post('show-industry-fuel-price-edit-modal','IndustryOilGasController#showEditModalFuelPrice')->name('industryfuelprice.edit.modal');
Route::post('delete-fuel-price/{id}', 'IndustryOilGasController#destroyFuelprice')->name('industryoilgas.destroyFuelprice');
i don't understand why am getting that error
Make sure you have defined removeogFuelPriceModel() and deleteData() within a blade component, because an Laravel helper method cannot be resolved outside a predefined php file. In this case, you are mostly defining those methods inside a JS file which won't work properly. To address this issue, you may inject those methods inside a script layout within the blade component. I wish this could help you out!

Django - AJAX - how to submit multiple forms?

Here are my two ajax codes for two forms. These two codes are exactly the same, except for button ID
$("#form_1_submit").on('click', function (e) {
e.preventDefault();
var form = $(this).closest("form");
var data = form.serializeArray();
$.ajax({
url: "",
dataType:"json",
type: "POST",
data: data,
success: function() {
alert('ajax request')
},
error: function() {
alert("error")
}
});
console.log(form.html())
});
$("#form_1_submit").on('click', function (e) {
e.preventDefault();
var form = $(this).closest("form");
var data = form.serializeArray();
$.ajax({
url: "",
dataType:"json",
type: "POST",
data: data,
success: function() {
alert('ajax request')
},
error: function() {
alert("error")
}
});
console.log(form.html())
});
And here is my views.py:
class BHA_UpdateView(UpdateView):
model = Different_Model
fields = '__all__'
def post(self, request, **kwargs):
if self.request.is_ajax():
print(self.request.POST)
form_1 = Form_2(request.POST, instance=Model_1.objects.filter(#some_filtering...)
form_2 = Form_1(request.POST, instance=Model_2.objects.filter(#some_filtering...)
if form_1.is_valid():
form_1.save()
return super().post(request, **kwargs)
if form_2.is_valid():
form_1.save()
return super().post(request, **kwargs)
return super().post(request, **kwargs)
There are two problems:
First: $.axax({...}) gives error, instead of success, and I don't know why. But it still saves to DB.
Second: Submitting one form results in the other form's values not saving to DB. This is my current page:
Ideally, clicking one of the Save button should result in saving data to each respective tables in DB. But if I click Save for Overall BHA, it saves
{'bha_name': 'form_1', 'depth_in' : 'form_1', 'depth_out': 'form_1'},
but at the same time saves this to my DB's table for Drill Bit:
{'bit_type': '', 'size': '', 'bit_model': ''}
emptying out the stored values for the table.
why this is happening, and how do I fix it?
++ form_1.is_valid() always returns True. I think this is why form_2's values are empty.
You could render several forms inside a single HTML form element and submit them all together without ajax
<form method="post">{% csrf_token %}
<div class="form-row">
<div class="col-sm">{{ form_a.as_p }}</div>
</div>
<div class="form-row">
<div class="col-sm">{{ form_b.as_p }}</div>
</div>
<div class="form-row">
<div class="col-sm">{{ form_c.as_p }}</div>
</div>
<button type="submit" class="save btn btn-default">Save</button>
</form>

AJAX Post to MVC Controller model every time empty

I am trying to send some data from a modal dialog to my controller with Ajax. But my modelfields are always null, but I enter my actionmethod in the controller.
This is a shortend version of my cshtml-file.
#model anmespace.MyModel
<form method="post" id="formID">
...
<div class="row">
<div class="col-md-5">#Resource.GetResource("MyModal", "Firstname")</div>
<div class="col-md-7"><input type="text" class="form-control" id="firstname" value="#Html.DisplayFor(model => model.FirstName)"></div>
</div>
...
<input type="submit" class="btn btn-primary" value="Submit" />
</form>
<script>
$("#formID").on("submit", function (event) {
var $this = $(this);
var frmValues = $this.serialize();
$.ajax({
cache: false,
async: true,
type: "POST",
url: "#Url.Action("ActionName", "Controller")",
data: frmValues,
success: function (data) {
alert(data);
}
});
});
</script>
Sorry MVC/Ajax are really new for me.
If you want to bind the form data to model then, the names of HTML elements should match with Model properties.
Note: name attribute value of html input field should match to the property of a model.
When you use form and submit button then it will try to reload the page by posting data to the server. You need to prevent this action. You can do this by returning false on onSubmit event in the Form element.
When you use jquery, do not forget to keep the ajax call/events inside the $(document).ready(function(){}) function.
I have written a simple code which takes First Name as input and makes an ajax call on clicking on submit button.
Html & Jquery Code:
<script>
$(document).ready(function() {
$("#formID").on("submit", function(event) {
var $this = $(this);
var frmValues = $this.serialize();
$.ajax({
cache: false,
async: true,
type: "POST",
url: "#Url.Action("PostData", "Home")",
data: frmValues,
success: function(data) {
alert(data.FirstName);
}
});
});
});
</script>
<div>
<form method="post" id="formID" onsubmit="return false;">
<input id="FirstName" name="FirstName"/>
<input type="submit" value="submit" />
</form>
</div>
My Model :
public class Person
{
public string FirstName { get; set; }
}
Action Method:
public ActionResult PostData(Person person)
{
return Json(new { Success = true, FirstName = person.FirstName });
}
Output:

Ajax call if textarea not in form with form nesting problem as well

System I working on is CMS where you insert templates like Contact form template and save that to database. This template is coded against server side to process data.
Now my "contentDiv" within form where all the templates were insert and saved than showed on the page withint form tag wrapped like
#using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { id = "first" }))
{
#Html.Hidden("someId", #Model.PageId)
}
<div id="contentDiv" style="width:100%">#Html.Raw(Model.Html)</div>
Above form is than saved as
$(function () {
$("form#first").submit(function (e) {
e.preventDefault();
var viewmodel = {
Id: $("#someId").val(),
Html: $("#contentDiv").val()
};
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: JSON.stringify(viewmodel),
dataType: "json",
contentType: "application/json; charset=utf-8",
beforeSend: function () { $("#status").fadeIn(); },
complete: function () { $("#status").fadeOut(); },
success: function (data) {
var message = data.Message;
},
error: function () {
}
});
});
});
notice that I moved "contentDiv out of form tag as my contact form which is wrapped in a form tag can not be nested within id=first form.
Is there a solution to form nesting? . If not than
My another question is
contentDiv is not wrapped up in form tag that means if client browser has javascript disabled than he wont be able to post contentDiv data to server and form will be of no use.
What to do?
If I don't move contentDiv out of form tag than than after inserting template the structure will be nesting of forms
#using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { id = "first" }))
{
<form id="contactform" action="/Home/Email" method="post" >
<div class="clear" style="padding-bottom:10px;"></div>
<div class="formCaption">Full Name</div>
<div class="formField"><input id="fullName" name="fullName" class="standardField" /></div>
<div><input id="sendBtn" value="Send" type="button" /></div>
</form>
}
I didn't understand from your description why the html needs to be outside the form. Also you should not use the .val() method for divs. You should use .html():
var viewmodel = {
Id: $("#someId").val(),
Html: $("#contentDiv").html()
};
Of course because you are using javascript to fetch the html which is outside of the main form if client browser has javascript disabled the form will be of no use. Only if you move the html inside the main form would this work without javascript:
#using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { id = "first" }))
{
#Html.HiddenFor(x => x.PageId)
#Html.HiddenFor(x => x.Html)
<input type="submit" value="Edit" />
}
<!--
You could still keep the div for preview or something but don't make
any use of it when submitting.
-->
<div id="contentDiv" style="width:100%">
#Html.Raw(Model.Html)
</div>

Resources