Passing arguments in jquery ajax resulting in undefined - javascript

I'm new to jQuery. I'm creating a cascading dropdown using jquery ajax. So based on the changed value of first dropdown, the second script fetches values from database from second dropdown.
<script>
$(document).ready(function () {
$("#builder_group").change(function () {
var selected_builder = $(this).val();
alert(selected_builder);
$.ajax({
type: 'POST',
url: 'getGroupzCode.php',
data: 'selected_builder',
datatype: 'json',
success: function (data) {
// Call this function on success
console.log(data);
var yourArray = JSON.parse(data);
console.log(yourArray);
$.each(yourArray, function (index, yourArray) {
$('#builder_group1').append($('<option/>', {
value: yourArray.id,
text: yourArray.name,
}));
});
},
error: function () {
displayDialogBox('Error', err.toString());
}
});
});
});
</script>
Problem is when I alert the selected value from first dropdown it works i.e alert(selected_builder) works , but when I try to pass it to the script it is showing as undefined in PHP script. How can I solve this.

Don't pass it as a string.
data: selected_builder,

You're passing a string as your data. Try passin selected_builder without the surrounding ', like this:
data: selected_builder,

Pass the variable name instead of string.
data: selected_builder,

data: 'selected_builder'+data
It should be key value pair

When passing as a json string (for sending using jQuery ajax), let native javascript stuff do it for you. Pass your data as a correct JSON string to be interpreted by your target.
data : JSON.stringify({ selected_builder : selected_builder})
This will allow your receiving method to get the data as a parameter named selected_builder.

Related

calling action with string type parameter from JavaScript in MVC

I have bellow action in my controller:
public ActionResult ShowContactTel(string tel)
{
return PartialView("ContactInfoView", tel);
}
And I call above action by JavaScript like this: (It is fired by clicking on a button)
function ShowTel(){
var e="#Model.TelShow";
$.get("ViewProfile/ShowContactTel", e).then(
function (r) {
$('#divTel').innerHTML = r;
});
}
But input argument of action receives null value (by setting break-point) and so return undesirable output.
Remark 1:
I tried bellow code for ShowTel() function but result not changed:
var str = "#Model.TelShow";
$.ajax({
type: 'GET',
url: '#Url.Content("~/ViewProfile/ShowContactTel")',
data: str,
success: function (dd) {
$('#divTel').innerHTML = dd;
}
});
And
var str = "#Model.TelShow";
$.ajax({
url: "ViewProfile/ShowContactTel",
type: 'GET',
data: str
}).then(function (r) {
$('#divTel').innerHTML = r;
});
I also tried type: 'POST' but it not working too.
Remark 2:
Using debugger command in ShowTel() function, I see #Model.TelShow has true value.
What is the problem?
Your current code (first approach) is passing the value of e variable as the data parameter for the $.getcall. jQuery $.get method will send that as query string values. So your code is making a get call like the below URL.
/ViewProfile/howContactTel?testValue
Assuming testValue is the value of variable e
Your action parameter name is tel. So send an js object with a property with that name.
Also use the jquery html method to update the inner html of your div.
$.get("/ViewProfile/ShowContactTel", { tel: e })
.then(function (r){
$('#divTel').html(r);
});
I would also recommend using the Url helper methods to generate the correct relative URLs to the action method.
var url = "#Url.Action("ShowContactTel","ViewProfile");
$.get(url, { tel: e }).then(function (r){
$('#divTel').html(r);
});

Writing specific value from database to HTML via AJAX/jQuery

First time question, hoping for some advice:
Code on webpage:
<form id="inbound" action="javascript:validateinbound();">
<input type="submit" value="Go!" id="inbound">
<script>
function validateinbound() {
$('#inbound:input').each(function () {
var iv = $(this).val();
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
var response = JSON.stringify(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+response);
}
});
});
});
};
</script>
</form>
This returns a string that I would like to work with that looks like this:
Answer:
[{"id":"1","answer":"Pull logging","question_id":"5","feature_id":"1","answer_id":"9"}]
Ideally what I would like to do is only select the 'value' to the maxmail_answer 'key' (hopefully those are the right terms?) to the webpage instead. Right now there is only one value but there will be more in the future so something that could parse this string for a specific key and only output those values.
Visually I would see:
Answer: Pull logging ( and then another Answer: for each value I pull out )
First time ever using this site and these languages so total noob and would appreciate some guidance.
Thanks!
You do not to stringify the JSON response, you can get the value of the key you want using the object notation . as follows:
function validateinbound() {
$('#inbound:input').each(function () {
var iv = $(this).val();
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
//var response = JSON.stringify(data); // no need for this line
$('#response').delay(3600).fadeIn(600);
// catch the answer here
// your result returns within an array so you need to catch the first index
$('#response').append("<p>Answer: </p>"+response[0].answer);
}
});
});
});
};
Besides, ids are unique, you can only access a single element via id selector #, you do not need a .each
What you are receiving from your server is an array of objects in the JSON format. The sample that you have put has the length of "1" and therefore, if want to reach the "id" of the first array, it would be like this:
// var response = JSON.stringify(data); (// don't stringify it!
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+data[0].id);
You need here a loop to go through your array of results and display each result
success: function(data) {
var response = JSON.stringify(data);
$('#response').delay(3600).fadeIn(600);
$.each(response,function(index,value){//the each loop
$('#response').append("<p>Answer: </p>"+value.answer);//get the answer using . notation
});
}
Json.stringify() returns your javascript object as json data, but i think in your case your response is a json data which you need to manipulate. Json.parse() does this for you and you can access your answer as a property of the javascript object.
success: function(data) {
var response = JSON.parse(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+response[0].answer);
}
if your json data has multiple result and you need to work through all of them use a loop.
$.each(response,function(index, object){
var response = JSON.parse(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+object.answer);
});
First of all. Thank you to everyone who commented on this to help me get started in the right direction. I was able to get what I needed working!! Here is the solution:
<form id="inbound" action="javascript:validateinbound();">
<input type="submit" value="Go!" id="inbound">
<script>
function validateinbound() {
$('#controlpanel:input').each(function () {
var iv = $(this).val();
$('#response').html("");
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
var newdata = JSON.stringify(data);
var response = JSON.parse(newdata);
$('#response').delay(3600).fadeIn(600);
$.each(response, function(array, object) {
$('#response').append("<p>Answer: </p>"+object.answer);
});
}
});
});
});
};
</script>
</form>
I needed to parse the data correctly. So I used JSON.stringify to get the data into a string that JSON.parse could use to manipulate the data. But function(index,object) wouldn't work because my output was not an index, but an array. So when changing to function(array,object) this allowed me to get my data just the way that I needed.
Again thanks to everyone for their help!

