Compare data with ajax response using jquery - javascript

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

Related

Why it value does not send in to ajax post?

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

how to use json data sent from backend

$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
<li>"i want to insert variable here"<li>
},
error: function (data) {
console.log('Error:', data);
}
});
controller returns this
return Response::json($results);
and it gives this
{"results":[{"id":1,"name":"user","nick":"user1"}]}
how can i acces this in ajax part
You can use the data in ajax, sent from controller like this:
$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) { // <-------- here data is your variable having json received from backend
$.each(data.results, function(key, val) {
// Use your results array here...
$('li.data').each(function(i) {
$(this).find('span.id').text(val.id);
$(this).find('span.name').text(val.name);
$(this).find('span.nick').text(val.nick);
});
});
},
error: function (data) {
console.log('Error:', data);
}
});
You'll get json inside the data variable under the success section of your ajax call
Hope this helps!
In your success method you can access the data returned from the server as:
success: function(data) {
var users = data.results;
var temptale = '';
for (var i = users.length - 1; i >= 0; i--) {
temptale += "<li>Name - " + users[i]['name'] + "<li>"
}
// use temptale to insert in your DOM
},
var queryInfoById= function (id) {
var params = {
"id": id,
};
$.getJSON(prefix + "/queryById.do", params, function (data) {
$("#name").val(data.name);
$("#age").val(data.age);
});
};
$.ajax({
url: '{{ URL('reports/groupsUsersGet') }}',
dataType: "json",
data: {
group_id : $('#group').val(),
},
success: function(data) {
var array = data.results;
for (var i=0; i < array.length; i++){
var obj = array[i];
var id = obj.id;
var name= obj.name;
var nick= obj.nick;
//Add here the data in your UL>LI elements.
}
},
error: function (data) {
console.log('Error:', data);
}
});

AJAX how to extract data return

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

Send extra parameters with ajax chosen

I'm currently using the chosen JQuery plugin :
http://harvesthq.github.io/chosen/
with this complement (to add an Ajax request) :
https://github.com/meltingice/ajax-chosen
I would like to know if anyone has ever been able to send extra parameters to the ajax function.
For now it only sends the letters in the input, but I would like to send an extra id.
Here's what i'm doing:
$("#mySelect").ajaxChosen({
minTermLength: 2,
type: "GET",
url: "/Orders/ajax_getBundleItems",
dataType: "json",
error: onItemChosenFail
},
function (data)
{
var terms = {};
$.each(data, function (i, val) {
terms[i] = val;
});
return terms;
});
I'm using the CakePHP Framework, here's my ajax function:
public function ajax_getBundleItems($term = null) {
$this->layout = false;
echo "<pre>";
var_dump($this->request->data);
var_dump($this->params['url']['term']);
echo "</pre>";
}
$this->params['url']['term'] gives me the letters in the input, and I would like $this->request->data to be an id.
Regards
you can pass it in url parameter like this:
var id = 123;
$("#mySelect").ajaxChosen({
minTermLength: 2,
type: "GET",
url: "/Orders/ajax_getBundleItems?Id="+id,
dataType: "json",
error: onItemChosenFail
},
function (data)
{
var terms = {};
$.each(data, function (i, val) {
terms[i] = val;
});
return terms;
});
or
var MyId = 23;
$("#mySelect").ajaxChosen({
minTermLength: 2,
type: "GET",
url: "/Orders/ajax_getBundleItems",
dataType: "json",
data: { id:MyId },
error: onItemChosenFail
},
function (data)
{
var terms = {};
$.each(data, function (i, val) {
terms[i] = val;
});
return terms;
});
you can pass here you Id from some variable
This is the actual answer, using the BeforeSend option:
$('select[name=element_id]', '#f-load-tc').ajaxChosen({
type: 'GET',
url: 'dynamic_url',
dataType: 'json',
afterTypeDelay: 300,
allow_single_deselect: true,
no_results_text: "No results matched",
beforeSend: function(xhr, opts) {
opts.url += '&category_id='+$category.val();
},
},
function (data) {
console.log(data);
var terms = {};
$.each(data, function (i, val) {
terms[i] = val;
});
return terms;
});

MVC dropdownlist onchange event not calling properly the action in controller

Hi all I need to do here is that when the selection is changed of a dropdown list, with the use of AJAX I want to call an action and pass some data. Here below you can find The code that I am using. I have searched a lot and dont get why it is not entering in the action. The data and url are correct. The Controller name is HomeController and the action name is getData.
<script type="text/javascript">
function submitform() {
var a = document.getElementById("tournaments");
var datad = a.options[a.selectedIndex].value;
var url = '/Home/getData';
var completeurl = window.location.host + url;
alert(completeurl);
$.ajax({
type: "GET",
url: completeurl,
data: {tournamentid : datad},
datatype: 'JSON',
success: function (data) { alert('got here with data'); },
error: function () { alert('something bad happened'); }
});
};
</script>
Dropdownlist:
<%: #Html.DropDownList("tournaments", null, new { name = "tournaments", title = "Please Select Tournament.", onchange = "submitform();",id = "tournaments"}) %>
Action:
[HttpGet]
public ActionResult getData(int? tournamentid)
{
//perform your action here
UserBl us = new UserBl();
int num = Convert.ToInt32(tournamentid);
Tournament tour = us.GetTournamentById(num);
return Json(tour, JsonRequestBehavior.AllowGet);
}
you would do it like this:
$(function(){ // document and jquery ready
$("#tournaments").on("change", function(e){
var dropValue = $(this).val();
$.ajax({
type: "GET",
url: '/Home/getData/' + dropValue,
datatype: 'JSON',
success: function (data) { alert('got here with data'); },
error: function () { alert('something bad happened'); }
});
});
});
There are two ways
one is (use selectedItem as tournamentId)
<script type="text/javascript">
$(function () {
$("#tournaments").change(function () {
var selectedItem = $(this).val();
submitform(selectedItem);
});
});</script>
Or
put javascript: for onchange attribute
onchange = "javascript:submitform();"
EDITED :
for that I would suggest
$.ajax({
cache: false,
type: "GET",
url: url,
data: { "tournamentid ": datad},
success: function (data) {
alert("succeded")
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed ');
}});

Categories

Resources