Hello I'm new to MVC and AJAX.
I have a problem sending input data from view to controller.
What is the wrong thing in this code ? :
Thanks in advance.
Head :
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
View :
<div id="inputdiv">
<p>Display name: <input type="text" id="name1" /> </p>
<p><button id="submitbutton">Submit</button></p>
</div>
<script type="text/javascript" language="javascript">
$(function () {
$("#submitbutton").click(function () {
var nameEntered = $("#name1").val()
$.post(
'<%= Url.Action("SimplePost") %>',
{ submittedName: nameEntered },
handleSuccess
);
});
});
function handleSuccess(content) {
$("#inputdiv").html(content);
$("#inputdiv").addClass("easy-notification");
}
</script>
Controller :
[HttpPost]
public ContentResult SimplePost(string submittedName)
{
string result = string.Format("Hello {0}!?", submittedName);
return new ContentResult { Content = result };
}
Related
I am new to Knockout JS and think it is great. The documentation is great but I cannot seem to use it to solve my current problem.
The Summary of my Code
I have two viewmodels represented by two js scripts. They are unified in a parent js file. The save button's event is outside
both foreach binders. I can save all data in the details foreach.
My Problem
I need to be able to include the value from the contacts foreach binder with the values from the details foreach binder.
What I have tried
I have tried accessig the data from both viewmodels from the parent viewmodel and sending the POST request to the controller from there but the observeableArrays show undefined.
Create.CSHTML (Using MVC5 no razor)
<div id="container1" data-bind="foreach: contacts">
<input type="text" data-bind="value: contactname" />
</div>
<div data-bind="foreach: details" class="card-body">
<input type="text" data-bind="value: itemValue" />
</div>
The save is outside of both foreach binders
<div class="card-footer">
<button type="button" data-bind="click: $root.save" class="btn
btn-success">Send Notification</button>
</div>
<script src="~/Scripts/ViewScripts/ParentVM.js" type="text/javascript"></script>
<script src="~/Scripts/ViewScripts/ViewModel1.js" type="text/javascript"></script>
<script src="~/Scripts/ViewScripts/ViewModel2.js" type="text/javascript"></script>
ViewModel1
var ViewModel1 = function (contacts) {
var self = this;
self.contacts = ko.observableArray(ko.utils.arrayMap(contacts, function (contact) {
return {
contactName: contact.contactName
};
}));
}
ViewModel2
var ViewModel2 = function (details) {
var self = this;
self.details = ko.observableArray(ko.utils.arrayMap(details, function (detail) {
return {
itemNumber: detail.itemValue
};
}));
}
self.save = function () {
$.ajax({
url: baseURI,
type: "POST",
data: ko.toJSON(self.details),
dataType: "json",
contentType: "application/json",
success: function (data) {
console.log(data);
window.location.href = "/Home/Create/";
},
error: function (error) {
console.log(error);
window.location.href = "/Homel/Create/";
}
});
};
ParentViewModel
var VM1;
var VM2;
var initialContactInfo = [
{
contactPhone: ""
}
]
var initialForm = [
{
itemValue: ""
]
}
$(document).ready(function () {
if ($.isEmptyObject(VM1)) {
ArnMasterData = new ViewModel1(initialContactInfo);
ko.applyBindings(VM1, document.getElementById("container1"));
}
if ($.isEmptyObject(VM2)) {
VM2 = new ViewModel2(initialForm);
ko.applyBindings(VM2, document.getElementById("container2"));
}
});
I want to make a autocomplete function on my input with existing titles from database, but seems that doesn't work. I don't know what's the problem but when I try to write something, notting happens.
Here is my controller
public function search()
{
return view('search-me');
}
public function autocomplete(Request $request)
{
$data = Models::select("email")->where("email", "LIKE","%{$request->input("query")}%")->get();
return response()->json($data);
}
Here is my route
Route::get('search-me', array('as' => 'search', 'uses' => 'AdminNewsController#search'));
Route::get('autocomplete',array('as' => 'autocomplete', 'uses' => 'AdminNewsController#autocomplete'));
Here is my view
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.js"></script>
</head>
<body>
<div class="container">
<h1> test</h1>
<input type="text" class="typeahead form-control">
</div>
</body>
<script type="text/javascript">
var path = "{{ route('autocomplete') }}";
$('input.typeahead').typeahead({
source: function (query, process){
return $.get(path, { query: query}, function (data) {
return process(data);
});
}
});
</script>
</html>
I'm using Laravel 5.2 but I guess is working on mine too. Here is the tutorial : https://www.youtube.com/watch?v=3AiMsvobceY
I'm creating a blog on laravel and so far I have the successful js code for posts that contain a title and content. But I'm having some trouble writing the js function for tags.
I would like to do the same for tags but I'm getting errors on everything I try.
<script src="https://cloud.tinymce.com/stable/tinymce.min.js?apiKey=fg5tc8gb4rtw6p9n3njd2hi4965rketxda84pbcfs09hb5x2"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.6.4/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({
selector: '.myeditablediv',
plugins: 'code , save, autoresize , textcolor colorpicker , emoticons, textpattern , wordcount',
toolbar: 'save , restoredraft , forecolor backcolor, emoticons',
save_onsavecallback: function () {
var content = tinymce.activeEditor.getContent();
console.log(content);
}
});
$(document).on('click', '#SubmitBtn', function () {
var content = tinymce.activeEditor.getContent();
var data = {
'title': $('#title').val(),
'content': content,
'_token': '{{csrf_token()}}'
};
$.post('/postData', data, function () {
console.log(data);
});
});
</script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Create the title</h1>
<form>
{{csrf_field()}}
<label for="title">Click here to edit the title of your post!</label>
<input type="text" name="title" id="title"/>
<h1>Create the content</h1>
<div class="myeditablediv">Click here to edit the content of your post!</div>
</form>
<input type="button" name="Submit" id="SubmitBtn" value="Submit"/>
</body>
</html>
<script src="https://cloud.tinymce.com/stable/tinymce.min.js?apiKey=fg5tc8gb4rtw6p9n3njd2hi4965rketxda84pbcfs09hb5x2"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.6.4/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({
selector: '.myeditabletag', // change this value according to your HTML
menu: {
view: {title: 'Edit', items: 'cut, copy, paste'}
},
save_onsavecallback: function () {
var content = tinymce.activeEditor.getContent();
console.log(content);
}
});
$(document).on('click', '#SubmitBtn', function () {
var name = tinymce.activeEditor.getContent();
var data = {
'name': name,
'_token': '{{csrf_token()}}'
};
$.post('/postTags', data, function () {
console.log(data);
});
});
</script>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Create a new Tag</h1>
<form>
{{csrf_field()}}
{{--<input type="text" name="name" id="name"/>--}}
<div class="myeditabletag">Click here to edit the name of your tag!</div>
</form>
<input type="button" name="Submit" id="SubmitBtn" value="Submit"/>
</body>
</html>
Here is the route for /postData for tags and posts:
Route::post('/postTags', ['uses' => 'TagController#store']);
Route::post('/postData', ['uses' => 'PostController#store']);
And here is the PostController and TagController store method:
public function store(Request $request)
{
$post = new Post;
$post->title = $request['title'];
$post->content = $request['content'];
$post->save();
}
public function store(Request $request)
{
$tag = new Tag;
$tag->name = $request['name'];
$tag->save();
}
You have a mistake in your JS code. You are selecting an ID that doesn't exist. You need to select the content of the changed tag, and send that as the data['name']. Try the following code:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/tinymce/4.6.4/tinymce.min.js"></script>
<script type="text/javascript">
tinymce.init({
selector: '.myeditabletag', // change this value according to your HTML
menu: {
view: {title: 'Edit', items: 'cut, copy, paste'}
},
save_onsavecallback: function () {
var content = tinymce.activeEditor.getContent();
console.log(content);
}
});
$(document).on('click', '#SubmitBtn', function () {
var name = tinymce.activeEditor.getContent();
var data = {
'name': name,
'_token': '{{csrf_token()}}'
};
console.log(data);
$.post('/postTags', data, function () {
});
});
</script>
I have a project which contains all plain html pages with angularJS and one .aspx page. I need some data in list/json format in my aspx page's code behind from angular controller. Can this be done ? If yes, please guide.
I'm new to angular, please be kind.
Scenario is I want to download the current html page as pdf. I found jspdf but for some reason it is not working in IE, works in chrome.
So, I am putting a workaround where I can do this with aspx page, I just need data there.
//Download PDF
$scope.PDFDownload = function () {
window.open('ReportPage.aspx');
//need to send list/json data to aspx code behind here.
}
I need some data in list/json format in my aspx page's code behind
from angular controller.
If you want to send/receive data to/from ASPX Web Form, you want to use WebMethod.
using System.Web.Script.Serialization;
namespace DemoWebForm
{
public partial class Default : System.Web.UI.Page
{
[System.Web.Services.WebMethod]
public static string PostJson(string firstName, string lastName)
{
return new JavaScriptSerializer().Serialize(
"Hello, " + lastName + ", " + firstName + "!");
}
}
}
Usage
<%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoWebForm.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body ng-app="demoApp">
<form id="form1" runat="server" ng-controller="DemoController">
<pre>{{user}}</pre>
<button type="button" onclick="ajaxPostData();">Post Data Ajax</button>
<button type="button" ng-click="ngPostData()">Post Data Angular</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js"></script>
<script type="text/javascript">
function ajaxPostData() {
var user = { firstName: "John", lastName: "Doe" };
$.ajax({
type: "POST",
url: '<%= ResolveUrl("~/default.aspx/postjson") %>',
data: JSON.stringify(user),
contentType: "application/json",
success: function (msg) {
console.log(msg.d);
}
});
}
var demoApp = angular.module('demoApp', [])
.controller('DemoController', function DemoController($scope, $http) {
$scope.user = { "firstName": "John", "lastName": "Doe" };
$scope.ngPostData = function () {
$http.post('<%= ResolveUrl("~/default.aspx/postjson") %>', $scope.user)
.then(function (result) {
console.log(result.data.d);
});
}
});
</script>
</form>
</body>
</html>
Screen shot
personManagerInstance.getString("firstname",'common','en') currently i pass direct string in ui its affecting but what i exactly need is read the data from json file and return as string..
personManagerInstance.getString("firstname",'common','en') method i need to read the data from json file and return as string or object?
personManagerInstance.getString("lastname",'registration','en') this method based on parameter read json from different location and return as string...
var PersonManager = function ()
{
return {
$get: function ($http, person)
{
var mainInfo = $http({
method: "get",
//"js/resources-locale_en_es.json"
url: "js/resources-locale_en_es.json"
}).success(function (data) {
return data.title;
});
return {
getPersonFirstName: function ()
{
return "as";
},
getPersonLastName: function ()
{
return person.lastName;
},
getString: function (labelid, moduleName, language)
{
//Here am getting the value id, moduleName, language based on the vaule I need to change the url path
//(i.e) js/resources-locale_en_es.json, js/registration/resources-locale_en_es.json
var l = mainInfo.success(function (data) {
person.firstName = data.title;
})
return person.firstName;
}
};
}
};
};
angular.module("mainModule", [])
.value("person", {
firstName: "",
lastName: ""
})
.provider("personManager", PersonManager)
.controller("mainController", function ($scope, person, personManager)
{
person.firstName = "John";
person.lastName = "Doe";
$scope.personInstance = person;
$scope.personManagerInstance = personManager;
});
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="script.js"></script>
</head>
<body ng-app="mainModule">
<div ng-controller="mainController">
<strong>First name:</strong> {{personManagerInstance.getPersonFirstName()}}<br />
<strong>Last name:</strong> {{personManagerInstance.getPersonLastName()}}<br />
<strong>Full name:</strong> {{personManagerInstance.getString("firstname",'common','en')}} {{personManagerInstance.getString("lastname",'registration','en')}}<br />
<br />
<label>Set the first name: <input type="text" ng-model="personInstance.firstName"/></label><br />
<label>Set the last name: <input type="text" ng-model="personInstance.lastName"/></label>
</div>
</body>
</html>
I don't see any trouble of using $http.get('file.json'),
you can use angular.toJson(result) to convert JSON string to object later on.
http://plnkr.co/edit/4K9sy5aCP4NML0nnYgZ4
This is solution for your question
$http({
method: "get",
url: "link to your json file"
}).success(function (data) {
callback(data);
});