i am trying some idea on a ajax send,but i can't find why this code can't not send any parameter to jsp and thorw the nullpointerException.
I fix my code here,thanks for reponse.
var dfd = {
resolve : function (res) {
$("#Div123").html(res);
}
};
function getAjaxResponse(page, responseType, dataVar, dataVal, dfd) {
var dataObject = $.parseJSON('{"'+ dataVar +'":"'+ dataVal +'"}');
$.ajax(page, {
type: 'POST',
dataType: responseType,
data: dataObject,
success: function (responseData) {
dfd.resolve(responseData);
}
});
}
$(document).ready(function(){
$("#submit").click(function(){
getAjaxResponse("ajaxreponse.jsp", "text", "aa", "yes", dfd);
});
});
Change your data to:
data: { dataVar : dataVal }
and your dataType to
dataType: isJSON ? "JSON" : "text
They both don't accept functions.
data accepts plain object or string and dataType accepts only string
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 writing a function in jquery which post the data to controller. currently it is posting form data to controller fine but when i post checkbox list with form data then it send always count 0 in controller here is my code.
function SubmitForm() {
var studentFormData = $("#frmStudent").serialize();
debugger;
var SubjectArraydata = new Array();
$(".chkSubject:checked").each(function () {
var row = {
"SubjectId": $(this).data("id")
};
SubjectArraydata.push(row);
});
$.ajax({
url: '#Url.Action("StudentForm", "Student")',
type: "POST",
dataType: "json",
data: studentFormData + JSON.stringify("&subjectData=" + SubjectArraydata),
async: true,
success: function (msg) {
},
error: function () {
}
});
}
Controller:
[HttpPost]
public ActionResult StudentForm(Student student, List<Subject> subjectData)
{
return Json(true);
}
any one tell me where is the problem in my code thank you.
Your cannot mix 'application/x-www-form-urlencoded' data (the contentType of your serialize() method) and 'application/json' data (the contentType of the JSON.stringify() method) like that.
Sinve you have confirmed that your only submitting one property of Subject, which is SubjectId and is typeof int, then you can append the SubjectId values to the serialized data.
var studentFormData = $("#frmStudent").serialize();
$(".chkSubject:checked").each(function () {
studentFormData += '&' + $.param({ SubjectIds: $(this).data("id") });
};
$.ajax({
url: '#Url.Action("StudentForm", "Student")',
type: "POST",
dataType: "json",
data: studentFormData,
success: function (msg) {
},
error: function () {
}
});
and change your controller method to
[HttpPost]
public ActionResult StudentForm(Student student, List<int> SubjectIds)
{
....
I think you use 'POST' method not correctly. You try to mix sending data as json and as url parameters.
data: studentFormData + JSON.stringify("&subjectData=" + SubjectArraydata),
what you send in data:
[
{...},
[{SubjectId: ''}, {SubjectId: ''}]
]
or:
{
1: {...},
subjectData: [{SubjectId: ''}, {SubjectId: ''}]
}
or some data sended as json, some in url?
Send all data in json, and dont serialize (jquery do it for you):
var data = [strudentFormData, subjectData];
$.ajax(..., data: data, ...);
as you see i have a ajax code pass data to server and return result include id,name,quantity.
How to get quantity or id or name only and print ? thank you!
<script type="text/javascript">
$("#bto_update_quantity").click(function (){
$.ajax({
url:"cart/update_quantity",
type:"get",
dataType:"text",
data : {
id : $('.frm_product_id_cart').text(),
name : $('.frm_product_name_cart').text(),
quantity : $('#frm_product_quantity_cart').val()
},
success : function()
{
$('#frm_product_quantity_cart').val()
}});
});
</script>
use dataType JSON instead of text.
$("#bto_update_quantity").click(function () {
$.ajax({
url: "cart/update_quantity",
type: "get",
dataType: "json",
data: {
id: $('.frm_product_id_cart').text(),
name: $('.frm_product_name_cart').text(),
quantity: $('#frm_product_quantity_cart').val()
},
success: function (data) {
var id = data.id;
var name = data.name;
var quantity = data.quantity;
}
});
});
your dataType should be Json and not a Text.
you should pass a return param in success function
success : function(data)
try to console log the data and you would know how to get your desired values
If result is object.
You can do:
$("#bto_update_quantity").click(function (){
$.ajax({
url:"cart/update_quantity",
type:"get",
dataType:"text",
data : {
id : $('.frm_product_id_cart').text(),
name : $('.frm_product_name_cart').text(),
quantity : $('#frm_product_quantity_cart').val()
},
success : function(result)
{
console.log(result.quantity);
}});
});
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}
I am making a simple ajax request using jquery . Below is my ajax function .
var makeJqueryAjaxRequest = function(arrParam) {
var request = $.ajax({
url : arrParam['url'],
async: false,
type: arrParam['type'],
data: arrParam['data'],
dataType: arrParam['data_type'],
success: function(data) {
if(data){
return data;
}
}
});
}
here is my function calls :
var items = {
"type" : 'POST',
"url" : ajaxGetUrl,
"data" : arrParam['data'],
"data_type" : 'html'
};
var msg = makeJqueryAjaxRequest(items);
Now don't know why my makeJqueryAjaxRequest function always returns the null value. If I alert the data in the success : I'm getting the data perfect . But when I try to return it gives me the null value
You can't return value from an Asynchronous callback function.
Because success is a async callback which is called by jQuery when a ajax Event(success in this case) fires. So returning something from this functions will not have any effect as they will be returned to jQuery code.
You can use the following
var makeJqueryAjaxRequest = function(arrParam) {
var request = $.ajax({
url : arrParam['url'],
async: false,
type: arrParam['type'],
data: arrParam['data'],
dataType: arrParam['data_type']
});
return request;
}
Then do
makeJqueryAjaxRequest(items).done(function(data){
if(data){
var msg = data;
// do whatever you like with msg now
}
});
Alternative Callback Approach:
var makeJqueryAjaxRequest = function(arrParam,callback) {
var request = $.ajax({
url : arrParam['url'],
async: false,
type: arrParam['type'],
data: arrParam['data'],
dataType: arrParam['data_type'],
success: function(data) {
if(data){
callback(data);
}
}
});
}
Then use it like
makeJqueryAjaxRequest(items,function(data){
// do whatever you like with data
});
Doc on $.ajax()
Note
And with either of these approach async: false is not necessary. You can remove that. As the doc says
As of jQuery 1.8, the use of async: false is deprecated