I have a database of movies, and I am looking to create a Json, and then access that json in my view. I have successfully created the json within the controller using the following code:
var movies = from m in db.Movies
select m;
string jsonData = JsonConvert.SerializeObject(movies);
This creates a json, which I have passed to the Console via writeline, and it generates the following JSON:
[{"ID":1,"Title":"When Harry Met Sally","ReleaseDate":"1989-01-11T00:00:00","Genre":"Romantic Comedy","Price":7.99,"Rating":"PG","Review":79.90},
{"ID":2,"Title":"Ghostbusters ","ReleaseDate":"1984-03-13T00:00:00","Genre":"Comedy","Price":8.99,"Rating":"PG","Review":94.90},
{"ID":3,"Title":"Ghostbusters 2","ReleaseDate":"1986-02-23T00:00:00","Genre":"Comedy","Price":9.99,"Rating":"15","Review":89.90},
{"ID":4,"Title":"Rio Bravo","ReleaseDate":"1959-04-15T00:00:00","Genre":"Western","Price":3.99,"Rating":"U","Review":91.90},
{"ID":5,"Title":"The Hangover","ReleaseDate":"2008-01-01T00:00:00","Genre":"Comedy","Price":9.99,"Rating":"18","Review":83.80},
{"ID":6,"Title":"Test","ReleaseDate":"2013-06-01T00:00:00","Genre":"Action","Price":10.00,"Rating":"18","Review":89.00}]
I then want to access that json in my view, and print it to my view. I have tried the following Ajax code, but I can't seem to get the json data to display.
<button id="test">Test</button>
<div class="inner"></div>
<script type="text/javascript">
$(document).ready(function () {
$('#test').on('click', function(){
$.ajax({
url: '#Url.Action("Index", "Movies")',
dataType: 'json',
context: document.body
}).done(function(serverdata) {
jsonData = serverdata;
$.each(jsonData, function(i, item) {
$(".inner").append("<p>" + jsonData + "</p>");
});
});
});
});
</script>
Any ideas? What am I doing wrong?
if we are talking about ASP.NET MVC then you can do this:
action code:
[HttpGet]
public JsonResult Index(int? PageId)
{
//other your code goes here
var movies = from m in db.Movies
select m;
return Json(new {result = movies}),JsonRequestBehavior.AllowGet);
}
client code:
$.ajax({
type: "GET",
url: '#Url.Action("Index", "Movies")',
dataType: 'json',
content: "application/json",
cache : false
}).done(function (serverdata) {
if(result.result.length > 0)
{
$.each(result.result, function(i, item) {
$(".inner").append("<p>" +"ID: "+ item.ID +", Title :" + item.Title+ "</p>");
});
}
else
{
alert("No movies in result");
}
}).fail(function (jqXHR, textStatus) {
alert("Internal server error." + "\n" + jqXHR.statusText );
});
try: -
<script type="text/javascript">
$(document).ready(function () {
$('#test').on('click', function(){
$.ajax({
url: '#Url.Action("Index", "Movies")',
method: 'GET',
dataType: 'json',
context: document.body
}).done(function(serverdata) {
var jsonData = serverdata;
$.each(jsonData, function(i, item) {
$(".inner").append("<p>" +"ID: "+ item.ID +", Title :" + item.Title+ "</p>");
});
});
});
});
</script>
Related
I'm getting data as json result from controller.
But in my ajax that data is empty. Why?
Controller:
public JsonResult GetMealType(string mType)
{
var obr = new Obroci();
var obrGrid = obr.GetMealType(mType);
return Json(obrGrid, JsonRequestBehavior.AllowGet);
}
Json variable has value.:
string:
[{"Type":"M1","Price":25,"Description":"Topli obrok"}]
ajax :
var newText = $('option:selected', this).text();
$.ajax({
url: "/Dumas/GetMealType?mtype=" + newText,
type: "POST",
data: 'json',
success: function (data) {
alert(data.success);
$("#lType").val(obj.Description);
},
error: function (status, error) {
alert("An AJAX error occured: " + status + "\nError: " + error);
}
});
You must correct your Ajax code to:
$.ajax({
url: "/Dumas/GetMealType",
type: "POST",
data: JSON.stringify({ mtype: newText }),
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.success);
$("#lType").val(obj.Description);
},
error: function (data) {
alert("An AJAX error occured: " + status + "\nError: " + error);
}
});
Please see my below code,
Controller -
public ActionResult AmountOwed()
{
int vehicleID = Convert.ToInt32(Request.Cookies["VehicleID"].Value);
var amountOwed = _PUSPERSContext.TblEOYPayments.Where(x => x.VehicleID == vehicleID).OrderByDescending(x => x.PaymentID).Take(1).Select(x => x.AmountOwed).ToList().FirstOrDefault();
return Json(amountOwed, JsonRequestBehavior.AllowGet);
}
This gives me the value I want but I now want to display it in a textbox in a partial view (_EOYPaymentsLayout.cshtml) -
<div class='form-group'>
#Html.LabelFor(m => m.TblEOYPayment.AmountOwed, new { title = "Amount Owed" })
#Html.TextBoxFor(m => m.TblEOYPayment.AmountOwed, new { title = "Amount Owed", #class = "form-control inputSizeMedium"})
</div>
I have have tried various things in my ajax code but I can never get the value into the view (this code is in the main view called Payments) -
$(document).ready(function () {
$('#addEOYPayment').click(function () {
$.ajax({
type: "GET",
url: "AmountOwed",
datatype: "Json",
success: function (data) {
$('#TblEOYPayment_AmountOwed').html(data.amountOwed);
}
});
});
});
Would be grateful for some advice. Thanks
Instead of return a json object, you can return a partial view
C#
public ActionResult AmountOwed()
{
int vehicleID =
Convert.ToInt32(Request.Cookies["VehicleID"].Value);
var amountOwed = _PUSPERSContext.TblEOYPayments.Where(x => x.VehicleID == vehicleID).OrderByDescending(x => x.PaymentID).Take(1).Select(x => x.AmountOwed).ToList().FirstOrDefault();
return PartialView("NameOfView.cshtml", amountOwed );
}
js
$(document).ready(function () {
$('#addEOYPayment').click(function () {
$.ajax({
type: "GET",
url: "AmountOwed",
datatype: "Json",
success: function (data) {
$('#TblEOYPayment_AmountOwed').html(data.responseText);
}
});
});
});
and your view may receive the type of thevariable amountOwed.
You must double check your url. Please do include the controller name. For an instance: URL: "\Home\AmountOwed\" + ID,
Thanks for the replies.
Finally got it working, it was just this:
$(document).ready(function () {
$('#addEOYPayment').click(function () {
$.ajax({
type: "GET",
url: "/Home/AmountOwed",
datatype: "Json",
success: function (data) {
$('#TblEOYPayment_AmountOwed').val(data);
}
});
});
});
I am currently trying to update a DynamoDB table with information that I add into a HTML form. Every time that I run my program and submit my information, I get this error:
POST https://quovje1gi8.execute-api.us-east-2.amazonaws.com/production/accounts 400 ()
I can run my Lambda function on AWS, and add data to my table just fine. I have checked again and again to make sure that my permissions are established correctly and they are. I just can't seem to figure this out.
My front-end:
<form>
<label for="username">Add Username:</label>
<textarea id="username"></textarea>
<button id='submitButton'>Submit</button>
</form>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js">
</script>
<script type="text/javascript">
var API_URL = 'https://quovje1gi8.execute-api.us-east-2.amazonaws.com/production/accounts';
$(document).ready(function(){
$.ajax({
type:'GET',
url: API_URL,
success: function(data){
$('#accounts').html('');
data.Items.forEach(function(accountsItem){
$('#accounts').append('<p>' + accountsItem.username + '</p>');
})
}
});
});
$('#submitButton').on('click', function(){
$.ajax({
type:'POST',
url: API_URL,
data: JSON.stringify({"username": $('#username').val()}),
contentType: "application/json",
success: function(data){
location.reload();
}
});
return false;
});
Lambda function:
'use strict';
console.log('Starting Function');
const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({region:'us-east-2'});
exports.handler = function(e, ctx, callback) {
var params = {
Item: {
user_id: ,
date: Date.now(),
username: "",
password: "",
name: "",
location: "",
field: "",
company: ""
},
TableName: 'accounts'
};
docClient.put(params, function(err, data){
if(err){
callback(err, null);
}
else{
callback(null, data);
}
});
}
OK new at this / long time away from it...
I have a json list created thus:
$.ajax({
url: 'http://www.somewebsite.com/land.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status) {
$.each(data, function(i, item) {
var balance = '<p>' + item.itemm + ' ' + item.amount + ' ' + item.status +
' ' + 'edit' + ' ' +
' delete' +
'</p><hr>';
total2 = total2 + parseInt(item.amount);
$("#mylbl").append(balance);
$("#mylbl5").html(total2);
});
},
error: function() {
output.text('There was an error loading the data.');
}
I'm using this method as I'm using phonegap...I have display items and add items working but want to add in edit and delete functionality...
I'm trying to add edit and delete links on each row (as above) but just cant get it sorted....
Only at delete stage .. and have tried this delete function..
function deleteRecord(id) // Get id of record . Function Call when Delete Button Click..
{
mysql_connect("localhost","454547_yeah","password");
mysql_select_db("454487_mydbdb");
var deleteStatement = mysql_query("DELETE FROM balance WHERE id=?");
db.transaction(function (tx) { tx.executeSql(deleteStatement, id, onError); alert("Delete Sucessfully"); });
}
Any help or pointers greatly appreciated ....I've trawlled the web and found nought that might help...
you can try this one
formDataEdit = {
itemm: $("#itemm"),
amount: $("#amount"),
status: $("#status")
};
$.ajax({
url: 'http://www.somewebsite.com/delete.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
data: formDataEdit,
success: function(data, status) {
alert("Edit successful");
},
error: function() {
output.text('There was an error loading the data.');
}
});
formDataDelete = {
id: $("#id")
};
$.ajax({
url: 'http://www.somewebsite.com/delete.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
data: formDataDelete,
success: function(data, status) {
alert("Delete successful");
},
error: function() {
output.text('There was an error loading the data.');
}
});
html
<b><a onclick="edit(1);">Edit</a> | <a onclick="delete(1);">Delete</a></b>
js
currentPage = {};
currentPage.edit = function(id){ //also can use for delete
alert(id);
};
public function getCrew(){
$search = $this->input->post('name');
if($this->input->post('ajax') && (!empty($search))){
$result = $this->model->getNames($search);
foreach($result as $r){
echo json_encode($r);
}
}
}
$(document).ready(function(){
$('#getMem').keyup(function(e){
var name = {
ajax: 1,
name: $('#getMem').val()
}
$.ajax({
url: 'work/getCrew',
type: 'POST',
data: name,
dataType: 'json',
success: function(data){
$('#freshMem').html(data.first_name);
},
error: function(){
alert('Error.');
}
});
});
});
This works fine if the result from database returns only one row, if more than one generates error, can anyone please tell me how to solve this
Use the Output class to tell the browser that JSON is being returned. The problem is that you are json_encodeing multiple objects in your foreach loop. Just json_encode the array returned from your model
public function getCrew(){
$search = $this->input->post('name');
if($this->input->post('ajax') && (!empty($search))){
$result = $this->model->getNames($search);
$this->output
->set_content_type('application/json')
->set_output(json_encode(array("response" => $result)));
}
}
$(document).ready(function(){
$('#getMem').keyup(function(e){
var name = {
ajax: 1,
name: $('#getMem').val()
}
$.ajax({
url: 'work/getCrew',
type: 'POST',
data: name,
dataType: 'json',
success: function(data)
{
var __html = '';
$.each(data.response, function (a, b)
{
__html += '<p>'+b.first_name+'</p>';
});
$('#freshMem').html(__html);
},
error: function()
{
alert('Error.');
}
});
});
});
Try this:
$.ajax({
url: 'work/getCrew',
type: 'POST',
data: name,
dataType: 'json',
success: function(data){
json_data = $.parseJSON(data);
$.each(json_data, function(i,item){
$('#freshMem').append(item.first_name);
});
},
error: function(){
alert('Error.');
}
});
You have to iterate over returned array.
Also you need to change your controller code:
public function getCrew(){
$search = $this->input->post('name');
if($this->input->post('ajax') && (!empty($search))){
$result = $this->model->getNames($search);
// assuming that $result is array...
$json = json_encode($result);
echo $json;
/*foreach($result as $r){
echo json_encode($r);
}*/
}
}