Pass the parameter only for non-empty variable in AJAX data - javascript

Here I want to do which are the variable not empty, I want to pass that variable one in data,in this case area is empty so I want pass the parameter for city and listing type, but I don't know how to do?
var city = "Karnadaka";
var area = "";
var listing type = "RENT";
$.ajax({
type: 'GET',
url: "http://www.domain.com/api/get/searchProperties",
data: {
area: area,
city: city,
listingType: listing_type
},
success: function(data) {
console.log(data);
}
});

you can use delete to remove the propery pair(s) in an Object
var city = "Karnadaka";
var area = "";
var listing_type = "RENT";
var data={
area: area,
city: city,
listingType: listing_type
}
for (k in data){
if(data[k]=="") delete data[k];
}
$.ajax({
type: 'GET',
url: "http://www.domain.com/api/get/searchProperties",
data: data,
success: function(data) {
console.log(data);
}
});

Try this:
var city = "Karnadaka";
var area = "";
var listing_type = "RENT";
var data = {};
if(city != '')
data['city'] = city;
if(area != '')
data['area'] = area;
if(listing_type != '')
data['listing_type'] = listing_type;
$.ajax({
type: 'GET',
url: "http://www.domain.com/api/get/searchProperties",
data: data,
success: function(response) {
console.log(response);
}
});

Related

JQuery TypeError: Converting circular structure to JSON in MVC

