How to update a specific div with ajax and jquery - html

I'm working on site and it has a fram. think of the gmail frame. And much like the gmail app I want only the inner div to be updated when clicking links on the navbar. I've got it so the div changes, but it certainly does not give me the results I'm hoping for. this is a rough outline of what I have
<div id=container>
<div id=page>
... some child divs in here
</div></div>
Because the container has a fixed scroll bar I don't want it to change I want to only replace the page div. this is what I managed to come up with on the jquery side. I'm just a beginner so I don't really know what I'm doing but I'm trying to learn.
$(document).ready(function () {
$.ajaxSetup ({
cache: false
});
var ajax_load = "<img src='bin/pics/loading.gif' alt='loading…' width='32px' height='32px' style='top: 250px; left: 250px;' />";
var loadUrl = "bin/ajax/load.html";
$("#mybuton").click(function(){
$("#page").load(loadUrl);
location.hash = 'ajax';
});
});
the load html contains this
<link rel="stylesheet" type="text/css" href="bin/main.css" />
<div id="page">
<div id="child">
<h1> sometitle </h1>
</div>
</div>
Any suggestions?

Here's the Jquery ajax link http://api.jquery.com/jQuery.ajax/
Eg Code :
ajax_control = jQuery.ajax({
url: "target.php",
type: "POST",
data: {variable_name: variable_value}
});
ajax_control.always(function(){
$('#content').html(ajax_control.responseText);
});
By assigning the call to a variable ("ajax_control" in the above example), you can abort whenever you want, by using :
ajax_control.abort();
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.get/

I don't like to answer with links, nor just text, so here is an example of how can you make a div/table or mostly any html container to change it's content.
If you're using MVC with Razor it'd look like this
TestView.cshtml
#using (Ajax.BeginForm("Test",
"TestController",
new AjaxOptions {
HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "searchResults" }))
{
Search User by ID: <input type="text" name="id" />
<input type="submit" value="Search" />
}
<table id="searchResults">
</table>
TestController.cs
public class TestController : Controller
{
public PartialViewResult Test(int id)
{
var model = myDbContext.Users.Single(q => q.UserID == id);
return PartialView("_PartialViewTest", model);
}
}
_PartialViewTest.cshtml
#model IEnumerable<MyApp.Models.User>
<table id="searchResults">
<tr>
<th>Name</th>
<th>Email</th>
</tr>
#foreach(var item in Model) {
<tr>
<td>#item.Name</td>
<td>#item.Email</td>
</tr>
}
</table>
...and if you want to do it using classic ASP.NET, it'd be like this:
TestPage.aspx
<body>
<form id="form1" runat="server">
<div>
<button type="button" onclick='testCall()'>Test!</button>
<hr />
<div id="ajaxResult">
</div>
</div>
</form>
</body>
Scripts.js / TestPage.aspx
function testCall() {
$.ajax({
url: "TestHandler.ashx",
dataType: 'json',
success: callbackTestCall
});
};
function callbackTestCall(payload) {
document.getElementById("ajaxResult").innerHTML = payload;
};
TestHandler.ashx
public class TestHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
Random random = new Random();
string actualData = random.Next(2001).ToString();
context.Response.ContentType = "text/plain";
context.Response.CacheControl = "no-cache";
context.Response.Write(jss.Serialize(actualData));
}
public bool IsReusable
{
// Whether or not the instance can be used for another request
get { return true; }
}
}
If you need further information please, let me know.

Related

AngularJS, how to display contents of a received JSON object

