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);
},
});
}
Related
I'm a newbie working with ajax. I have a problem while sending the data into ajax post.
The output of console.log(obj.Id) and console.log(oke) is 2. Then I tried to send it through data in ajax, but it end up 0 in the controller.
$(function () {
$("body").on('click', '#btnEdit', function () {
alert("clicked ok");
$("#addRowModal").modal("hide");
var obj = {};
obj.Id = $(this).attr('data-id');
oke = $(this).data("id");
console.log(obj.Id)
console.log(oke)
$.ajax({
url: '#Url.Action("Details", "InvoicePPh")',
data: oke,
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("sukses");
},
error: function(response) {
alert("error")
}
});
});
});
And my controller looks like this
[HttpPost]
public JsonResult Details(int id)
{
var obj = dbContext.invoicePPhs.FirstOrDefault(s => s.Id == id);
InvoicePPh pph = new InvoicePPh();
pph2326.TaxForm = obj.TaxForm;
return Json(pph);
}
I want the '2' value that passes into my controller, how can I do that? Thank you for your help.
An alternative way to send your data your Controller method using Ajax would be to wrap your data in a JSON object and then send it to the server for processing. The server will be then deserialize your JSON object and you can access the required properties from that process:
$(function () {
$("body").on('click', '#btnEdit', function () {
alert("clicked ok");
$("#addRowModal").modal("hide");
var obj = {};
obj.Id = $(this).attr('data-id');
oke = $(this).data("id");
console.log(obj.Id)
console.log(oke)
var json = {
oke: oke
};
$.ajax({
url: '#Url.Action("Details", "InvoicePPh")',
data: {'json': JSON.stringify(json)},
type: 'POST',
dataType: "json",
success: function (response) {
alert("sukses");
},
error: function(response) {
alert("error")
}
});
});
});
And your Controller method will be:
using System.Web.Script.Serialization;
[HttpPost]
public JsonResult Details(string json)
{
var serializer = new JavaScriptSerializer();
dynamic jsondata = serializer.Deserialize(json, typeof(object));
//Get your variables here from AJAX call
var id= Convert.Int32(jsondata["id"]);
var obj = dbContext.invoicePPhs.FirstOrDefault(s => s.Id == id);
InvoicePPh pph = new InvoicePPh();
pph2326.TaxForm = obj.TaxForm;
return Json(pph);
}
If you just need id in your method parameter just change data in ajax to:
contentType: "application/x-www-form-urlencoded",
data: { 'id': oke },
id is name of parameter from controller method.
Please change the data property in ajax part.
$.ajax({
url: '#Url.Action("Details", "InvoicePPh")',
data: { 'id': oke },
type: 'POST',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (response) {
alert("sukses");
},
error: function(response) {
alert("error")
}
});
I am currently trying to request Data with Java Script from my API but it doesn`t work.
Everytime i POST i get the error, that "TypeError: 'NoneType' object is not subscriptable" in FLASK.
Code of my API:
#http://127.0.0.1:5000/fnd
#app.route('/fnd', methods=['POST'])
def fnd():
content = request.json
return jsonify(content['Text'])
For the Post I am using JQuery AJAX Requests
$(function ()
{
var output = $('#output');
$('#checkonfake').on('click',function(){
var texttocheck = $('#texttocheck').val();
var datad = {"Text": texttocheck}
console.log(datad);
if(texttocheck != ""){
$.ajax(
{
dataType: "json",
type: 'POST',
data:
{
datad
},
url: 'http://127.0.0.1:5000/fnd',
success: function (result)
{
console.log(result);
},
error: function ()
{
console.log("error");
}
});
}
})
});
I have like a Input Box and a button and as soon as i press the button the request should be sent off.
you can change code to this by string:
#http://127.0.0.1:5000/fnd
#app.route('/fnd', methods=['POST'])
def fnd():
s_json = request.get_data(as_text=True)
obj = json.loads(s_json)
return jsonify(obj['Text'])
and change html code to this:
datad = {"aaa":"aaaa", "bbb":"bbb","Text":"Text"}
$.ajax(
{
dataType: "json",
type: 'POST',
data: JSON.stringify(datad),
url: 'http://127.0.0.1:5000/fnd',
success: function (result)
{
console.log(result);
},
error: function ()
{
console.log("error");
}
});
or if you wana uses json
#app.route('/fnd', methods=['POST'])
def fnd():
return jsonify(request.form["Text"])
datad = {"aaa":"aaaa", "bbb":"bbb","Text":"Text"}
$.ajax(
{
dataType: "json",
type: 'POST',
data: datad,
url: 'http://127.0.0.1:5000/fnd',
success: function (result)
{
console.log(result);
},
error: function ()
{
console.log("error");
}
});
by the way:
i can't find the info for request.json in flask.palletsprojects.com
so.. i don;t know this param means and why it is none
I have following jquery code in my Razor viewpage
$(document).ready(function () {
var grouplistvalues = #Html.Raw(Json.Encode(Session["grouplist"]));
$("#nsline").click(function () {
alert(grouplistvalues)
$.ajax({
type: "POST",
url: "SetupGroups",
data: { grouplist : grouplistvalues },
dataType: "html",
success: function (response)
{
grouplistvalues = null;
grouplistvalues = response;
alert(response)
},
error: function ()
{
}
});
});
$("#ewline").click(function () {
$.ajax({
type: "POST",
url: "SetupGroups",
data: { grouplist : grouplistvalues },
dataType: "html",
success: function (response)
{
grouplistvalues = null;
grouplistvalues = response;
},
error: function ()
{
}
});
});
in above grouplistvalues its taking session as html raw
when I alert it on #nsline click function I can see it,
in above function I'm calling to ajax function and above grouplistvalues value updating
once I alert it on #nsline click function success response I can see a alert like folllowing
since this(grouplistvalues value) 1,2,.. changing as [1,2..] I cannot call to other ajax function in #ewline click function since parameter difference,
this is the above common ajax call
[HttpPost]
public JsonResult SetupGroups(long[] grouplist)
{
Session["grouplist"] = null;
List<long> groupList = new List<long>();
foreach (var groupitem in grouplist)
{
groupList.Add(groupitem);
}
long[] grouparray = groupList.ToArray();
Session["grouplist"] = grouparray;
return Json(grouparray);
}
}
Though I have two click functions its work with only the first click(ewline or nsline only the first time)
How to solve this
It was the dataType in your ajax request. It should be json:
dataType: "json"
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);
}
Can't seem to get the variable getID to work. I'm trying to change the html of the div. I know that the variable has the right value.
$('.cardid').change(function() {
var getID = $(this).attr('value');
$.ajax({
type: "POST",
url: "inc/change_thumbnail.php",
data: "id="+getID,
cache: false,
success: function(data) {
$("#"+getID).html(data);
alert("success");
},
error: function (err) {
alert("error");
}
});
});
Write data in $.ajax as data: {id : getID}, instead of data: "id="+getID,
Use val to get the value of an input :
var getID = $(this).val();
As you're making a POST request, you should also use the data argument to let jQuery properly send the value :
$.ajax({
type: "POST",
url: "inc/change_thumbnail.php",
data: {id:getID},
cache: false,
success: function(data) {
$("#"+getID).html(data);
alert("success");
},
error: function (err) {
alert("error");
}
});
You can try this:
$('[id="'+getID+'"]').html(data);
and yes you should pass it this way:
data:{id:getID}