Facing error on JSON.stringify(ApplObj) :
How to post this object to controller
JQuery Code -
var ApplName = $("#ApplicantName").val();
var ApplMobile = $("#ApplicantMobile").val();
var ApplEmail = $("#ApplicantEmailId").val();
var ApplFHName = $("#ApplicantFHName").val();
var ApplObj = {
ApplicantName: ApplName, ApplicantMobile: ApplMobile, ApplicantEmailId: ApplEmail, ApplFHName: ApplicantFHName
}
$.ajax({
url: '#Url.Action("SaveApplicatDetail", "Dashboard")',
data: JSON.stringify(ApplObj),
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
}
});
Controller Code...
this jsonresult used for save records and return value...
this code is working in other project....
public JsonResult SaveApplicatDetail()
{
try
{
var resolveRequest = HttpContext.Request;
TicketMasterModel TMM = new TicketMasterModel();
resolveRequest.InputStream.Seek(0, SeekOrigin.Begin);
string jsonString = new StreamReader(resolveRequest.InputStream).ReadToEnd();
if (jsonString != null)
{
TMM = (TicketMasterModel)js.Deserialize(jsonString, typeof(TicketMasterModel));
}
int TicketId = 0;
using (var db = new UnitOfWork())
{
DAL.tbl_TrnTicketMaster TM = new DAL.tbl_TrnTicketMaster();
TM.ApplicantName = TMM.ApplicantName;
TM.ApplicantMobile = TMM.ApplicantMobile;
TM.ApplicantEmailId = TMM.ApplicantEmailId;
TM.ApplicantFHName = TMM.ApplicantFHName;
TM.FK_CompanyId = 1;
TM.CustomerId = UserSession.UserId;
TM.IsSubmissionLocked = false;
TM.CreatedBy = UserSession.UserId;
db.tbl_TrnTicketMaster.Insert(TM);
TicketId = TM.PK_TicketId;
}
return Json(TicketId, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
basically JSON.stringify turns a Javascript object into JSON text and stores that JSON text in a string.
try this,
var ApplName = $("#ApplicantName").val();
var ApplMobile = $("#ApplicantMobile").val();
var ApplEmail = $("#ApplicantEmailId").val();
var ApplFHName = $("#ApplicantFHName").val();
var ApplObj = {
'ApplicantName': ApplName, 'ApplicantMobile': ApplMobile, 'ApplicantEmailId': ApplEmail, 'ApplFHName': ApplicantFHName
}
$.ajax({
url: '#Url.Action("SaveApplicatDetail", "Dashboard")',
data: JSON.stringify(ApplObj),
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data);
}
});
Problem Resolved -
"JSON.stringify" is used array to convert it.
var ApplName = $("#ApplicantName").val();
var ApplMobile = $("#ApplicantMobile").val();
var ApplEmail = $("#ApplicantEmailId").val();
var ApplFHName = $("#ApplicantFHName").val();
var ApplDetails = {
ApplicantName: ApplName,
ApplicantMobile: ApplMobile,
ApplicantEmailId: ApplEmail,
ApplicantFHName: ApplFHName
}
var ApplObj = { ApplicantDetail: ApplDetails };
$.ajax({
url: '#Url.Action("SaveApplicatDetail", "Dashboard")',
data: JSON.stringify(ApplDetails),
dataType: 'json',
type: 'POST',
contentType: "application/json; charset=utf-8",
success: function (data) {
}
});

Keyup functionality defect in jquery

I have passed the value of textbox to ajax using keyup(). But on emptying the textbox it displays all the contents from the relative table. I want an empty page while the textbox is empty. Can anyone help me with this problem. The codes are:
$('.form-control').keyup(function () {
var name = $('#member_search').val();
var phone = $('#member_contact').val();
var father = $('#member_father').val();
$.ajax({
type: "post",
url: "search_result.php",
data: {
name: name,
contact: phone,
father: father
},
success: function (data) {
$('#result').html(data);
}
});
});
Just check whether any one has content else empty the result box
$('.form-control').keyup(function () {
var name = $('#member_search').val();
var phone = $('#member_contact').val();
var father = $('#member_father').val();
if (name || phone || father) {//use name && phone && father if you want to make sure all inputs has content
$.ajax({
type: "post",
url: "search_result.php",
data: {
name: name,
contact: phone,
father: father
},
success: function (data) {
$('#result').html(data);
}
});
} else {
$('#result').html('');
}
});

"Message":"Invalid object passed in (JSON data formatting issue)

I am trying to send json to my webmethod but its showing below error.
{"Message":"Invalid object passed in, \u0027:\u0027 or \u0027}\u0027 expected. (17): { \"mappingData
:\"\"[\"Ref No,0\",\"Date,0\",\"Amt,0\",\"Sender Name,0\",\"Sender Add,0\",\"Beneficiary Name,0\",\"Beneficiary
Add,0\",\"Phone,0\",\"Secret Code,0\",\"Secret Ans,0\",\"Preferred Id,0\"]\"}","StackTrace":" at System
.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeDictionary(Int32 depth)\r\n at System
.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System
.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit
, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize
(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n at System.Web.Script
.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services
.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer serializer)\r\n
at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData, HttpContext
context)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context,
WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}
My Javascript code is :
function tableToJson() {
var myArray = [];
$('.dataRow').each(function(){
var data= $(this);
var ColumnAlias= data.find('div.ColumnAlias p').html();
var TableNames=data.find('div.ddlTableNames select').val();
var mainData=ColumnAlias+','+TableNames;
myArray.push(mainData);
});
var json_text = JSON.stringify(myArray);
if (json_text!=null) {
$.ajax({
type: "POST",
url: "CorrespondentTemplate.aspx/SaveMappings",
data: '{ "mappingData:""'+json_text+'"}',
contentType: "application/json",
success: function (data) {
alert(data.d);
}
});
}
return false;
}
Please check this line, I don't know whats wrong with it
data: '{ "mappingData:""'+json_text+'"}',
Quotes are misplaced. Should be
data: '{ "mappingData":"'+json_text+'"}',
Or you can do this
data: JSON.stringify({ mappingData: myArray }),
I tried below way to resolve the above issue.
function tableToJson() {
var myArray = [];
$('.dataRow').each(function(){
var data= $(this);
var ColumnAlias= data.find('div.ColumnAlias p').html();
var TableNames=data.find('div.ddlTableNames select').val();
var mainData=ColumnAlias+','+TableNames;
myArray.push(mainData);
});
var json_text = JSON.stringify(myArray);
var jsonFormat={mappingData:json_text};
var jsonFormatInString=JSON.stringify(jsonFormat);
if (json_text!=null) {
$.ajax({
type: "POST",
url: "CorrespondentTemplate.aspx/SaveMappings",
data: jsonFormatInString,
contentType: "application/json",
success: function (data) {
alert(data.d);
}
});
}
return false;
}
These three lines done the job for me.
var json_text = JSON.stringify(myArray);
var jsonFormat={mappingData:json_text};
var jsonFormatInString=JSON.stringify(jsonFormat);

How to send multiple values using ajax to PHP