How to get a <list> from mvc controller to view using jquery ajax

I need to get a list from mvc controller to view using jquery ajax. But I get [object Object].
Ajax code
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: '/Home/getList',
success: function (data) {
debugger;
$scope.StuList = data;
alert(data);
}
});
In Controller
public JsonResult getList()
{
Models.clsSave obj = new Models.clsSave();
var list = new List<Model>();
list= obj.getList();
return Json(list,JsonRequestBehavior.AllowGet);
}
If you are getting [Object,Object] means it contains the data. You just Iterate it on the success function of your $.ajax as shown below
success: function (data) {
$.each(data.items, function(item) {
alert('id :'item.id +' Name:'+item.sname);
});
}
All the best
You are getting an Object from ajax response to view that in alert try to stingify your object:
alert(JSON.stringify(data))
I need to get a list from mvc controller to view using jquery ajax.
But I get [object Object].
that means you're getting correct data list
how will I store it in $scope.StuList
You can just assign that data to $scope.StuList.
$scope.StuList = data;
Just to verify your data, put it in iteration
$.each($scope.StuList,function(i,v){
alert(v.sname);
});
You should get the correct data.
Or you can also put it in console, and verify yourself.
console.log($scope.StuList)
Hope this will help, or let me know if you still facing any issue.

How to submit a form and pass some extra parameters to a $.getJSON callback method?

I know how to pass some parameters to a JQuery $.getJSON callback method, thanks to this question:
$.getJSON('/website/json',
{
action: "read",
record: "1"
},
function(data) {
// do something
});
And I can also submit a form to a $.getJSON callback method:
$.getJSON('/website/json', $(formName)
function(data) {
// do something
});
But I want to pass some parameters AND submit some form elements. How can I combine the two things togheter?
I could serialize the form elements and manually add some parameters to the url, and it looks like it works:
$.getJSON('/website/json',
'action=read&record=1&'
+ $(formName).serialize(),
function(data) {
// do something
});
But it doesn't look very elegant. Is this the proper way, or there's a better way to do it?
We could implement the functionality demonstrated in this answer as a custom jQuery instance method which produces an object of key/value pairs from a form and combines it with the properties that aren't derived from the form:
$.fn.formObject = function (obj) {
obj = obj || {};
$.each(this.serializeArray(), function (_, kv) {
obj[kv.name] = kv.value;
});
return obj;
};
$.getJSON('/website/json', $(formName).formObject({
action: "read",
record: "1"
}), function(data) {
// do something
});
Make an Ajax post to send the data to the server. Retrieve the parameter data in the backend code along with the form data.
var formData = {data from form};
formData.action = 'read';
formData.post = '1';
$.ajax({
url: '/website/json',
type: "post",
data: formData
}).done(function (data) {
// remove prior values set upon request response
formData.action = null;
formData.post = null;
});

Reusing 'data' passed in the jquery-ajax call

I'm using jquery's .ajax() method on a button click.
I wanted to know if there a way in whcih I can use the data that I passed in the data-part of the AJAX call in my success() function.
This is my code,
$.ajax({
url: //my URL here..
type: 'POST',
data:{
projDets : projDetailsArray,
},
datatype:'html',
error: function(){
alert('Error loading Project Information');
},
success: function(html){
//I wanted to re-use 'projDets' that I'm passing in the
//'data' part of my code..
}
});
Any help will be appreciated.
Thanks
You could wrap the $.ajax parameter in a closure, set up the "data" value as a local variable, and then reference it both for the "data" value and inside the "success" function:
$.ajax(function() {
var data = {
projDets: projDetailArray
// ...
};
return {
url: // your URL here..
type: 'POST',
data: data,
datatype:'html',
error: function(){
alert('Error loading Project Information');
},
success: function(html){
// just reference "data" here!
}
};
}());
Pritish - a quick and dirty way would be to store the json array in a jquery .data() object and then retrieve it as required.
1st, set the data: element to a named array:
// set 'outside' of the $ajax call
var projDetailsData = {projDets : projDetailsArray};
// now store it in a div data object
$("#targetDiv").data("myparams", projDetailsData);
// the data part of the $ajax call
data: projDetailsData,
to retrieve it again:
// get the value stored and call the $ajax method again with it
var projDetailsDataCopy = $("#targetDiv").data("myparams");
worth a try maybe!!
jim
[edit] - also, you could of course store the array in a module level vaiable -yuk!! :)

Categories

Resources