Should I use another variable for "streszczenie"? or what should I do?
In my opinion in TinyMCE body have html but I get only "\t" Pobably I have got problem with JS
this is new problem - this question is related with this link. I added this for other users
this I write in TinyMCE
this I get from TinyMCE textarea "streszczenie"
As you can see there is text ghhfgh but I can`t get this text
Now I have got problem with execute JSON
<script type="text/javascript">
function Save() {
tinyMCE.triggerSave();
var Temat_controll = $('#Temat').val();
var Streszczenie_controll = tinyMCE.get('Streszczenie').getContent();
var PelnyOpis_controll = $('#PelnyOpis').text();
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
Temat: Temat_controll,
Streszczenie: Streszczenie_controll,
PelnyOpis: PelnyOpis_controll
},
type: "POST",
async: false,
error: function() {
},
success: function(data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
I get this but all the time JSON is not execute
When I click button tinyMCE.get('Streszczenie').getContent() is empty I check this and I don`t know why because I have got text into textarea
<script type="text/javascript">
function Save() {
var Temat_controll = $('#Temat').val();
var $d = tinyMCE.get('Streszczenie').getContent();
if ($d.length != 0) {
if ($d.val().length != 0) {
var Streszczenie_controll = tinyMCE.get('Streszczenie').getContent();
}
else {
var Streszczenie_controll = 'ewewe';
}
}
var PelnyOpis_controll = $('#PelnyOpis').text();
$.ajax({
url: '#Url.Action("DodajTematSave", "StronaGlowna")',
dataType: "json",
data: {
Temat: Temat_controll,
Streszczenie: Streszczenie_controll,
PelnyOpis: PelnyOpis_controll
},
type: "POST",
async: false,
error: function () {
},
success: function (data) {
if (data.Success) {
alert('success');
}
}
});
}
</script>
You are getting the content in wrong way, not by jQuery's val().
To get the tinymce content, just use tinyMCE object reference:
// Get the HTML contents of the currently active editor
console.debug(tinyMCE.activeEditor.getContent());
// Get the raw contents of the currently active editor
tinyMCE.activeEditor.getContent({format : 'raw'});
// Get content of a specific editor:
tinyMCE.get('content id').getContent()
As mentioned:
http://www.tinymce.com/wiki.php/API3:method.tinymce.Editor.getContent
Hope it heled. Polish man : )
Related
I want to post data in the Mssql Database using Asp.netCore Api and Html Form. I have Added This script to post data.but All the values are coming null
Jquery script in Html File
<script type="text/javascript">
var valdata = $("#formData").serialize();
$(document).ready(function () {
$("#btnsubmit").click(function (e) {
let formData = {};
$("#formData").serializeArray().map((x) => { formData[x.name] = x.value; });
$.ajax({
url: "https://localhost:44389/Register",
contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: 'json',
data: valdata,
success: function (data) {
alert(data);
},
failure: function (data) {
alert("Failure: " + data);
},
error: function (data) {
alert("Error: " + data);
}
});
});
});
</script>
.net Core Api
[HttpPost]
[Route("Register")]
public void RegisterExecute([FromBody]CustmRegistration Register)
{
try
{
userInterface.InsertCustomer(Register);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
but All the values are coming null
Where are these values null? my suggestion is to start debugging a bit more thoroughly.
Have you tried your api function trough postman or a tool likewise?
Settting breakpoints can be nice to look into your program's data at runtime.
if these values are null in your database it would be nice to see what userInterface.InsertCustomer(Register); does.
Once you know if your .net part is working start debugging your ajaxc call. take a look at the network section of the developer tools form the browser you are using.
If you have collected more data, people can help you more easelly.
1.When you use .serialize(), it generates the data in a query string format which needs to be sent using the default contentType which is application/x-www-form-urlencoded; charset=UTF-8, not as JSON. Either remove the contentType option or specify contentType: application/x-www-form-urlencoded; charset=UTF-8 can work.
2.Also you need move the serialize method into onclick event.
3.Be sure change [FromBody] to [FromForm].
Here is a whole working demo:
View:
#model CustmRegistration
<form id="formData">
<!--more code-->
<input type="button" id="btnsubmit"value="create" />
</form>
#section Scripts
{
<script type="text/javascript">
$(document).ready(function () {
$("#btnsubmit").click(function (e) {
var valdata = $("#formData").serialize(); //move to here...
$.ajax({
url: "/home/Register",
//contentType: "application/json; charset=utf-8",
type: 'POST',
dataType: 'json',
data: valdata,
success: function (data) {
alert(data);
},
failure: function (data) {
alert("Failure: " + data);
},
error: function (data) {
alert("Error: " + data);
}
});
});
});
</script>
}
Controller:
[HttpPost]
[Route("Register")]
public void RegisterExecute([FromForm]CustmRegistration Register)
{ //...}
I have the following jquery function which is sending data to a controller:
function bound(e) {
var ele = document.getElementsByClassName("e-grid")[0]
ele.addEventListener('click', function (e) {
if (e.target.classList.contains('e-up')) {
var grid = document.getElementById('FlatGrid').ej2_instances[0]; //Grid Instance
var rowObj = grid.getRowObjectFromUID(ej.base.closest(e.target, '.e-row').getAttribute('data-uid'));
var data = rowObj.data;
//alert(JSON.stringify(data));
var code = data.ClientCode;
$.ajax({
type: "POST",
url: "/Client/ShowClient",
data: { "ClientCode": code }, //First item has latest ID
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
}
});
}
And my controller method:
[HttpPost]
public ActionResult ShowClient(string ClientCode)
{
if (ClientCode == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
*action*
}
However I am getting a 500 (Internal Server Error) error for this. Any idea what I am missing cause my method is not being hit at all.
And I can see that var code does have the correct string value.
Remove commas from the parameter name "ClientCode" and contentType and will be work
$.ajax({
type: "POST",
url: "/Client/ShowClient",
data: { ClientCode: code }, //First item has latest ID
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
The comments have provided you with a combination of suggestions that when put together will give you the desired behavior.
First, you can build the URL in teh view using #Url.Action
url: '#(Url.Action("ShowClient","Client"))',
Next, the object model is not being built correctly
data: { ClientCode: code },
Note the last of quotes around the key.
And finally remove the JSON content type.
Which results to portion of code.
$.ajax({
type: "POST",
url: '#(Url.Action("ShowClient","Client"))',
data: { ClientCode: code },
success: function (data) {
if (data.length !== 0) {
console.log(data);
}
},
error: function (data) {
console.log(data);
}
});
Change the url to this:
url: "../Client/ShowClient"
I want to write code for multipledelete by using jquery json.
This is the jquery code:
function DeleteSelected() {
var categories = new Array();
debugger;
// iterate all checkboxes and obtain their checked values, unchecked values are not pushed into array
$("input[type='checkbox']").each(function ()
//$('input[type=checkbox]').prop("checked", this.checked)
{
this.checked ? categories.push($(this).val()) : null;
});
// assume urldata is your web method to delete multiple records
var urldata = "WebForm5.aspx/deleteRecord";
debugger;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: urldata,
data: "{ 'Id':'"+JSON.stringify( categories)+"' }", // used to convert array into proper JSON format
dataType: "json",
success: function (dt) {
// done whatever tasks if succeeded
alert("entry deleted");
debugger;
$("#example1").DataTable();
//$("#example1").bind;
debugger;
},
error: function (result) {
alert("Error");
}
});
}
This is aspx code(codebehind for multiple delete):
[WebMethod]
// note clear difference between single and multiple selections
public static void deleteRecord(List<int> Id)
{
clsCategoryBL objproject = new clsCategoryBL();
// iterate through input list and pass to process method
for (int i = 0; i < Id.Count; i++)
{
objproject.CategoryDelete(Id[i]);
}
}
I want to pass the id to aspx page but the problem is that output comes error popup.
error: function (result) {
alert("Error");
}
The below line will return JSON for the array categories
"{ 'Id':'"+JSON.stringify( categories)+"' }"
Validate the value with http://jsonlint.com/ and check if the result is valid JSON.
Since you had declared the method as public static void deleteRecord(List<int> Id) that means the expected input will be like [1,2,3]
Also use below line to get exact error coming
error: function (xhr, ajaxOptions, thrownError) {
alert("error # " + xhr + ajaxOptions + thrownError);
}
UPDATE 1:
Below is working code
var categories = new Array();
// do your logic to push
categories.push(1);
categories.push(2);
categories.push(3);
var valuetxt = "{ \"Id\":\"" + JSON.stringify(categories) + "\" }";
var urldata = "WebForm1.aspx/deleteRecord";
$.ajax({
type: "POST",
url: urldata,
data: valuetxt, // used to convert array into proper JSON format
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
// in result you will get same data which is posted
alert(result.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("error # " + xhr + ajaxOptions + thrownError);
}
});
[WebMethod]
// change the parameter to string, convert back JSON to Integer Array
public static string deleteRecord(string Id)
{
// do something - for sample here returning same JSON of integer
return Id;
}
Controller:
[HttpPost]
public ActionResult FileExist(string fileName)
{
bool result = true;
string path = Server.MapPath(TempPath) + fileName + ".xlsx"; //Path for the file
string[] Files = Directory.GetFiles(Server.MapPath(TempPath));
for (int i = 0; i < Files.Length; i++)
{
if (path == Files[i])
{
//The filename already exists
result = false;
}
}
return Json(new { returnvalue = result });
}
My JS:
$(document).on('click', '#saveButton', function () {
var fileName = $('#fileName').val();
$.ajax({
type: 'POST',
url: '/Calculation/FileExist',
data: { 'fileName': fileName },
dataType: 'JSON',
success: function (result) {
if (!result.returnvalue) {
$('#errorMessage').text("The filename already exists. Please choose another one (The files are automatically deleted every second day)");
$('#downloadButton').css("visibility", "hidden");
}
}
});
});
When I debug this in VS it works fine. But when I have Published and put it up on a server it wont work.
My error looks like this:
Why is this not working when published?
Considering that Calculation is your Controller Class, try to give the ajax request as following
$.ajax({
type: 'POST',
url: '#Url.Action("FileExist","Calculation")',,
data: { 'fileName': fileName },
dataType: 'JSON',
success: function (result) {
if (!result.returnvalue) {
$('#errorMessage').text("The filename already exists. Please choose another one (The files are automatically deleted every second day)");
$('#downloadButton').css("visibility", "hidden");
}
}
});
And if this event is written in a seperate js file then here is a code for that.
In your View make a js function as
function GetUrlToCheckIfFileExist(){
return '#Url.Action("FileExist","Calculation")';
}
And in your js file use the following code
var getUrlToCheckIfFileExist = window.GetUrlToCheckIfFileExist();
$.ajax({
type: 'POST',
url: getUrlToCheckIfFileExist,
data: { 'fileName': fileName },
dataType: 'JSON',
success: function (result) {
if (!result.returnvalue) {
$('#errorMessage').text("The filename already exists. Please choose another one (The files are automatically deleted every second day)");
$('#downloadButton').css("visibility", "hidden");
}
}
});
Make the url in view and set in a javascript variable and use it in your js file.
for cshtml file
<script>
var urlpath = '#Url.Action("FileExist","Calculation")';
</script>
for js file
$(document).on('click', '#saveButton', function () {
var fileName = $('#fileName').val();
$.ajax({
type: 'POST',
url: urlpath,
data: { 'fileName': fileName },
dataType: 'JSON',
success: function (result) {
if (!result.returnvalue) {
$('#errorMessage').text("The filename already exists. Please choose another one (The files are automatically deleted every second day)");
$('#downloadButton').css("visibility", "hidden");
}
}
});
});
//When focusout event is working, tested with alert.. but ajax call is not working and my aspx.cs method also not firing.. Please solve this issue.
//This is my aspx page jquery code.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var elem = document.getElementById('<%=txtProduct.ClientID %>');
$(elem).focusout(function () {
myF($(this).val());
});
function myF(value) {
var fist = value.split(' ( ', 1);
$.ajax({
type: 'POST',
url: 'Invoice.aspx/getProductDetails',
data: "{'strCode':'" + fist + "'}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
alert(response.d.toString());
},
failure: function (response) {
alert('error');
}
});
}
});
</script>
//Server side code
[WebMethod]
public static string getProductDetails(string strCode)
{
List<string> companyInfo = new List<string>();
companyInfo.Add(HttpContext.Current.Cache[Convert.ToString(HttpContext.Current.Session["UserID"]) + "CompanyID"].ToString());
companyInfo.Add(strCode);
List<string> price = Database.MasterDB.getProductInfo(companyInfo);
if (price.Count > 0)
return price[0].ToString();
else
return "000";
}
Since you are using Session thing inside web method, that might be giving null values or blank values. This is because you have not enabled session for webmethod.
Like this - [WebMethod(EnableSession=true)].
Read more