I have a tinymce wysiwyg and i want to post the html from it to my action method:
$("#save").click(function () {
var ed = tinymce.get('wysiwyg');
var id = $("#destinationId").val();
var PostContent = JSON.stringify({ 'content': ed.getContent(), 'destinationId' : id });
console.log(PostContent);
$.ajax({
url: '#Url.Action("SaveDestinationContent", "Home")',
type: 'POST',
dataType: 'JSON',
cache: false,
data: PostContent,
success: function (data) {
},
error: function (xhr, error) {
},
});
I always get null in my action method that looks like this:
[HttpPost]
public ActionResult SaveDestinationContent(string content, string destinationId)
{
return Json("TRUE");
}
i have tried to do this in a couple of different ways:
$("#save").click(function () {
var ed = tinymce.get('wysiwyg');
var PostContent = ed.getContent();
console.log(ed.getContent());
var id = $("#destinationId").val();
$.ajax({
url: '#Url.Action("SaveDestinationContent", "Home")',
type: 'POST',
dataType: 'JSON',
cache: false,
data: {
content: PostContent.toString(), destinationId: id
},
success: function (data) {
},
error: function (xhr, error) {
},
});
but none of them work!
<---- EDIT ------>
I know it has to do with the serialization of the html because when i just add some random string and post that it works as expected!
Related
I have some ajax call like this
function ExportData() {
var data = {
action: "export_database", // the name of your PHP function!
};
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: data,
beforeSend: function () {},
success: function (data) {
alert(data);
},
});
}
And php function like this
function export_database(){
return $response;
}
The problem is in that response I have something like this
{
"type": "https://tools.ietf.org/html/rfc7231#section-6.5.1",
"title": "One or more validation errors occurred.",
"status": 400,
"traceId": "|3fa58ee1-48bf0cb9f60bfa25."
}
I want to alert only title, but when i try data.title , i got undefine
Do I must encode or decode something, thanks?
This is what you need. Just access the object by data.title and it will show in the alert()
You need to define dataType as json in your request.
If its does not work then use JSON.parse(data) like this:
var response = JSON.parse(data)
alert(response.title)
Try below:
function ExportData() {
var data = {
action: "export_database", // the name of your PHP function!
};
jQuery.ajax({
type: "POST",
url: ajaxurl,
dataType: 'json'
data: data,
beforeSend: function () {},
success: function (data) {
alert(data.title);
},
error: function(error){
//Error
alert(error.title)
}
});
}
Hope this helps.
Try Below:
function ExportData() {
var data = {
action: "export_database", // the name of your PHP function!
};
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: data,
beforeSend: function () {},
success: function (data) {
var parsedData = jQuery.parseJSON(data)
alert(parsedData.title);
},
});
}
You have to use JSON.parse() for accessing data objects Like this:
function ExportData() {
var data = {
action: "export_database", // the name of your PHP function!
};
jQuery.ajax({
type: "POST",
url: ajaxurl,
data: data,
beforeSend: function () {},
success: function (data) {
var res = JSON.parse(data)
alert(res.title);
},
});
}
I am trying to pass the model from view to controller using ajax AND when I check the value in the JS debugger model has data but it's not binding with controller and the controller model is showing null.
function BulkUpdate()
{
debugger;
var model = #Html.Raw(Json.Encode(Model.tags))
$.ajax({
type: 'GET', //GET
data: JSON.stringify({model}),
url: '#Url.Action("BulkUpdate", "Home")',
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});
}
//and my controller code is
public ActionResult BulkUpdate(List<Tag> tags)
{
ModelAccessor obj1 = new ModelAccessor();
obj1.updatedDatas = new List<UpdatedData>();
foreach (var item in tags)
{
var tag = db.Tags.Where(x => x.Id.Equals(item.Id)).FirstOrDefault();
if (tag.TagValue != item.TagValue)
{
UpdatedData changedRow = new UpdatedData {
OldTagValue=tag.TagValue,
NewTagValue=item.TagValue.Trim()
};
obj1.updatedDatas.Add(changedRow);
}
}
return PartialView("_UpdateConfirmationBulk", obj1);
}
I have a solution.
function BulkUpdate()
{
debugger;
var model = #Html.Raw(Json.Encode(Model.tags))
$.ajax({
type: 'GET', //GET
data: {'tags':JSON.stringify({model})},
url: '#Url.Action("BulkUpdate", "Home")',
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});
}
Try this because your method expects a parameter named tags and this is missing in you ajax call.
Can you try the type by post?
var model = #Html.Raw(Json.Encode(Model.tags))
$.ajax({
type: 'POST', //GET
data: JSON.stringify({model}),
url: '#Url.Action("BulkUpdate", "Home")',
contentType: 'application/json; charset=utf-8',
dataType: "json",
success: function (data) {
$('#myModalContent').html(data);
$('#myModal').modal('show');
}
});
I have the function below:
function getHtmlFromMarkdown(markdownFormat, requestUrl) {
const dataValue = { "markdownFormat": markdownFormat }
$.ajax({
type: "POST",
url: requestUrl,
data: dataValue,
contentType: "application/json: charset = utf8",
dataType: "text",
success: function (response) {
alert(response);
document.getElementById("generatedPreview").innerHTML = response;
},
fail: function () {
alert('Failed')
}
});
}
And i have this on my server:
[WebMethod]
public static string GenerateHtmlFromMarkdown(string markdownFormat)
{
string htmlFormat = "Some text";
return htmlFormat;
}
I have on response html code, not the string that i want. What am I doing wrong?
And if i change the "dataType: json" it doesn't even enter either the success nor fail functions
Your data type of ajax must be json like this
function getHtmlFromMarkdown(markdownFormat, requestUrl) {
var dataValue = { "markdownFormat": markdownFormat }
$.ajax({
type: "POST",
url: requestUrl,
data: JSON.stringify(dataValue),
dataType: "json",
success: function (response) {
alert(response);
document.getElementById("generatedPreview").innerHTML = response;
},
error: function () { alert("Failed"); }
});
}
try with this.
function getHtmlFromMarkdown(markdownFormat, requestUrl) {
var obj={};
obj.markdownFormat=markdownFormat;
$.ajax({
type: "POST",
url: requestUrl,
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
document.getElementById("generatedPreview").innerHTML = response.d;
},
failure: function () {
alert('Failed')
}
});
}
The web service on http://localhost:57501/api/addDatabase has the following code.
[System.Web.Mvc.HttpPost]
public ActionResult Post(addDatabase pNuevaConeccion)
{
pNuevaConeccion.insertarMetaData();
return null;
}
The Ajax function is on a javascript that creates the JSON from the give values on http://localhost:1161/CreateServer.
$(document).ready(function ()
{
$("#createServer").click(function (e) {
e.preventDefault(); //Prevent the normal submission action
var frm = $("#CreateServerID");
var dataa = JSON.stringify(frm.serializeJSON());
console.log(dataa);
$.ajax({
type: 'POST',
url: 'http://localhost:57501/api/addDatabase/',
contentType: 'application/json; charset=utf-8',
crossDomain: true,
//ContentLength: dataa.length,
data: dataa,
datatype: 'json',
error: function (response)
{
alert(response.responseText);
},
success: function (response)
{
alert(response);
if (response == "Database successfully connected") {
var pagina = "/CreateServer"
location.href = pagina
}
}
});
});
});
When I run this code an alert pops up saying "undefined" but if I delete the contentType the alert doesn't show up. The problem is that the variables that the function Post (from the web service) receives are NULL even though I know that the JSON named dataa is not NULL since I did a console.log.
I have seen various examples and pretty much all of them say that I should use a relative URL but the problem is that since there are 2 different domains and when I tried it, it couldn't find the URL since it's not in the same localhost.
Web service should return a JSON format instead of null. like below example.
public JsonResult Post()
{
string output = pNuevaConeccion.insertarMetaData();
return Json(output, JsonRequestBehavior.AllowGet);
}
try to use this code for calling the web method
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: dataa,
url: 'http://localhost:57501/api/addDatabase/',
success: function (data) {
console.log(data);
},
error: function (error) {
console.log(error);
}
});
its my old code.(ensure action parameter variable name and post variable name are same)
$('#ConnectionAddres_ZonesId').change(function () {
var optionSelected = $(this).find("option:selected");
var id = { id: optionSelected.val() };
$.ajax({
type: "POST",
url: '#Url.Action("GetParetArea", "Customers")',
contentType: "application/json;charset=utf-8",
data: JSON.stringify(id),
dataType: "json",
success: function (data) {
$('#ConnectionAddres_ParentAreaId').empty().append('<option value="">Select parent area</option>');
$.each(data, function (index, value) {
$('#ConnectionAddres_ParentAreaId').append($('<option />', {
value: value.Id,
text: value.Area
}));
});
},
});
});
public ActionResult GetParetArea(int id)
{
var parents="";
return Json(parents, JsonRequestBehavior.AllowGet);
}
Is it possible to submit entire form (all the fields including fileupload) to server (webmethod or handler etc) using Jquery/Ajax? If yes, how?
ASPX:
$.ajax({
type: "POST",
url: "SupplierBidding.aspx/SubmitBid",
data: JSON.stringify({ id: $('#txtbidderid').val(), bidamt: $('#txtbidamt').val() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (data, status) {
span.fadeIn("slow", function () {
span.text(data.d).fadeOut('slow');
});
},
failure: function (data) {
alert(data.d);
},
error: function (data) {
alert(data.d);
setTimeout(function () {
btn.prop('disabled', false);
}, 3000);
}
});
}
WebMethod:
[WebMethod]
public static string SubmitBid(string id, string bidamt)
{
//code
return "";
}
I would like to replace data: JSON.stringify({ id: $('#txtbidderid').val(), bidamt: $('#txtbidamt').val() }) with entire form including files also.
You can use Formdata.
FormData Docs
Code example.
var fdata = new FormData();
fdata.append( 'file', input.files[0] );
$.ajax({
url: 'http://yourserver.com/upload.php',
data: fdata,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log('siceess')
}
});
Did you try jQuery Form plugin?
It handles file uploads.
Worked for me before.