How to parse json string to integer ? (ajax) - json

i had problem with these codes.
<script>
$(function() {
$('#submitRegister').click(function (e) {
console.log('jalan fungsi submit');
e.preventDefault();
var paramObj = {};
$.each($('#registerForm').serializeArray(), function (_, kv) {
if (paramObj.hasOwnProperty(kv.name)) {
paramObj[kv.name] = $.makeArray(paramObj[kv.name]);
paramObj[kv.name].push(kv.value);
}
else {
paramObj[kv.name] = kv.value;
}
});
console.log(paramObj);
var dataMitra = paramObj;
var urlAjax = "my url";
$.ajax({
type: "POST",
url: urlAjax,
contentType: "application/json; charset=utf-8",
data: dataMitra,
crossDomain: true,
success: function (data) { alert("ajax worked"); },
error: function (data) { console.log(data); },
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("accept", "application/json");
},
headers: {
'Access-Control-Allow-Origin': '*'
}
});
});
});
am using ajax for post to my API, there are several fields that are required to use integers. looks json below
================================================
ada_lahan: "1" *
alamat_juragan: "jalan intan v no. 192"
alamat_lahan: ""
code: "10640" *
country_id: "100" *
email: "gecok123#gmail.com"
juragan: "arjuna"
juragan_refferal: "1" (it should be int)
juragan_stage: "arjuna"
kabupaten_id: "2" *
kecamatan_id: "2" *
kelurahan_id: "4" *
lahan_kabupaten_id: "Kota / Kab*"
latitude_juragan: "-6.1642709" *
longitude_juragan: "106.86704039999995" *
nama_juragan: "bram story"
provinsi_id: "27" *
telepon: "82312233332"
=================================================
note : * means should be integer value
how can i parse the string value to integer ? only for the several fields.
thanks

Related

How to perform an Ajax call from a partial view. Asp.net MVC

I want to perform an Ajax Call to get data from a form that is in a partial view, to a controller and get a response message back.
Ajax Call
$("#submitContactInfo").on("click", function () {
if ($('#contact-form').valid() === true) {
$.ajax({
url: '#Url.Action("SendEmailAsync", "Home")',
type: "Post",
data: {
"name": Name.value,
"lastName": LastName.value,
"email": Mail.value,
"phone": Mobile.value
},
dataType: "json",
success: function (result) {
if (result.value === "1") {
...
}
else {
...
}
}
});
}
});
My Controller
[HttpPost]
public async System.Threading.Tasks.Task<ActionResult> SendEmailAsync(string name, string lastname, string email, string phone)
{
var value = 0;
...
return Json(value, JsonRequestBehavior.AllowGet);
}
First thing I stumbled upon was that#Scripts{} does not work on partial views so I had to think of another way.
So I created an external file and named it 'custom.js' and referenced it on _Layout.chtml, below the:
#Scripts.Render("~/bundles/jquery")
#Scripts.Render("~/bundles/jqueryval")
...
#Scripts.Render("~/Scripts/custom.js")
The second thing I noticed was that the url from the Ajax Call was not working because I was using Razor syntax in an external js file.
So I changed url: '#Url.Action("SendEmailAsync", "Home")', to url: '/Home/SendEmailAsync',
After that I was getting a 500 error, so I figured that by changing type: "Post", to type: "Get", and dataType: "json", to dataType: "html", and by adding contentType: "application/json; charset=utf-8", I was a little closer because I was getting a 404 error.
So I went to my Controller method and removed [HTTPPOST] and that was it.
Final Ajax Call:
$("#submitContactInfo").on("click", function () {
if ($('#contact-form').valid() === true) {
$.ajax({
url: '/Home/SendEmailAsync',
type: "GET",
data: {
"name": Name.value,
"lastName": LastName.value,
"email": Mail.value,
"phone": Mobile.value
},
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (result) {
if (result === "1") {
...
}
else {
...
}
}
});
}
});
My Controller
public async System.Threading.Tasks.Task<ActionResult> SendEmailAsync(string name, string lastname, string email, string phone)
{
var value = 0;
...
return Json(value, JsonRequestBehavior.AllowGet);
}
If you have a better solution or any remarks to make, feel free. I'm open to suggestions.

How to pass a variable in button id and then send that id to ajax data?

I am passing id of the product to button id and then through Ajax data, I'm sending that product id to the controller
for(var i=0;i<productsJSON.length;i++)
{
var td5 = document.createElement('td');
td5.innerHTML = "<br><button type='button' id="+product.id+"onclick='Addtocart() ' >Add To Cart</button><br>";
}
function Addtocart() {
var quantity = document.getElementsByName("quantity").item(0).value;
$.ajax({
type: "POST",
data: 'pid=' + this.id + '&quantity=' + quantity,
url: "ProductController",
success: function(content) {
console.log(content);
alert('done');
}
});
}
You have to use a JSON object.
Here I set data from an HTML form using the GET method.
$.ajax(
{
type: "GET",
data: $("#form").serialize(),
url: "url",
success: function(data)
{
# Code
},
error: function()
{
# Code
}
}
);

Call JSON method in asp.net mvc without page refresh?

