AJAX how to extract data return - javascript

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);
}});
});

Related

Compare data with ajax response using jquery

I have Script is as below
$(document).ready(function () {
$('body').find('.tree').fadeOut(0);
$('.tree-title').click(function () {
var id = $(this).attr('id');
$.ajax({
contentType : "application/json; charset=utf-8",
dataType : "json",
url : "loadSubFolders",
type : 'GET',
data : {
id : id
},
success : function(response) {
$.each(response, function(index, value) {
response.push('<li class="tree-title" id='+value.folderId+'>'+value.folderName+'</li>');
alert("Appended Successfully");
});
$('.tree').append( response.join('') );
},
error : function(res, textStatus) {
var msg = "Unable to load Subfolder";
alert(msg);
}
});
setStatus($(this));
});
});
In this I want to compare data means id to some response element like
success : function(response) {
$.each(response, function(index, value) {
if(id==value.rootId){
response.push('<li class="tree-title" id='+value.folderId+'>'+value.folderName+'</li>');
alert("Appended Successfully");
}
else{
response.push('<li class="tree-title" ></li>');
alert("Append Failed");
}
});
$('.tree').append( response.join('') );
},
But it s not working
How could i achieve this? Can anybody suggest me?
You can supply properties to your success callback and access them from within the closure using this. Example this.id The custom properties you specify can't already be defined in the ajax prototype, otherwise you'll rewrite the default values. Try this:
$(document).ready(function () {
$('body').find('.tree').fadeOut(0);
$('.tree-title').click(function () {
var id = $(this).attr('id');
$.ajax({
contentType : "application/json; charset=utf-8",
dataType : "json",
url : "loadSubFolders",
type : 'GET',
data : {
id : id
},
id : id,
success : function(response) {
afterSuccess(response , this.id);
function afterSuccess(data, i) {
$.each(data, function(index, value) {
if(i==value.rootId){
data.push('<li class="tree-title" id='+value.folderId+'>'+value.folderName+'</li>');
alert("Appended Successfully");
}
else{
alert("Append Failed");
}
});
$('.tree').append( data.join('') );
}
}
});
setStatus($(this));
});
});
You could load your results into a separate variable like contents
$(document).ready(function () {
$('body').find('.tree').fadeOut(0);
$('.tree-title').click(function () {
var id = $(this).attr('id');
$.ajax({
contentType : "application/json; charset=utf-8",
dataType : "json",
url : "loadSubFolders",
type : 'GET',
data : {
id : id
},
id : id,
success : function(response) {
afterSuccess(response , this.id);
function afterSuccess(data, i) {
var contents = "";
$.each(data, function(index, value) {
if(i==value.rootId){
contents += '<li class="tree-title" id='+value.folderId+'>'+value.folderName+'</li>';
alert("Appended Successfully");
}
else{
alert("Append Failed");
}
});
$('.tree').append( contents );
}
}
});
setStatus($(this));
});
});

Jquery Ajax Data Key Name defining with a Variable

I am defining a key for 'id', instead of the variable 'action_upd's value(which is "action"), my php reads literally 'action_upd' and not the value
If I do in my php:
if($_POST['action_upd']){ echo "Action"}
my $.ajax will do --> alert "Action"
action_upd = "'" + action_upd + "'"; <-- same result
.
action_upd = "action";//used to be 'cow' if you check some comments
id = "1234";//just an id of an item
$.ajax({
type: 'POST',
url: './DB/DB.php',
data: { action_upd:id,'val': val},
success: function (result) {
alert(result);
},
error : function(result){
alert(result + "error");
}
});
Put action_upd in quotes if you want it to be a string and not a variable. Otherwise your code will do cow:id instead of action_upd:id when executed
$.ajax({
type: 'POST',
url: './DB/DB.php',
data: { 'action_upd':id,'val': val},
success: function (result) {
alert(result);
},
error : function(result){
alert(result + "error");
}
});
I seperated 'action_upd' and 'id', my idea was the key would change dependent of an option i choosed and would have the id
//original
data: { action_upd:id ,'val': val},
if 'action_upd' was (for example) 'update_item', if(isset($_POST['update_item'])){ update();}
//end result
data: { 'action_upd':action_upd,'id':id,'val': val},
need an extra if to check action_upd was iniciated then check the action

Jquery AJAX CALL with parameter to controller's method not working

I am working with Jquery AJAX Call in MVC Application. My view looks like this :
<p>
Name #Html.TextBox("Name")
Date #Html.TextBox("Date")
<input type="submit" id="SubmitName" value="Submit" />
</p>
My AJAX call is as follows :
<script type="text/javascript">
function send() {
var Details = JSON.stringify({
StudentName: $("#Name").val(),
DateofJoining: $("#Date").val()
});
$('#target').html('sending..');
$("SubmitName").click(function () {
$.ajax({
url: "/DQR/Details",
type: "POST",
dataType: "json",
contentType: "application/json",
data : Details ,
success: function (data) {
$('#target').html(data.msg);
},
});
})
}
</script>
And my controller looks like this :
[HttpPost]
public ActionResult Details (string StudentName, string DateofJoining)
{
var result = (from dc in _db.Details
where dc.Name== StudentName
select dc.Address);
return Json(result, JsonRequestBehavior.AllowGet);
}
I don't know what I'm missing. The ajax request is not working. Could anyone help me with this ?
Imagining that ur controller name is DQR then you need to write as below:-
$.ajax({
url: "/DQR/Details",
type: "POST",
dataType: "json",
contentType: "application/json",
data : Details ,
success: function (data) {
$('#target').html(data.msg);
},
});
and id should be:-
$("#SubmitName").click(function () {
var Details = JSON.stringify({
StudentName: $("#Name").val(),
DateofJoining: $("#Date").val()
});
$('#target').html('sending..');
//// your ajax call
}});
and what is Send()? i mean the click event should be under $(document).ready(function() {});
I would suggest take simple button rather than "submit" if you are playing client side with that.
Bind click handler properly, move Details object creation in click handler
$(function() {
$("#SubmitName").click(function () {
var Details = JSON.stringify({
StudentName: $("#Name").val(),
DateofJoining: $("#Date").val()
});
$('#target').html('sending..');
$.ajax({
url: "/DQR/Details",
type: "POST",
dataType: "json",
contentType: "application/json",
data : Details ,
success: function (data) {
$('#target').html(data.msg);
}
});
});
});
You can use jQuery $.post method as well.
Here is an example.
var StudentName = $("#Name").val();
var DateofJoining = $("#Date").val();
$.post('/Controller/Action', { 'StudentName': StudentName , 'DateofJoining': DateofJoining }, function(data) {
$('#target').html(data.msg);
}, 'json');
Here is more information about $.post

jQuery ajax request data not send

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

Variable not working in simple Ajax post

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}

Categories

Resources