I have successfully received the JSON object from an API, which is evident from a console.log code. Now, I want to display the various elements in that JSON file. For example, the JSON contains elements like "name" and "url". How do I display these individually, in an h1 HTML element, after clicking the submit button and fetching the JSON file. I'm a newbie and sorry if this is an obvious question, I'm kinda stuck and need help. Thank you in advance!
My HTML Code is:
<body ng-app="myApp">
<div ng-controller="UserCtrl">
Search : <input type="text" placeholder="Search Employees"
ng-model="formData.searchText"/> <br/><br/>
<button ng-click="getByID()">Submit</button>
{{response.data.name}}
</body>
The JS is:
var myApp = angular.module('myApp', []);
myApp.controller('UserCtrl', function($scope, $http) {
var id = "my secret key comes here";
$scope.formData = {};
$scope.searchText;
$scope.getByID = function() {
$http.get("https://rest.bandsintown.com/artists/" + $scope.formData.searchText + "?app_id="+id)
.then(response => {
console.log(response.data.name)
})
}
});
Thank you so much in advance!
You need to use a variable to assign it with the response data and then use it in html. For example to display name from response.data.name:
<body ng-app="myApp">
<div ng-controller="UserCtrl as vm">
Search : <input type="text" placeholder="Search Employees"
ng-model="vm.searchText"/> <br/><br/>
<button ng-click="vm.getByID()">Submit</button>
<h1>{{ vm.name }}</h1>
</body>
In controller:
var myApp = angular.module('myApp', []);
myApp.controller('UserCtrl', function($http) {
let vm = this;
var id = "my secret key comes here";
vm.searchText;
vm.name;
vm.getByID = function() {
$http.get("https://rest.bandsintown.com/artists/" + vm.searchText + "?app_id="+id)
.then(response => {
console.log(response.data.name);
vm.name = response.data.name;
})
}
});
Put the data on $scope:
$scope.getByID = function() {
var url = "https://rest.bandsintown.com/artists/" + $scope.formData.searchText;
var params = { app_id: id };
var config = { params: params };
$http.get(url, config)
.then(response => {
console.log(response.data.name)
$scope.data = response.data;
})
}
Then use the ng-repeat directive:
<body ng-app="myApp">
<div ng-controller="UserCtrl">
Search : <input type="text" placeholder="Search Employees"
ng-model="formData.searchText"/> <br/><br/>
<button ng-click="getByID()">Submit</button>
{{data.name}}<br>
<div ng-repeat="(key, value) in data">
{{key}}: {{value}}
</div>
</div>
</body>
For more information, see
AngularJS ng-repeat Directive API Reference

Trigger preview mode by passing data from one controller to another

I want to trigger a preview mode from one controller onto another using angular service but can't get the final step done. I am trying to get the url from the passed parameter into that ng-src in SideMenuCtrl. Not sure how to do it so that it would happen dynamically.
I have seen a few similar threads but not with a final end result like mine because I am trying to eventually display an image on the screen.
How would I link the passed parameter advert to vm.previewImage/.
var app = angular.module('app', [])
.service('appState', function() {
this.data = {
preview: {
enabled: false,
advert: ''
}
};
this.previewAdvert = function(advert) {
//flick the inPreview variable
this.data.preview = {
enabled: !this.data.preview.enabled,
advert: advert
}
}
})
.controller('SideMenuCtrl', function(appState) {
var vm = this;
vm.preview = appState.data.preview;
})
.controller('ContentCtrl', function(appState) {
var vm = this;
vm.advertUrl = 'http://1.bp.blogspot.com/-vXmHgrrk4ic/UpTbgBkp8eI/AAAAAAAAFjQ/ajBQ9WvwNUc/s1600/gloomy-stripes-dark-background-tile.jpg';
vm.previewAdvert = function() {
console.log('preview/stop preview');
appState.previewAdvert(vm.advertUrl);
}
});
<html ng-app="app">
<body>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<div ng-controller="SideMenuCtrl as vm">
<div class="ads" ng-if="vm.preview.enabled">
<img ng-src="{{vm.previewImage}}">
</div>
</div>
<div ng-controller="ContentCtrl as vm">
<label for="adInput">Advert URL</label>
<input type="url" id="adInput" ng-model="vm.advertUrl"></input>
<button ng-mouseenter="vm.previewAdvert()" ng-mouseleave="vm.previewAdvert()">Preview</button>
</div>
</body>
</html>
Your service is shared all right between your controllers. However I noticed that with AngularJs properties from the controller are not always updated when their value change.
When this happens, you can use a function that returns your value and use the function call instead your value in your views. This way, updates are detected.
(NOTE: I moved the "SideMenuCtrl" div under because with the image appearing, the button was not hovered anymore, causing "mouseleave" to be called and that produced a flickering)
var app = angular.module('app', [])
.service('appState', function() {
this.data = {
preview: {
enabled: false,
advert: ''
}
};
this.previewAdvert = function(advert) {
//flick the inPreview variable
this.data.preview = {
enabled: !this.data.preview.enabled,
advert: advert
}
}
})
.controller('SideMenuCtrl', function(appState) {
var vm = this;
vm.getPreviewImage = function(){
return appState.data.preview.advert;
};
vm.isPreviewEnabled = function(){
return appState.data.preview.enabled;
};
})
.controller('ContentCtrl', function(appState) {
var vm = this;
vm.advertUrl = 'http://1.bp.blogspot.com/-vXmHgrrk4ic/UpTbgBkp8eI/AAAAAAAAFjQ/ajBQ9WvwNUc/s1600/gloomy-stripes-dark-background-tile.jpg';
vm.previewAdvert = function() {
console.log('preview/stop preview');
appState.previewAdvert(vm.advertUrl);
}
});
<html ng-app="app">
<body>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.js"></script>
<div ng-controller="ContentCtrl as vm">
<label for="adInput">Advert URL</label>
<input type="url" id="adInput" ng-model="vm.advertUrl"></input>
<button ng-mouseenter="vm.previewAdvert()" ng-mouseleave="vm.previewAdvert()">Preview</button>
</div>
<div ng-controller="SideMenuCtrl as vm">
<div class="ads" ng-if="vm.isPreviewEnabled()">
<img ng-src="{{vm.getPreviewImage()}}">
</div>
</div>
</body>
</html>