Here is my JSON method in controller
public JsonResult GetNotificationForAll()
{
Int64 userid = Convert.ToInt64(Session["UserID"]);
string searchcriteria = string.Format("N.notificationfor ={0}", 1);
PODService.Notification[] notification = service.GetNotificationBySearchCriteria(searchcriteria);
return Json(notification, JsonRequestBehavior.AllowGet);
}
Here is my script code for JSON method:
var URL6 = "/Home/GetNotificationForAll";
$.getJSON(URL6, "", function (data) {
var x = { "padding-left": "10px" };
$.each(data, function (index, value) {
$("<td>"
+ value["Notification_Name"]
+ "</td>")
.appendTo("#Allnotification").css(x);
});
});
Here is my view:
<div id="Allnotification" style="color:White;float:left;margin-left:10px"> </div>
I want to show data without page refresh.
i have found the solution.
function NotificationForALL() {
$("#Allnotification").empty();
$.ajax({
type: "GET",
url: "#Url.Action("GetNotificationForAll", "Home")",
dataType: "json",
cache: false,
success: function (data) {
$.each(data, function(index, element) {
var x = { "padding-left": "10px" };
$("<td>"
+ element["Notification_Name"]
+ "</td>") .appendTo("#Allnotification").css(x);
});
setTimeout(function(){NotificationForALL();}, 900000);
}
});
}
NotificationForALL();
Hope it will help to someone

jqPlot and JSON formatted Data

I'm returning a JSON string with an Ajax call in jQuery, I'd like to pump that data into a bar chart using jqPlot.
I got the JSON conversion code from another Stack-Overflow post, but can't understand why this isn't working. My code:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(DTO), //JSON.stringify(AnDParms), combined,
url: "GetAdmitsDischarges.asmx/GetAandD",
dataType: "json",
success: function (data) {
//do chart stuff here.
var line1 = [];
for (var prop_name in data.d) {
line1.push([prop_name, data[prop_name]])
}
var ticks = ['Admits', 'Discharges'];
var plot1 = $.jqplot('chartdiv', [line1], {
title: 'Admits & Discharges',
series: [{ renderer: $.jqplot.BarRenderer}],
axesDefaults: {
tickRenderer: $.jqplot.CanvasAxisTickRenderer
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer
}
}
});
//to prove the flow is working...
//alert("Data: " + data.d);
}, //end of success
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ' ' + errorThrown + ' ' + XMLHttpRequest);
} //end of error
}); //end of ajax call
In Firebug, the value of line1 is (going from 0 to 32):
[["0", undefined],["1", undefined],...["31", undefined],["32",
undefined]]
While the value of data is:
Object { d="{"Admits":"35","Discharges":"36"}" }
Thanks for any help you can offer...
The problem is your JSON structure:
{
"Admits": "35",
"Discharges": "36"
}
You are providing a JSON object, but jqplot needs array instead:
[
["Admits", 35],
["Discharges", 36]
]
I finally figured it out with the help of Dave Ward of Encosia.com...if you've not checked out his blog, head straight there right now...it's great for all your .Net/jQuery needs.
Here is my javascript:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(DTO),
url: "GetAdmitsDischarges.asmx/GetAandD",
dataType: "json",
success: function (data) {
var jqPlotData = $.map(data.d, function (value, key) {
if (key != "__type") {
return [value]; //was key, value
}
});
var ticks = ['Admits', 'Discharges'];
var plot1 = $.jqplot('chartdiv', [jqPlotData], {
title: 'Admits & Discharges',
seriesDefaults: {
renderer: $.jqplot.BarRenderer,
rendererOptions: { varyBarColor: true },
pointLabels: { show: true }
},
axes: {
xaxis: {
renderer: $.jqplot.CategoryAxisRenderer,
ticks: ticks
}
},
highlighter: { show: false }
});
Also, I removed the JSON serialization from my web service, and just returned the object. Hopefully this will help others.

ajax json output parsing in jquerymobile

public function actionajaxSearch() {
$data_fetched=Person::model()->findByAttributes (array('Code'=>'Cust0001'));
echo CJSON::encode($data_fetched); }
$('#searchResult').live('pageshow', function(e,info)
{
$.post('?r=mobile/ajaxSearch',$('form').serialize(),
function(res)
{
arrayvalue =res;
$.each(arrayvalue, function(i, profile) {
alert(i);
alert(profile);
});
}
});
I am getting the output as json encode one.
In traversing alert i am getting the value each character not by key or value.
Any help?
Adding the datatype and contenttype solved the problem. Added the complete code for other's ref.
public function actionajaxSearch() {
$data_fetched=Person::model()->findByAttributes (array('Code'=>'Cust0001'));
echo CJSON::encode($data_fetched); }
$('#searchResult').live('pageshow', function(e,info)
{
$.ajax({
beforeSend: function() { $.mobile.showPageLoadingMsg(); },
complete: function() { $.mobile.hidePageLoadingMsg() },
url: '?r=mobile/ajaxSearch',
data: $('form').serialize(),
type: 'POST',
ContentType: "application/json",
dataType: "json",
success:function(res) {
if(res !='')
{
$.each(res, function(key, value) {
var li='<li>'+value['Code']+'</li>';
$("#mylist").append(li); //append li to ul of id list
}); //eachfunction
$('#mylist').listview();
$('#mylist').listview('refresh');
}//sucess
});