I'm trying to collect a Facebook user info and then sign them up. How do i include more than one value in ajax?
$.signuser = function () {
FB.api('/me', function (response) {
var str = "";
alert(response.name);
var fbfname = response.first_name;
var fblname = response.last_name;
var fblname = response.id;
var fblink = response.link;
var fbusername = response.username;
var fblink = response.email;
$.ajax({
type: "POST",
data: {
data: fbfname,
fblname
},
complete: function () {
//$('#booksloadjif').css('display','none')
},
url: "fbpost.php"
}).done(function (feedback) {
$('#fg').html(feedback)
});
});
}
You can pass multiple key / value pairs to PHP as an object in $.ajax
$.signuser = function () {
FB.api('/me', function (response) {
var data = { // create object
fbfname : response.first_name,
fblname : response.last_name,
fblname : response.id,
fblink : response.link,
fbusername : response.username,
fblink : response.email
}
$.ajax({
type: "POST",
data: data, // pass as data
url: "fbpost.php"
}).done(function (feedback) {
$('#fg').html(feedback)
}).always(function() {
$('#booksloadjif').css('display','none')
});
});
}
and you'd access them in PHP with
$_POST['fbfname']
$_POST['fblname']
etc, i.e. the keynames in javascript are also the key names for the $_POST array

Saving javascript objects using jquery and passing an ID from database

I am using jQuery to save the values of my javascript objects. I need to retreive the ID of inserted object from the database. I know how to do it, if the Save function is within the javascript object (see code below). But how can I set the ID variable, if the Save function is not in the javascript object?
Working:
Person = function() {
var self = this;
self.ID;
self.Name;
self.SurName;
self.Save = function() {
$.ajax({
type: "POST",
url: "Save",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ Name: self.Name, SurnName: self.SurName }),
dataType: "json",
success: function (result) {
var ID = result.d.ID; //this is the ID retreived from database
self.ID = ID; //set the ID, it works, since I can reference to self
}
});
};
}ยจ
So how would I now implement a function (outside the Person class!) like:
SavePerson = function(p) {
$.ajax({
type: "POST",
url: "Save",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ Name: p.Name, SurnName: p.SurName }),
dataType: "json",
success: function (result) {
var ID = result.d.ID; //this is the ID retreived from database
p.ID = ID; //set the ID, it doesn't work, becouse if I call SavePerson repetedly for different objects, a p will not be a correct person.
}
});
};
Just to clarify, you would like the Person object id property to be updated with the recent save? If so the following script would suffice. I have used deferred's to ensure that p.ID is only updated upon completion of the asynchronous request.
$.Person = function() {
var self = this;
self.ID;
self.Name;
self.SurName;
}
$.SavePerson = function() {
var dfd = $.Deferred();
$.ajax({
type: "POST",
url: "Save",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ Name: p.Name, SurnName: p.SurName }),
dataType: "json",
success: dfd.resolve
});
return dfd.promise();
};
var p = new $.Person();
$.SavePerson().then(function(result){
p.ID = result.d.ID;
});
There may be better ways to do this but I'd have my database also return the Name and Surname along with the ID, then search my Person list to find the correct object in the success function.
Perhaps this is what you desire?
I borrowed some code here:
/*** makeClass() ***
* The following allows us to easily create
* Javascript classes. Source of this:
* http://ejohn.org/blog/simple-class-instantiation/
* makeClass - By John Resig (MIT Licensed)
*/
function makeClass() {
return function(args) {
if (this instanceof arguments.callee) {
if (typeof this.init == "function") this.init.apply(this, args.callee ? args : arguments);
} else return new arguments.callee(arguments);
};
});
/* set up ajax */
$.ajaxSetup({
async: false,
type: "POST",
contentType: "application/json",
converters: {
"json jsond": function(msg) {
return msg.hasOwnProperty('d') ? msg.d : msg;
}
},
data: '{}',
dataType: "json",
error: function(jqXHR, status, error) {
alert("An error occurred on the server. Please contact support.");
}
});
/* set up my person class */
var personClass = makeClass();
personClass.prototype.init = function() {
this.ID = '';
this.SurName = '';
this.Name = '';
}
/* create my save function */
personClass.prototype.SavePerson = function(p) {
this.Name = (typeof p === 'undefined') ? this.Name : p.Name;
this.SurName = (typeof p === 'undefined') ? this.SurName : p.SurName;
$.ajax({
url: "Save",
data: JSON.stringify({
Name: this.Name,
SurnName: this.SurName
}),
success: function(result) {
var ID = result.ID; //ID from database
this.ID = ID; //set the ID,
}
});
};
//create two persons
var person1 = personClass();
var person2 = personClass();
//set person1 to be fred
person1.Name = "Fred";
person1.SurName = "Flintstone";
// independent person
var p = {Name: "Barney", SurName: ""};
p.Surname = "Rubble";
//save specific and the independent (as person2)
person1.SavePerson();
person2.SavePerson(p);
//alert the ID of both
alert(person1.ID + ":" + person2.ID);

Categories