pass a list of objects via ajax to a MVC controller always sends null

I am probably missing something very simple. I have been working on this for a day and an half now and can not get it to work. I am looping through a table and creating a list of objects to send back to my controller. For some reason I am always receiving a null value in my controller. Here is the java script.
var items = [];
$('#grid tr').each(function () {
var item = {};
item.numReceived = $(this).find("input[id*='NumReceived']").val();
/*skip the header row*/
if (item.numReceived !== null) {
item.transactionID = $(this).find("input[id*='item_TransactionID']").val();
items.push(item);
}
});
$.ajax({
url: './ReceivePOLines',
type: "Post",
cache: false,
data: JSON.stringify(items),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function () {
window.location.replace("../Home/Index");
},
error: function (request) {
alert("error");
}
});
here is the method signature in the controller
[HttpPost]
public void ReceivePOLines(List<RecievedTransactions> inTransactions)
And here is the class ReceivedTransactions
public class RecievedTransactions{
public int numReceived { get; set; }
public int transactionID { get; set; }
}
Here are the results from Fiddler showing what was passed
[{},{"numReceived":"10000","transactionID":"10661768"},{"numReceived":"10000","transactionID":"10661769"},{"numReceived":"2000","transactionID":"10661770"},{"numReceived":"2500","transactionID":"10661771"},{"numReceived":"2500","transactionID":"10661772"},{"numReceived":"2000","transactionID":"10661773"},{"numReceived":"10000","transactionID":"10661774"}]
Any and all help appreciated.
cheers
bob
This is a new answer. Originally, I was getting null, like you. But, now it works the way you want (array of complex objects). Please get this to work for you. If you can't get it to work, although it should, I can create an ASP.NET Fiddle.
public class RecievedTransactions
{
public int numReceived { get; set; }
public int transactionID { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public void ReceivePOLines(List<RecievedTransactions> inTransactions) // MyArray MyArray
{
return;
}
//you use your own action name
public ActionResult Tut133()
{
return View();
}
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Tut132</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(function () {
var items = [];
$('#grid tr').each(function () {
var item = {};
item.numReceived = $(this).find("input[id*='NumReceived']").val();
/*skip the header row*/
if (item.numReceived !== null) {
item.transactionID = $(this).find("input[id*='item_TransactionID']").val();
items.push(item);
}
});
$.ajax({
//!!changing your url
//url: './ReceivePOLines',
url: "/Home/ReceivePOLines",
type: "Post",
cache: false,
//data: JSON.stringify({ MyArray: items }),
data: JSON.stringify(items),
//expecting back from server-need to remove since we are not getting back data from server
//dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function () {
//alerting success instead of opening window
alert("success");
//window.location.replace("../Home/Index");
},
error: function (request) {
alert("error");
}
});
})
</script>
</head>
<body>
<table id="grid">
<tr>
<td><input type="text" id="NumReceived1" value="10000" /></td>
<td><input type="text" id="item_TransactionID1" value="10661768" /></td>
</tr>
<tr>
<td><input type="text" id="NumReceived2" value="10000" /></td>
<td><input type="text" id="item_TransactionID2" value="10661769" /></td>
</tr>
</table>
<input type="button" id="theButton" value="Go" />
</body>
</html>

Get html of view from controller - .NET MVC

I want to make previews of one view on a homepage type view. To do so, I'd like to call a ListPreviews Action. I want this action to get the html body of a given view and then take the first hundred characters or so.
How can I access the actual html of a view from a controller?
This should be simple.
In your RouteConfig.cs set the defaults, mine looks like this:
defaults: new { controller = "Home", action = "Index2006", id = UrlParameter.Optional }
For your Controller/Model:
public class AView
{
public string theHtml { get; set; }
}
public class HomeController : Controller
{
[HttpPost]
public ActionResult Index2005(AView AView)
{
//put breakpoint here to see all the <html> here in view
var result = HttpUtility.UrlDecode(AView.theHtml, System.Text.Encoding.Default);
return Json(new
{
Greeting = "Returning data not used"
}
, #"application/json");
}
For your view:
<!DOCTYPE html>
<html id="PassMe">
<head>
<meta name="viewport" content="width=device-width" />
<title>Index2005</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$(".btn").click(function () {
var AView = { theHtml: escape($("#PassMe").html()) }; //JSON.stringify($("#PassMe").html())
$.ajax({
url: '/Home/Index2005',
type: 'POST',
data: AView,
success: function (result) {
$("#detail").append(result.Greeting);
},
error: function (result) {
alert('Error');
}
});
});
});
</script>
</head>
<body>
<button style="margin-bottom: 20px;" class="btn btn-default">Click to pass HTML</button>
</body>
</html>

MVC 5 - JSON post to controller always is null on controller side

I've looked for a couple hours now, hoping not to duplicate a question, and I just can't find what I'm looking for.
I am working on passing a complex object back from a form to a controller, and having it parse everything out. The problem I get is the controller shows a null input, despite the header post from Chrome showing the data going out. Can anyone give me a hand? I've included code below.
Model
public class QuizTakenObject
{
[NotMapped]
public QuizTakenComplete quizTakenComplete { get; set; }
[NotMapped]
public List<QuizSubmittedAnswers> submittedAnswers { get; set; }
[NotMapped]
public TopicList Topic { get; set; }
[NotMapped]
public QuizHeader QuizHeader { get; set; }
}
View/Script
#model App.Models.QuizTakenObject
#{
ViewBag.Title = "Take Quiz";
}
#section pageScripts{
<script type="text/javascript">
$(document).ready(function () {
//Highlight background of selected background for increased visibility
$("input[name^=QuizSubmittedAnswer]").change(function () {
$(this).parent().addClass("bg-primary");
$(this).parent().siblings().removeClass("bg-primary");
});
//Show save prompt on page after one answer is picked
var i = 0;
if (i == 0) {
$("input[name^=QuizSubmittedAnswer]").change(function () {
$("#quizSave").fadeIn('fast');
$("#quizSave").animate({ height: '125px' }, 'fast')
.animate({ width: '250px' }, 'fast', function () {
$("#quizSaveText").fadeIn('500');
});
});
}
//Prevent submitting before all answers have been selected
//Count all questions, one per form group
var questionsCount = $("form-group").length;
//Listen for answers to be selected
$("input[name^=QuizSubmittedAnswer]").change(function () {
//Check to see if all answers are selected
if ($("input[name^=QuizSubmittedAnswer]:checked").length >= questionsCount) {
$("#saveAndSubmitQuizButton").removeClass("disabled");
}
});
//Save and submit quiz
$("#saveAndSubmitQuizButton").click(function () {
event.preventDefault;
var complete = true;
saveQuizAttempt(complete);
});
//Save but not submit quiz
$("#saveQuizOnlyButton").click(function () {
event.preventDefault;
var complete = false;
saveQuizAttempt(complete);
});
//Create or update quiz attempt in DB
//saveQuizAttempt complete indicates if the record is to be marked as final
function saveQuizAttempt(complete) {
var array = $("#takeQuizForm").serializeArray();
//build JSON array
var json = {};
$.each(array, function () {
json[this.name] = this.value || '';
})
//array.push({ "IsComplete": complete });
//AJAX to post data
$.ajax({
type: "POST",
url: "SubmitQuiz",
data: JSON.stringify(array),
dataType: "json",
contentType:"application/json; charset=UTF-8",
success: function (data) {
console.log("Success!");
},
error: function () {
console.log("Error");
}
});
}
});
</script>
}
<style>
#quizSave {
display: none;
position: fixed;
z-index: 999;
height: 0;
width: 0;
bottom: 100px;
right: 0;
background-color: khaki;
border: 1px solid black;
border-radius: 2px 2px 2px 2px;
padding: .5em 1em .5em 1em;
}
</style>
<h2>#ViewBag.TopicName Quiz</h2>
<div class="row">
<div class="container col-xs-9 col-sm-9 col-md-9 col-lg-9">
<div class="well well-sm">
<strong>Directions:</strong> #Model.QuizHeader.QuizSummary
</div>
#using (Html.BeginForm("SubmitQuiz", "Quiz", FormMethod.Post, new { id = "takeQuizForm" }))
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true, "", new { #class = "text-danger" })
#Html.HiddenFor(model => model.QuizHeader.QuizID)
#Html.HiddenFor(model => model.QuizHeader.TopicID);
<input type="hidden" name="QuizTakenComplete.UserID" id="QuizTakenComplete.UserID" value="#(ViewBag.UserID)" />
<input type="hidden" name="QuizTakenComplete.IsComplete" id="QuizTakenComplete.IsComplete" value="false" />
<!--Questions/Answers-->
for (int i = 0; i < #Model.QuizHeader.QuizQuestions.Count(); i++)
{
<div class="quizQuestionBlock#(i)">
<hr />
<h4>#Model.QuizHeader.QuizQuestions.ElementAt(i).Question</h4>
<form-group>
<input type="hidden" name="QuizSubmittedAnswers[#(i)].QuestionID" id="QuizSubmittedAnswers[#(i)].QuestionID" value="#(Model.QuizHeader.QuizQuestions.ElementAt(i).QuestionID)">
#{for (int j = 0; j < Model.QuizHeader.QuizQuestions.ElementAt(i).QuizAnswers.Count(); j++)
{
<!--answers via radio buttons-->
<div id="answer#(j)#(i)" class="quizAnswer#(j)">
<input type="radio" class="individualQuizAnswer" name="QuizSubmittedAnswers[#(i)].AnswerID" value="#Model.QuizHeader.QuizQuestions.ElementAt(i).QuizAnswers.ElementAt(j).AnswerID"> #Model.QuizHeader.QuizQuestions.ElementAt(i).QuizAnswers.ElementAt(j).Answer
</div>
}
}
</form-group>
</div>
}
<hr />
<button class="btn btn-success btn-block disabled" id="saveAndSubmitQuizButton" type="button">submit quiz</button>
<div style="text-align:center;">
<small> Submitting quiz will finalize this attempt and update your score records.</small>
</div>
<br />
<br />
}
</div>
<!--Sidebar-->
<div class="container col-xs-3 col-sm-3 col-md-3 col-lg-3">
<div class="panel panel-default">
<div class="panel-heading collapsable">
<h5><span class="glyphicon glyphicon-cog"></span> Actions</h5>
</div>
<div class="panel-body">
<span class="glyphicon glyphicon-backward"></span> #Html.ActionLink("return to library", "Index", new { controller = "Library" })<br />
#Html.ActionLink("cancel/go home", "Index", new { controller = "Home" }, new { #style = "color:red;" })
</div>
</div>
</div>
<!--Quiz Save/Quit-->
<div id="quizSave">
<div id="quizSaveText" style="display:none;">
Save current answers and return to App training/quiz library?<br />
<button type="button" id="saveQuizOnlyButton" class="btn btn-success">yes</button>
<button type="button" data-toggle="tooltip" class="btn btn-danger" title="this will cancel all previous work without saving and return to the main menu">no</button>
<br />
<small>You will be able to return later to resume your work.</small>
</div>
</div>
</div>
Controller
//POST: Quiz/SubmitQuiz
[HttpPost]
public async Task<ActionResult> SubmitQuiz(string quizObject)
{
//Send false value for complete in AJAX call, just parse based on this
//Two starting JS scripts, which flow into a unified function
var input = new JavaScriptSerializer().Deserialize<QuizTakenObject>(quizObject);
var quizTakenComplete = new QuizTakenComplete
{
UserID = input.quizTakenComplete.UserID,
IsComplete = input.quizTakenComplete.IsComplete,
LastUpdate = DateTime.Now
};
//Parse if complete for purposes of updating records.
if (quizTakenComplete.UserID != null || quizTakenComplete.UserID != "")
{
db.QuizTakenComplete.Add(quizTakenComplete);
await db.SaveChangesAsync();
var quizAttemptID = quizTakenComplete.QuizAttemptID;
//Now Add Each Answer
var quizTaken = new QuizSubmittedAnswers();
quizTaken.QuizAttemptID = quizAttemptID;
quizTaken.TopicID = input.Topic.TopicID;
quizTaken.QuizID = input.QuizHeader.QuizID;
return Content("Saved");
}
else
{
return Content("Not Saved");
}
}
I think that the problem is in Ajax Call you didn't specify the attribute name
try with this
$.ajax({
type: "POST",
url: "SubmitQuiz",
data: {quizObject : JSON.stringify(array)},
dataType: "json",
contentType:"application/json; charset=UTF-8",
success: function (data) {
console.log("Success!");
},
error: function () {
console.log("Error");
}
});