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

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; });

Related

Ajax call is being accidently triggered

I'm creating a login page and at the bottom of the pop-up form, there is another button that takes you to the registration page. The issue appears to be that when navigating to the new page it all sits under the original sign-in form which uses an ajax call to check if the user exists so when they try to submit the registration form it then calls that ajax call from the sign-in form.
Sign-in form
<div id="myForm">
<form onsubmit="return false;" id="loginForm">
<h1>Login</h1>
<label for="email"><b>Email</b></label>
<input type="email" id="email" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" id="psw" placeholder="Enter Password" name="psw" required>
<div id="message" class="alert-danger"></div>
<br />
<button type="submit" id="submit" class="btn">Login</button>
<button type="button" class="btn cancel" onclick="closeForm();">Close</button>
</form>
<div class="d-inline">
<button class="btn-info">#Html.ActionLink("User Registration", "SignUp", "SignUp_SignIn")</button>
</div>
</div>
Then the ajax call is
$(document).ready(function () {
$("form").on('submit', function (event) {
var data = {
'email': $("#email").val(),
'psw': $("#psw").val()
};
$.ajax({
type: "POST",
url: 'SignUp_SignIn/CredentialCheck',
data: data,
success: function (result) {
if (result == true) {
$("#message").text("Login attempt was successful");
}
else {
$("#message").text("Email/Password didn't match any results");
}
},
error: function () {
alert("It failed");
}
});
return false;
});
});
After looking at the comments I realized that the reason that the login form was being called from the layout.cshtml so when the ajax call was being called it was grabbing all the form tags that existed on any page that was loaded up. After changing the ajax so it was calling a specific id for the login form instead of form it allowed for proper actions to take place.
An example of what I'm refusing to
$(document).ready(function () {
$("form").on('submit', function (event) {
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
//Do stuff
}
});
});
});
The above will try to redirect you on the submit of any form that is loaded up, but if we go through and change the way it accesses the form like below then it will only work if the one specific form is submitted.
$(document).ready(function () {
$("#loginForm").on('submit', function (event) {
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
//Do stuff
}
});
});
});

I have a probllem when the button delete has clicked but the data cannot delete and the url not show the id

I have tried to solve this problem several hours but I never solve this problem
I have a problem with my code, when I click the delete button from json, I can't get the ID just link from the console like this:
example :
That happened : request
I want Like this : request/?id=1
I paste some code to check :
Controller request.php:
public function delete()
{
// $this->m_request->delete($this->input->post('id_form'));
$id = $this->input->post('id_form');
$data = $this->m_request->DeleteRequest($id);
echo json_encode($data);
}
Model m_request.php:
public function DeleteRequest($id)
{
$hasil = $this->db->query("DELETE FROM request WHERE id_form='$id'");
return $hasil;
}
And Then View (I just put the modal script and ajax json script) :
Modal View :
<div class="modal fade" id="ModalHapus" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="myModalLabel">Hapus Request</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">X</span></button>
</div>
<form class="form-horizontal">
<div class="modal-body">
<input type="hidden" name="kode" id="textkode" value="">
<div class="alert alert-warning">
<p>Apakah Anda yakin mau menghapus request ini?</p>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Tutup</button>
<button class="btn_hapus btn btn-danger" id="btn_hapus">Hapus</button>
</div>
</form>
</div>
</div>
Ajax/JSON Script :
//GET HAPUS
$(document).on('click', '.hapus', function() {
var id = $(this).attr('data');
$('#ModalHapus').modal('show');
$('[name="kode"]').val(id);
})
// Hapus Request
$('#btn_hapus').on('click',function(e){
e.preventDefault();
var id = $('textkode').val();
$.ajax({
type: "POST",
url: "<?= site_url('request/delete')?>",
dataType: "JSON",
data: {id:id},
success: function(data){
// $('#ModalHapus').modal('hide');
console.log(data)
load_data();
}
});
return false;
})
There are a lot of reasons why the ajax request is possibly not working. The first thing which came in my mind is, that you have not specified an ID and method of the input form. Make sure you have both in your HTML form tag. For example:
<form id=“id_form” method=“post” class=“...”>
...
<input type="text" name="kode" id="textkode">
</form>
In you JS Code do the following
$.ajax({
type: "POST",
url: "<?= site_url('request/delete')?>",
dataType: "JSON",
data: $(“#id_form”).serialize(),
success: function(data){
console.log(data)
load_data();
}
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nERROR: "+ err);
}
});
Also change the your delete function to this:
public function deleteTableRow()
{
$id = $_POST['textkode']; // Because I'm not sure what this->input->post() makes
$result = $this->m_request->DeleteRequest($id);
echo json_encode(array('id' => $id, 'result' => $result)); // The contents of array should then be displayed in the console of your webbrowser
}
Note that I changed the function name. It could be very misleading for other programmers, because delete is used in many programming languages as destructor for dynamic objects!
Additionally I would recommend to create an ajax.php file to parse different kind of ajax request. This file would also work as a controller, but just for ajax calls. In case you have several forms, the code is more readable.

ajax form in CodeIgniter - sending generated form

