When I run this script I am getting AjaxFunction is undefined. I have searched and know that it is not defined in proper scope but can anyone let me know what is the correct way to define it and what is the reason for the error.
<script type=”text/javascript”>
function(AjaxFunction) {
alert(“test”);
$.ajax({
type: “GET”,
url: “cfquery.cfm”,
success: function (res) {
alert(res);
document.getElementById("loadingdiv").style.display = ”block”;
document.getElementById("loadingdiv").innerHTML = res;
}
});
};
</script>
<cfform id="PageloadAjax" name="PageloadAjax">
<div id="Displayingdiv" name="displayingdiv">
<cfinput id="CFQUERYbutton" name="CFQUERYbutton" type="button" value="Displaypage" onclick="AjaxFunction">
</div>
<div id="loadingdiv" name="loadingdiv"></div>
</cfform>
Right now you are defining an anonymous function with AjaxFunction as a parameter. Step one in getting this to works is to change
function(AjaxFunction) {...}
into
function AjaxFunction() {...}
Also, in the onClick attribute, you must call the function, not just name it. So change
onclick="AjaxFunction"
into
onclick="AjaxFunction()"
I recommend looking at some basic JavaScript material to more easily understand and solve these minor issues. You could start with W3 Schools for easily understandable tutorials, or You don't know JS if you want more in-depth JavaScript knowledge.
Try this
<script type=”text/javascript”>
function AjaxFunction() {
alert(“test”);
$.ajax({
type: “GET”,
url: “cfquery.cfm”,
success: function (res) {
alert(res);
document.getElementById("loadingdiv").style.display=”block”;
document.getElementById("loadingdiv").innerHTML=res;
}
});
};
</script>
And call function in onclick = "AjaxFunction()".
the answer that perfectly worked for me is:
<script type="text/javascript">
function AjaxFunction(mode) {
var url="";
if ( mode =="contacts") url = "cfquery.cfm";
if ( mode =="tagsvsscripts") url = "cfqueryprogram.cfm";
if ( mode =="siteinfo") url = "CFtagsvsscripts.cfm";
if ( mode =="Jqueryhide") url = "dynamic.cfm";
$.ajax({
type: "GET",
url: url,
success: function (res) {
$("#results").addClass("loading");
document.getElementById("loadingdiv").style.display="block";
$("#results").html(res);
$("#results").removeClass("loading");
}
});
}
</script>
<div class="card mb-4">
<div class="card-header bg-secondary">
Ajax Page Load Example Using Bootstrap
</div>
<div class="card-block">
<div class="row">
<div class="col-lg-3 col-xl-2 col-form-label">
<input class="btn btn-primary" name="CFQUERYbutton"
type="button" value="Displaypage" onclick="AjaxFunction('Jqueryhide')">
<br><input class="btn btn-primary"
name="CFQUERYbutton" type="button" value="Displaypage"
onclick="AjaxFunction('contacts')">
<br><input class="btn btn-primary"
name="CFQUERYbutton" type="button" value="Displaypage"
onclick="AjaxFunction('tagsvsscripts')">
<br><input class="btn btn-primary"
name="CFQUERYbutton" type="button" value="Displaypage"
onclick="AjaxFunction('siteinfo')">
</div>
<div id="loadingdiv" name="loadingdiv">
</div>
<div id="results"></div>
</div>
</div>
</div>
Related
I have a code on my Asp.Net Core APP which I want to handle exclusively through Modals and with responses from the Controller, which change depending on the values that are sent from the View.
Right now I have the following code, which, what it does is change the message in a div on the Modal, for the response it receives from the controller, with the button that calls said Modal.
General part of the view:
#model AP.ViewModels.UK1
<div class="container">
<div class="card level-3">
<h3>Ac</h3>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div class="form-group">
<input asp-for="UK2" class="form-control" />
<span asp-validation-for="UK2" class="text-danger"></span>
</div>
<div class="form-group">
<input asp-for="UK3" class="form-control" />
<span asp-validation-for="UK3" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="UK5" class="btn btn-primary" /> |
<!-- Button to Open the Modal -->
<button id="btnOpenModal" type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
CALL CONTROLLER / MODAL BUTTON
</button>
</div>
</form>
</div>
</div>
</div>
</div>
Modal Code on the View:
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">CONTROLLER RESPONSE:</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body" id="modalcontent">
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">CANCEL</button>
<button type="button" class="btn btn-primary" data-dismiss="modal">OK1</button>
</div>
</div>
</div>
</div>
Script which calls Modal and sent the data to the Controller:
<link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" href="~/css/site.css" />
<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script>
$(function () {
$("#btnOpenModal").click(function () {
var uk = {};
uk.UK2 = $("#UK2").val();
uk.UK3 = $("#UK3").val();
$.ajax({
type: "POST",
url: "/UK1/GetViewContent",
data: uk,
beforeSend: function (request) {
request.setRequestHeader(
"RequestVerificationToken",
$("[name='__RequestVerificationToken']").val());
},
success: function (data) {
$('#modalcontent').html(data);
},
error: function (response) {
$("#myModal").modal('toggle')
}
});
});
$("#myModal").on("click", ".btn-default", function () {
alert("Cancel button click");
});
$("#myModal").on("click", ".btn-danger", function () {
// code
alert("Delete button click");
$('#myModal').modal('hide')
});
});
</script>
Controller Code:
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult GetViewContent(UK1 uk)
{
if (uk.UK2 == uk.UK3)
{
return Ok("A-CASE 1");
}
if (uk.UK2 >= uk.UK3)
{
return Ok("B-CASE 2");
}
if (uk.UK2 <= uk.UK3)
{
return Ok("C-CASE 3");
}
if (uk.UK2 == null)
{
return Ok("D-CASE 4");
}
if (uk.UK3 == null)
{
return Ok("E-CASE 5");
}
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create(UK1 ukk)
{
return View("Home1");
}
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> CreateDos(UK1 ukk)
{
return View("Home2");
}
Now this is what I want to achieve with the code:
I would like my code to have 5 possible Modals, one for each possible response from the Controller, and that each one of these Modals had a different message, as well as different buttons, and my question is, how can I do it? Which are my options?
The first thing that comes to my mind is to have HTML code for 5 different Modals in view, and depending on which the Controller's response is, the code calls a different one of the Modals, the problem is that I don't know how to do that, since I don't know how to read the controller Response as a 'variable' in the script code, or how I should put "Ifs" that depend on the response there in the Script, but I understand that this should go in this part of the code:
success: function (data) {
$('#modalcontent').html(data);
},
error: function (response) {
$("#myModal").modal('toggle')
}
In any case, what I would like for my 5 Modals, is something similar to this:
1)If the answer that is received from the Controller is "A-CASE 1", the Modal should get an "A" message on the div, and just the Cancel button should appear at the botton of the Modal.
2)If the answer that is received from the Controller is "B-CASE 2", the Modal should get an "B" message on the div, and both the Ok and Cancel button should appear at the botton of the Modal, the Ok Button should call me the Controller's Create method.
3)If the answer that is received from the Controller is "C-CASE 3", the Modal should get an "C" message on the div, and both the Ok and Cancel button should appear at the botton of the Modal, the Ok Button should call me the Controller's CreateDos method.
4)If the answer that is received from the Controller is "D-CASE 4", the Modal should get an "D" message on the div, and just the Cancel button should appear at the botton of the Modal.
5)If the answer that is received from the Controller is "E-CASE 5", the Modal should get an "E" message on the div, and just the Cancel button should appear at the botton of the Modal.
Anyway, thanks for reading everything and thanks in advance, all this is simply because I try to learn how to make the Modal Script do different things, and consider different cases, depending on what is the response that is sent from the Controller, since I understand that the complexity of the problem arises that the variables of the Script environment exist at different times than the variables of the View, and I don't know to what extent it is possible to treat the 'response' sent by the controller as a Variable, but I would like to learn how to do it if possible, and I want to understand all this.
Here is a working demo:
UK1:
public class UK1
{
public string UK2 { get; set; }
public string UK3 { get; set; }
}
UK1Controller:
//UK2 and UK3 are string,so that they can be null.When comparing them,we need to change them to int
[HttpPost]
[ValidateAntiForgeryToken]
public string GetViewContent(UK1 uk)
{
if (Convert.ToInt32(uk.UK2) == Convert.ToInt32(uk.UK3))
{
return "A-CASE 1";
}
if (Convert.ToInt32(uk.UK2) >= Convert.ToInt32(uk.UK3))
{
return "B-CASE 2";
}
if (Convert.ToInt32(uk.UK2) <= Convert.ToInt32(uk.UK3))
{
return "C-CASE 3";
}
if (uk.UK2 == null)
{
return "D-CASE 4";
}
if (uk.UK3 == null)
{
return "E-CASE 5";
}
return "";
}
public IActionResult ShowUK1()
{
return View();
}
public IActionResult Create()
{
return Ok();
}
public IActionResult CreateDos()
{
return Ok();
}
ShowUK1 View(I change OK1 button to <a> tag,and add id to Ok1 and Cancel):
<div class="container">
<div class="card level-3">
<h3>Ac</h3>
<hr />
<div class="row">
<div class="col-md-4">
<form asp-action="Create">
<div class="form-group">
<input asp-for="UK2" class="form-control" />
<span asp-validation-for="UK2" class="text-danger"></span>
</div>
<div class="form-group">
<input asp-for="UK3" class="form-control" />
<span asp-validation-for="UK3" class="text-danger"></span>
</div>
<div class="form-group">
<input type="submit" value="UK5" class="btn btn-primary" /> |
<!-- Button to Open the Modal -->
<button id="btnOpenModal" type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
CALL CONTROLLER / MODAL BUTTON
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">CONTROLLER RESPONSE:</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body" id="modalcontent">
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button id="cancel" type="button" class="btn btn-danger" data-dismiss="modal">CANCEL</button>
<a id="ok1" class="btn btn-primary" >OK1</a>
</div>
</div>
</div>
</div>
<script>
$(function () {
$("#btnOpenModal").click(function () {
var uk = {};
uk.UK2 = $("#UK2").val();
uk.UK3 = $("#UK3").val();
$.ajax({
type: "POST",
url: "GetViewContent",
data: uk,
beforeSend: function (request) {
request.setRequestHeader(
"RequestVerificationToken",
$("[name='__RequestVerificationToken']").val());
},
success: function (data) {
switch (data) {
case "A-CASE 1":
$("#ok1").attr("hidden", "hidden");
$('#modalcontent').html("A");
break;
case "B-CASE 2":
$("#ok1").removeAttr("hidden");
$("#ok1").attr("href", "Create");
$('#modalcontent').html("B");
break;
case "C-CASE 3":
$("#ok1").removeAttr("hidden");
$("#ok1").attr("href", "CreateDos");
$('#modalcontent').html("C");
break;
case "D-CASE 4":
$("#ok1").attr("hidden", "hidden");
$('#modalcontent').html("D");
break;
case "E-CASE 5":
$("#ok1").attr("hidden", "hidden");
$('#modalcontent').html("E");
break;
default:
break;
}
},
error: function (response) {
$("#myModal").modal('toggle')
}
});
});
});
</script>
result:
I'm using ajax to make a request and open a modal bootstrap window afterwards. The problem is that when I use ajax, I make a request to my controller, and the return (modal content) I load as follows:
//modal loading
$('#contentModalFinanceiroParcela').html(data);
//exibição da modal
$('#modalFinanceiroParcela').modal({
keyboard: true,
}, 'show');
So far, everything perfect. The problem is that from then on, I can't bind the form to register the submit event of the form. In the function bindFormFinanceiroParcela, no matter how much I pass the "dialog", bind does not work.
bindFormFinanceiroParcela(document.getElementById("contentModalFinanceiroParcela"));
Searching the forums, I found that the process works if I load the modal using the "load" command, as below, but I can't do it like that, otherwise it will make a second request to the controller, because previously, I already used ajax .
//That way it works, but I can't use it.
$('#contentModalFinanceiroParcela').load(url, function () {
$('#modalFinanceiroParcela').modal({
keyboard: true
}, 'show');
// Inscreve o evento submit
bindFormFinanceiroParcela(this);
stopLoadPage();
});
Is there a possibility that I can bind the form without using the "load" command mentioned in the script above?
function openModalFinanceiroParcelaSemURL(data) {
startLoadPage();
//Create the modal window block in the body of the page
if (!$("#modalFinanceiroParcela").data('bs.modal'))
CreateModalFinanceiroParcela();
//Load modal content via ajax request
$('#contentModalFinanceiroParcela').html(data);
$('#modalFinanceiroParcela').modal({
keyboard: true,
}, 'show');
bindFormFinanceiroParcela(document.getElementById("contentModalFinanceiroParcela"));
stopLoadPage();
}
function bindFormFinanceiroParcela(dialog) {
$('form', dialog).submit(function (e, i) {
if ($(this).valid() || i) {
startLoadOneMoment();
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (result) {
if (result.success) {
window.location = window.location;
} else {
$('#contentModalFinanceiroParcela').html(result);
bindFormFinanceiroParcela();
}
stopLoadOneMoment();
}
});
return false;
} else {
return false;
}
});
function CreateModalFinanceiroParcela() {
var html = '<div class="modal modal-primary modal-system" tabindex="-1" role="dialog" id="modalFinanceiroParcela" data-backdrop="static"><div class="modal-dialog modal-dialog-centered"><div class="modal-content"><div class="content-modal-system" id="contentModalFinanceiroParcela"></div></div></div></div>';
$("body").append(html);
}
RAZOR DELETE:
#using Retaguarda.Domain.Enuns
#model Retaguarda.Application.ViewModels.Financeiro.FinanceiroParcela.FinanceiroParcelaViewModel
#{
ViewData["Title"] = "Excluir Parcela";
Layout = null;
}
<div>
<form asp-action="Delete" id="frm-excluir-financeiro-parcela">
#Html.AntiForgeryToken()
<div class="modal-shadow">
<div class="modal-header modal-header-primary">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4><i class="modal-title text-center glyphicon glyphicon-trash"></i> #ViewData["Title"] </h4>
</div>
<div class="panel">
<div class="panel-body container-fluid pt-15 pl-15 pr-15">
<div class="form-horizontal">
<vc:summary />
<br />
<div class="message-delete">
#Html.HiddenFor(model => model.Id, new { id = "hid-financeiro-parcela-id" })
<i class="icon fa-trash" aria-hidden="true"></i>
<p>
Tem certeza de que deseja excluir a parcela #(Model.Parcela)?<br />
</p>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-md-offset-2 col-md-10">
<div class="float-right">
<div class="btn-group btn-group-sm mr-auto"
role="group">
<div class="btn-group btn-group-sm" role="group">
#*<button id="btn-excluir-financeiro-parcela" type="submit" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>*#
<button id="btn-excluir-financeiro-parcela" type="button" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>
<button id="btn-cancelar-financeiro-parcela" class="btn btn-danger" data-dismiss="modal"><i class="icon wb-close"></i> Cancelar </button>
</div>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
<script src="~/lib/jquery-validation/dist/jquery.validate.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
#section Scripts {
#{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
}
Ajax call
$('#dtFinanceiroParcela').on('click', 'tr .btn-excluir-financeiro-parcela', function (e) {
e.preventDefault();
startLoadOneMoment();
var id = $(this).attr('data-id');
var data = { id: id };
var dataURL = jQuery.param(data);
$.ajax({
url: "/financeiro-parcela-gerenciar/remover-financeiro-parcela/" + id,
type: "GET",
// data: dataURL,
contentType: "application/json",
async: false,
success: function (result) {
if (typeof result.success !== 'undefined') {
if (!result.success) {
stopLoadOneMoment();
swal("Oops", result.message, "error");
return false;
}
}
// alert(this.url);
stopLoadOneMoment();
openModalFinanceiroParcelaSemURL(result);
return false;
},
error: function () {
stopLoadOneMoment();
alert("Oops! Algo deu errado.");
return false;
}
});
Your form inside razor does not contain any submit button because its commented out.
#*<button id="btn-excluir-financeiro-parcela" type="submit" class="btn btn-success"><i class="icon wb-check"></i> Excluir </button>*#
Remove the comment or change the type of the other button to "submit"
I guess the submit event is attached successfully but never called due to the missing submit button inside your form.
I'm trying to add some additional data to a form in my laravel blade using js and ajax post, but I can't get the form to submit. I've stripped everything else out to try to find what's wrong, but I'm mystified. Can anyone help?
My blade looks like this;
#extends('layouts.app')
#section('content')
<div class="container">
<div class="row justify-content-center">
<div class="col-12 col-md-6 mt-5 mb-2">
<div class="card">
<div class="card-body">
<form id="payment-form">
<button id="card-button" class="btn btn-lg btn-block btn-success">
<span id="button-text"><i class="fas fa-credit-card mr-1"></i>{{ __('Add Payment Method') }}</span>
</button>
</form>
</div>
</div>
</div>
</div>
</div>
#endsection
#section('javascript')
<script>
const cardButton = document.getElementById('card-button');
var form = document.getElementById('payment-form');
cardButton.addEventListener('click', function(event) {
// event.preventDefault();
console.log('On click check');
var payment = '1234';
$.ajax({
type: "POST",
url: "/payment-post",
data: {
payment: payment,
'_token': $('meta[name="csrf-token"]').attr('content'),
},
});
});
</script>
#endsection
You have to use like this
var payment = '1234';
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
type: "POST",
url: "{{url('')}}/payment-post",
dataType: "text",
data: {
payment: payment,
_token: CSRF_TOKEN
},
success: function (response) {
//Do something
}
});
In the end I tracked this down to 'defer' being present in the script tag in the header, which was stopping all the event listeners from working. Once I changed it to this
<script src="{{ asset('js/app.js') }}"></script>
everything working fine.
I have a strongly typed view in which I am looping over some objects from a database and dispaying them in a jumbobox with two buttons in it. When I click one of the buttons I have a modal popping up. I'd like to have somewhere in this modal the name and the id of the corresponding object, but I do not really know how to do this. I am a bit confused where to use c# and where javascript. I am a novice in this, obviously.
Can someone help?
This is the code I have so far. I don't have anything in relation to my question, except the code for the modal :
#model IEnumerable<eksp.Models.WorkRole>
#{
ViewBag.Title = "DisplayListOfRolesUser";
}
<div class="alert alert-warning alert-dismissable">You have exceeded the number of roles you can be focused on. You can 'de-focus' a role on this link.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var dataJSON;
$(".alert").hide();
//make the script run cuntinuosuly
$.ajax({
type: "POST",
url: '#Url.Action("checkNumRoles", "WorkRoles")',
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
if (data == false) {
$(".alert").show();
$('.btn').addClass('disabled');
//$(".btn").prop('disabled', true);
}
}
function errorFunc() {
alert('error');
}
});
</script>
#foreach (var item in Model)
{
<div class="jumbotron">
<h1>#Html.DisplayFor(modelItem => item.RoleName)</h1>
<p class="lead">#Html.DisplayFor(modelItem => item.RoleDescription)</p>
<p> #Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { #class = "btn btn-primary btn-lg" })</p>
<p> <button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
</div>
}
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Save</button>
</div>
</div>
</div>
</div>
I think your confusing the server side rendering of Razor and the client side rendering of the Modal. The modal cannot access your Model properties as these are rendered server side before providing the page to the user. This is why in your code <h4 class="modal-title">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4> this does not work.
What you want to do is capture the event client side in the browser. Bootstrap allows you to achieve this by allowing you to hook into events of the Modal. What you want to do is hook into the "show" event and in that event capture the data you want from your page and supply that to the Modal. In the "show" event, you have access to the relatedTarget - which is the button that called the modal.
I would go one step further and make things easier by adding what data you need to the button itself as data-xxxx attributes or to DOM elements that can be easily access via JQuery. I have created a sample for you based on what you have shown to give you an idea of how it can be achieved.
Bootply Sample
And if needed... How to specify data attributes in razor
First of all
you will need to remove the data-toggle="modal" and data-target="#myModal" from the button, as we will call it manually from JS and add a class to reference this button later, your final button will be this:
<button type="button" class="btn btn-default btn-lg modal-opener">Had role in the past</button>
Then
In your jumbotron loop, we need to catch the values you want to show later on your modal, we don't want to show it, so we go with hidden inputs:
<input type="hidden" name="ID_OF_MODEL" value="#item.WorkRoleId" />
<input type="hidden" name="NAME_OF_MODEL" value="#item.RoleName" />
For each information you want to show, you create an input referencing the current loop values.
Now you finally show the modal
Your document.ready function will have this new function:
$('.modal-opener').on('click', function(){
var parent = $(this).closest('.jumbotron');
var name = parent.find('input[name="NAME_OF_MODEL"]').val();
var id = parent.find('input[name="ID_OF_MODEL"]').val();
var titleLocation = $('#myModal').find('.modal-title');
titleLocation.text(name);
// for each information you'll have to do like above...
$('#myModal').modal('show');
});
It simply grab those values we placed in hidden inputs.
Your final code
#model IEnumerable<eksp.Models.WorkRole>
#{
ViewBag.Title = "DisplayListOfRolesUser";
}
<div class="alert alert-warning alert-dismissable">You have exceeded the number of roles you can be focused on. You can 'de-focus' a role on this link.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var dataJSON;
$(".alert").hide();
//make the script run cuntinuosuly
$.ajax({
type: "POST",
url: '#Url.Action("checkNumRoles", "WorkRoles")',
dataType: "json",
success: successFunc,
error: errorFunc
});
function successFunc(data, status) {
if (data == false) {
$(".alert").show();
$('.btn').addClass('disabled');
//$(".btn").prop('disabled', true);
}
}
function errorFunc() {
alert('error');
}
$('.modal-opener').on('click', function(){
var parent = $(this).closest('.jumbotron');
var name = parent.find('input[name="NAME_OF_MODEL"]').val();
var id = parent.find('input[name="ID_OF_MODEL"]').val();
var titleLocation = $('#myModal').find('.modal-title');
titleLocation.text(name);
// for each information you'll have to do like above...
$('#myModal').modal('show');
});
});
</script>
#foreach (var item in Model)
{
<div class="jumbotron">
<input type="hidden" name="ID_OF_MODEL" value="#item.WorkRoleId" />
<input type="hidden" name="NAME_OF_MODEL" value="#item.RoleName" />
<h1>#Html.DisplayFor(modelItem => item.RoleName)</h1>
<p class="lead">#Html.DisplayFor(modelItem => item.RoleDescription)</p>
<p> #Html.ActionLink("Focus on this one!", "addWorkRoleUser", new { id = item.WorkRoleId }, new { #class = "btn btn-primary btn-lg" })</p>
<p> <button type="button" class="btn btn-default btn-lg" data-toggle="modal" data-target="#myModal">Had role in the past</button> </p>
</div>
}
<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">#Html.DisplayFor(modelItem => item.RoleName)//doesn't work</h4>
</div>
<div class="modal-body">
<p>Some text in the modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Save</button>
</div>
</div>
</div>
I am having trouble formatting the JSON data into html I have tried various methods and would just like a bit of help or pointing in the right direction. The example I've been playing with is 'apple' and here is what I'm currently getting, this is the second element of the apiResult array (pic).
In my ajax call the action I'm using is opensearch as I was advised to do that but I have seen a lot of people using query. Here is my codepen if anyone needs to take a look for themselves. Thanks for any help, I appreciate it.
Here is my html:
<div id="main">
<div id="title">
<h1>Wikipedia searcher!</h1>
<hr />
</div>
<div id="content">
<h3 id="random">Click here for a random wikipedia page</h3>
<form>
<div class="row" id="searchDiv">
<div class="col-xs-4">
<h3>Search for a wikipedia article:</h3>
</div>
<div class="col-xs-4">
<input type="text" class="form-control" id="search" name="search">
</div>
<div class="col-xs-4">
<button type="button" class="btn btn-default" id="searchBtn">Search</button>
</div>
</div>
</form>
<ul id="theData">
</ul>
</div>
</div>
</div>
Here is my JS:
$(document).ready(function() {
$("#searchBtn").click(function() {
var $theData = $("#theData");
var title;
$.ajax({
url: 'https://en.wikipedia.org/w/api.php',
data: {
action: 'opensearch',
limit: 10,
namespace: 0,
search: $("#search").val(),
format: 'json'
},
dataType: 'jsonp',
success: function processResult(apiResult) {
var html = "";
$theData.html("Displaying search results for " + apiResult[0]);
apiResult.shift();
console.log(apiResult[0].length);
$.each(apiResult, function(i, apiResult) {
for(var x = 0; x <= apiResult[0].length; x++)
{
html += "<div class='result'>";
html += apiResult[i][x] + "<br>";
html += "</div><br>";
}
});
$theData.append(html);
}
});
});
});