I want to open a modal and get the content (the formular) form the controller. These steps work fine.
Now I have the formular inside the modal. How I can submit these formular and process it with the same controller function?
At the Moment I do the Ajax-Call in this way
$('.modaldisconnect').click(function(){
var modid = $(this).attr('modid');
$.ajax({
url: "<?php echo base_url() ?>admin/module/disconnect_form",
method: "POST",
data: {modid:modid},
// Callback function that is executed after data is successfully sent and received
success: function(data){
// Print the fetched data of the selected phone in the section called #phone_result
// within the Bootstrap modal
$('.modal-ajax-content').html(data);
// Display the Bootstrap modal
$('#disconnect_modal').modal('show');
},
error: function(error){
// Show error message
alert('error');
}
});
});
This is the form which will be generate from the controller by the call above
echo' <div class="modal-body">
<div id="modul_disc_infos">
<span class="module-headlines-title">'._l("modul_name").': <span id="disc_modulname">'._l('module_'.$result->folder.'_titel').'</span></span>
<span class="module-headlines-subtitle">'._l("modul_disconnect_deadline").': <span id="disc_enddate">'.$enddate.'</span></span>
</div>
<div id="modul_disc_check">
<div class="alert alert-danger" role="alert">'._l("modul_disconnect_disclaimer").'</div>
<hr>
<input type="checkbox" name="check_disclaimer" value="1"> '._l("modul_disconnect_disclaimer_check").'
<input type="hidden" name="modid" value="'.$this->input->post('modid').'">
<input type="hidden" name="formstep" value="1">
'.$errormsg.'
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">'._l('close').'</button>
<button type="button" class="btn btn-danger" id="submit_disconnect" >'._l('modul_disconnect_now').'</button>
</div>';
By the way - is there a better way to parse the values of the formular instead one by one like in my code "var modid = $(this).attr('modid');"?
I've solved that in this way that i do 2 different ajax call, starts with a click or submit on the form or a specific button. One call generate the form, one call handle the form. For me it works and its a little bit flexibel to use the same functions for different jobs.
//Formular for disconnection
$('.modaldisconnect').click(function(){
var modid = $(this).attr('modid');
$('#ajax_modal_title').html('<?php echo _l('modul_disconnect'); ?>');
$.ajax({
url: "<?php echo base_url() ?>admin/module/disconnect_form",
method: "POST",
data: {modid:modid},
// Callback function that is executed after data is successfully sent and recieved
success: function(data){
// Print the fetched data of the selected phone in the section called #phone_result
// within the Bootstrap modal
$('.modal-ajax-content').html(data);
// Display the Bootstrap modal
$('#ajax_modal').modal('show');
},
error: function(error){
// Show error message
alert('error');
}
});
});
//Handle the disconnection
$("#ajax_form").on("submit", function (event) {
event.preventDefault();
subform=$('input[name="subform"]').val();
$.ajax({
url: "<?php echo base_url() ?>admin/module/"+subform+"_form",
type: "POST",
data: $('#ajax_form').serialize(),
success: function(result){
$('.modal-ajax-content').html(result);
},
error: function(error){
// Show error message
alert('error');
}
});
});

Form post from partial view to API

I am trying to create an SPA application using Sammy. When I call #/entitycreate link, I return a partial view from Home controller which contains an html form to submit. Partial view comes as I expect but rest of it doesn't work. Below are my problems and questions, I'd appreciate for any help.
KO binding doesn't work in partial view, even though I did exactly how it's done in the default SPA project template (see home.viewmodel.js).
This one is the most critical: when I submit this form to my API with ajax/post, my model always comes back with a null value, therefore I can't create an entity via my API. I have tried with [FromBody] and without, model always comes null.
In some sense a general question, should I include Html.AntiForgeryToken() in my form and [ValidateAntiForgeryToken] attribute in my API action?
Partial View:
#model namespace.SectorViewModel
<!-- ko with: sectorcreate -->
<div class="six wide column">
<div class="ui segments">
<div class="ui segment">
<h4 class="ui center aligned header">Create New Sector</h4>
</div>
<div class="ui secondary segment">
<form id="entity-create-form" class="ui form" action="#/sectorcreatepost" method="post" data-bind="submit: createEntity">
<!-- I am not sure if I should include AntiForgeryToken for WebAPI call -->
<!-- Html.AntiForgeryToken() -->
<fieldset>
<div class="field required">
#Html.LabelFor(m => m.Name)
#Html.TextBoxFor(m => m.Name, new { data_bind = "value: name" })
</div>
<div class="ui two buttons">
<button class="ui positive button" type="submit">Create</button>
<button class="ui button" type="button" id="operation-cancel">Cancel</button>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<!-- /ko -->
JS View Model:
function SectorCreateViewModel(app, dataModel) {
var self = this;
self.name = ko.observable("ko binding doesn't work");
self.createEntity = function () {
console.log("ko binding doesn't work");
}
Sammy(function () {
this.get("#sectorcreateget", function () {
$.ajax({
url: "/home/getview",
type: "get",
data: { viewName: "sectorcreate" },
success: function (view) {
$("#main").html(view);
}
});
return false;
});
this.post("#/sectorcreatepost",
function () {
$.ajax({
url: "/api/sectors",
type: "post",
data: $("#entity-create-form").serialize(),
contentType: "application/json; charset=utf-8",
success: function (response) {
console.log(response);
},
error: function (xhr, status, error) {
console.log(xhr);
console.log(status);
}
});
return false;
});
this.get("#/yeni-sektor", function () {
this.app.runRoute("get", "#sectorcreateget");
});
});
return self;
}
app.addViewModel({
name: "SectorCreate",
bindingMemberName: "sectorcreate",
factory: SectorCreateViewModel
});
API Action:
public HttpResponseMessage Post([FromBody]SectorViewModel model)
{
// model is always null, with or without [FromBody]
if (!ModelState.IsValid)
return Request.CreateResponse(HttpStatusCode.BadRequest);
// repository operations...
return response;
}
I have removed contentType: "application/json; charset=utf-8", from ajax request based on the article here. #2 is now resolved, #1 and #3 still remains to be answered.

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

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();
},

Resources