how can i get JSON object from controller in my view and use it in Jquery function? - json

i want to return JSON from my controller and get it in my view .this is my code, when i debug it . goes to my controller and get value but in my j query code nothing happen .when i debug my j query code by firebug it dos not run the function(data). what is wrong in my code ?i want get object of part-booklet from server. its a row of data and add this row to my Telerik mvc grid .thanks in advance
its my contoroller code:
#region dynamic_add_row_to_grid
private PartBooklet GetPartBooklet( int sparepart ) {
return _PartBookletService.GetList().Where(m => m.SparePartCode == sparepart).FirstOrDefault();
}
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult GetItems( int sparepart ) {
var PartbookletList = this.GetPartBooklet(sparepart);
return Json(PartbookletList, JsonRequestBehavior.AllowGet);
}
#endregion
and its jquery code:
$("#btnadd").button().click( function () {
alert("button");
var sparepartcode = $("#SparePartCode").val();
alert( sparepartcode );
$.getJSON("../Shared/GetItems", { sparepart: sparepartcode }, function( data ) {
alert( data.val );
alert("PartbookletList");
var grid = $('#InvoiceItemGrid').data('tGrid');
grid.dataBind( data );
}).error( function () {
alert("JSON call failed");
});
$( function () {
$.ajaxSetup({
error: function (jqXHR, exception) {
if ( jqXHR.status === 0 ) {
alert('Not connect.\n Verify Network.');
} else if ( jqXHR.status == 404 ) {
alert('Requested page not found. [404]');
} else if ( jqXHR.status == 500 ) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror' ) {
alert('Requested JSON parse failed.');
} else if ( exception === 'timeout' ) {
alert('Time out error.');
} else if ( exception === 'abort' ) {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
});

$("#btnadd").button().click( function () {
//alert("button");
var sparepartcode = $("#SparePartCode").val();
$.ajax({
url: "/Shared/GetItem?sparepart=" + sparepartcode,
type: 'GET',
success: function(a, b, data) {
//alert( data.val );
alert("PartbookletList");
var grid = $('#InvoiceItemGrid').data('tGrid');
grid.dataBind( data );
},
error: function(jqXHR, textStatus, errorThrown) {
alert("JSON call failed");
},
// other options and setup ...
});
});
Note that in a successful ajax request, it's the 3rd parameter that contains the actual data you need.

Related

How to pass json data to webix text

Good day, i'm new to webix and codeigniter, i wanna ask if after getting the json from controller the format is like {End_date: "2019-07-31", value: "2019-07-31"} in console log, how to display on webix text?
function GetEndDate() {
return $.ajax('<?php echo base_url(); ?
>index.php/date/dateController/GetEndDate/' + Id);
}
webix.ready(function(){
$.when(GetEndDate()).done(function(EndDates){
EndDate = EndDates[0];
rendersformSection();
});
});
function rendersformSection(){
{view:'text', id:'Final_date', name:'Final_date', labelAlign:
'right',label:'Final Date', labelWidth:200,
suggest: {
filter: function (item, value) {
if (item.value.toString().toLowerCase().indexOf(value.toLowerCase()) >= 0)
return true;
return false;
},
body: {
data: EndDate,
datatype: "json",
template: function(obj){
return obj.End_date;
}
}
},
on: {
onBeforeShow: function () {
var texts = [];
EndDate.forEach(function (obj) {
texts.push(obj.value);
});
}
}
webix.ui(rendersformSection);
}
I expect when the page load. the final date will show the date get from the function GetEndDate().

Stripe and back4app : Cannot read property 'id' of undefined

I'm trying to integrate payment in my app.
Here is the cloud code for Back4app :
var Stripe = require("stripe")(
"TestSecretKeyOk"
);
Parse.Cloud.define("purchaseItem", function(request, response) {
var item, order;
Parse.Promise.as().then(function() {
var itemQuery = new Parse.Query('Item');
itemQuery.equalTo('ItemName', request.params.itemName);
return itemQuery.first(null,{useMasterKey: true}).then(null, function(error) {
return Parse.Promise.error('Sorry, this item is no longer available.');
});
},{useMasterKey: true}).then(function(result) {
if (!result) {
return Parse.Promise.error('Sorry, this item is no longer available.');
} else if (result.get('quantityAvailable') <= 0) {
return Parse.Promise.error('Sorry, this item is out of stock.');
}
item = result;
item.increment('quantityAvailable', -1);
return item.save(null,{useMasterKey: true}).then(null, function(error) {
console.log('Decrementing quantity failed. Error: ' + error);
return Parse.Promise.error('An error has occurred. Your credit card was not charged.');
});
},{useMasterKey: true}).then(function(result) {
if (item.get('quantityAvailable') < 0) { // can be 0 if we took the last
return Parse.Promise.error('Sorry, this item is out of stock.');}
order = new Parse.Object("Order");
order.set('name', "azeaze"); //You can pass the client data from request.params at the begining
order.set('email', "a#gmail.com");
order.set('address', "NA");
order.set('zip', "99999");
order.set('city_state', "CA");
order.set('item', item.get('ItemName'));
order.set('fulfilled', false);
order.set('charged', false);
return order.save(null,{useMasterKey:true}).then(null, function(error) {
return Parse.Promise.error('An error has occurred. Your credit card was not charged.');
});
},{useMasterKey:true}).then(function(order) {
return Stripe.charges.create({
amount: item.get('price')*100, // It needs to convert to cents
currency: "usd",
source: request.params.cardToken,
description: "Charge for dominwong4#gmail.com"
}, function(err, charge) {
// asynchronously called
console.log(charge.id);
});
},{useMasterKey:true}).then(function(purchase) {
order.set('stripePaymentId', purchase.id);
order.set('charged', true);
order.save(null,{useMasterKey:true});
},{useMasterKey:true}).then(function() {
//your email logic
},{useMasterKey:true}).then(function() {
response.success('Success');
}, function(error) {
response.error('erreur trouvé ' + error);
});
});
Everything seems working fine :
-Stripe telling me payment is ok in their backend and no error .
But even if Parse Dashboard implement the order
StripePaymentID still null and this error raising :
TypeError: Cannot read property 'id' of undefined
So i don't understand what's not working , if you can help , i would be gratefull.
I recommend you update your Stripe Version. Just need to upload a file, with the name: "package.json" and insert the content like the structure below:
{
"dependencies": {
"stripe": "^5.8.0"
}

Ajax Internal Server Error in Yii2

View urlCreate code
$ajaxSaveTestGrid = Yii::$app->urlManager->createUrl('testgrid/ajaxsave');
This Is My View Ajax Code
function saveRow(id, index) {
if(id == 'tbl_testGrid') {
save(id, index);
}
}
function save(id, index) {
var testGrid_name = $('#testGrid_name' + index).val();
var testGrid_qty = $('#testGrid_qty' + index).val();
var testGrid_price = $('#testGrid_price' + index).val();
var url = '$ajaxSaveTestGrid';
// alert(testGrid_name+testGrid_qty+testGrid_price);
$.ajax({
type: 'GET',
url: url,
data: {
testGrid_name:testGrid_name,
testGrid_qty:testGrid_qty,
testGrid_price:testGrid_price
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
if(response == 'error') {
alert('Fail to save! Please try again');
} else {
$('#testGrid_name' + index).attr(\"disabled\",true);
$('#testGrid_qty' + index).attr(\"disabled\",true);
$('#testGrid_price' + index).attr(\"disabled\", true);
$('#testGrid_save_button' + index).attr(\"class\", \"hidden\");
$('#testGrid_delete_button' + index).attr(\"class\", \"hidden\");
$('#testGrid_edit_button' + index).attr(\"class\", \"show\");
$('#hid_testGrid_id' + index).val(response[0].testgrid.id);
$('html,body').animate({scrollTop: $('#btn_testGrid').offset().top});
}
}
});
}
This is my Controller
public function actionAjaxsave() {
$result = array();
$testGrid_name = $_GET['testGrid_name'];
$testGrid_qty = $_GET['testGrid_qty'];
$testGrid_price = $_GET['testGrid_price'];
$model = new Testgrid();
$model->name = $testGrid_name;
$model->price = $testGrid_price;
$model->qty = $testGrid_qty;
if ($model->save()) {
array_push($result, ['testgrid' => $model]);
$result = Json::encode($result);
echo $result;
} else {
echo 'error';
}
}
It occurring Internal Server Error
I want to save json Data to model.
Internal Server Error means that your code has fatal errors and error displaying is turned off. If you want to see the error itself, you must enable error displaying.
Check out the following question with its answers: How do I get PHP errors to display?
After you see the error, you can fix it.
PS:
$testGrid_name = $_GET['testGrid_name'];
This is not a recommended way to access GET variables. Use Yii::$app->request->get('testGrid_name') instead

How to Insert Data Into Database Table Using jQuery in ASP.Net MVC4

im working on ASP.NET MVC 4 project. well i already insert data into a SQL Server database using jQuery using a post method in .
Now im trying to insert data into 2 tables using the same view, my problem is that i can't passing multiple POST parameters to Web API Controller Method. here is my js function and my controller code, ill apreciate your help
var add_ClientPreste = function () {
var dataContrat = {
REFCONTRAT : 'mc1' ,
DATECREATION : '2016-05-23',
DATEFINCONTRAT : '2016-05-23'
};
var dataClient = {
C_IDCLIENTGROUPE : 11 ,
C_IDLOCALITE:332,
DATECREATION : '2016-05-23',
DATEMODIFICATION : '2016-05-23',
CODECLIENTPAYEUR : '999999999' ,
NOMCLIENTPAYEUR : 'morad'
};
$.ajax({
type: 'POST',
url: 'add_ClientPayeurContrat',
dataType: 'json',
data:{dataClient},
success: function (data) {
if(data==0) {
alert("enregistrement avec success : " );
}
else {
alert("error : "+ data );
}
},
error : function(data1) {
alert("aaaaaaaaaaaaaa " +data1);
}
});
}
$('#btntest').on('click', function () {
add_ClientPreste();
});
$('#btntest').on('click', function () {
add_ClientPreste();
});
Controller code
[HttpPost]
public ActionResult add_ClientPayeurContrat(SIG_CLIENTPAYEUR dataClient, SIG_CONTRAT dataContrat)
{
string msg = "";
try
{
ModSigma1.SIG_CLIENTPAYEUR.Add(dataClient);
ModSigma1.SIG_CONTRAT.Add(dataContrat);
ModSigma1.SaveChanges();
msg = "0";
}
catch (Exception ex)
{
msg = ex.Message;
}
return new JsonResult { Data = msg, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
var add_ClientPreste = function () {
var dataContrat = {
REFCONTRAT : 'mc1' ,
DATECREATION : '2016-05-23',
DATEFINCONTRAT : '2016-05-23'
};
var dataClient = {
C_IDCLIENTGROUPE : 11 ,
C_IDLOCALITE:332,
DATECREATION : '2016-05-23',
DATEMODIFICATION : '2016-05-23',
CODECLIENTPAYEUR : '999999999' ,
NOMCLIENTPAYEUR : 'morad'
};
$.ajax({
type: 'POST',
url: 'add_ClientPayeurContrat',
dataType: 'json',
data:{dataClient: dataClient},
success: function (data) {
if(data==0){
alert("enregistrement avec success : " );
}
else {
alert("error : "+ data );
}
},
error : function(data1){
alert("aaaaaaaaaaaaaa " +data1);
}
});
}
$('#btntest').on('click', function () {
add_ClientPreste();
});
$('#btntest').on('click', function () {
add_ClientPreste();
});
//controller code
[HttpPost]
public ActionResult add_ClientPayeurContrat(SIG_CLIENTPAYEUR dataClient, SIG_CONTRAT dataContrat)
{
string msg = "";
try
{
ModSigma1.SIG_CLIENTPAYEUR.Add(dataClient);
ModSigma1.SIG_CONTRAT.Add(dataContrat);
ModSigma1.SaveChanges();
msg = "0";
}
catch (Exception ex)
{
msg = ex.Message;
}
return new JsonResult { Data = msg, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
you did not add dataClient: dataClient in ajax.
so please add this.
Hope this will help you.

AngularJS + Parse REST API - Paging through more than 1,000 results

Im using Parse REST API + AngularJS and Im trying to be able to get more than 1000 items per query. I try to develop a recursive function and concatenate each query until I get all the data. My problem is that I am not able to concatenate the JSON objects successfully. Here is what I have:
$scope.getAllItems = function(queryLimit, querySkip, query) {
$http({method : 'GET',
url : 'https://api.parse.com/1/classes/myClass',
headers: { 'X-Parse-Application-Id':'XXX','X-Parse-REST-API-Key':'YYY'},
params: {limit:queryLimit, skip:querySkip},
}).success(function(data, status) {
query.concat(data.results);
if(query.lenth == queryLimit) {
querySkip += queryLimit;
queryLimit += 100;
$scope.getAllItems(queryLimit, querySkip, query);
} else {
$scope.clients = query;
}
})
.error(function(data, status) {
alert("Error");
});
};
var myQuery = angular.toJson([]); //Am I creating an empty JSON Obj?
$scope.getAllItems(100,0, myQuery);
Is there any better solution to achieve this?
There may be better, more concise ideas available, but this is what I worked out for myself.
In my service ...
fetch : function(page, perpage) {
var query = // build the query
// the whole answer to your question might be this line:
query.limit(perpage).skip(page*perpage);
return query.find();
},
fetchCount : function() {
var query = // build the same query as above
return query.count();
},
In the controller...
$scope.page = 0; // the page we're on
$scope.perpage = 30; // objects per page
MyService.fetchCount().then(function(count) {
var pagesCount = Math.ceil(count / $scope.perpage);
$scope.pages = [];
// pages is just an array of ints to give the view page number buttons
for (var i=0; i<pagesCount; i++) { $scope.pages.push(i); }
fetch();
});
function fetch() {
return MyService.fetch($scope.page, $scope.perpage)).then(function(results) {
$scope.results = results;
});
}
// functions to do page navigation
$scope.nextPage = function() {
$scope.page += 1;
fetch();
};
$scope.prevPage = function() {
$scope.page -= 1;
fetch();
};
$scope.selectedPage = function(p) {
$scope.page = p;
fetch();
};
Then paging buttons and results in my view (bootstrap.css)...
<ul class="pagination">
<li ng-click="prevPage()" ng-class="(page==0)? 'disabled' : ''"><a>«</a></li>
<li ng-repeat="p in pages" ng-click="selectedPage(p)" ng-class="(page==$index)? 'active' : ''"><a>{{p+1}}</a></li>
<li ng-click="nextPage()" ng-class="(page>=pages.length-1)? 'disabled' : ''"><a>»</a></li>
</ul>
<ul><li ng-repeat="result in results"> ... </li></ul>
I fixed my recursive function and now its working. Here it is:
$scope.getAllItems = function(queryLimit, querySkip, query, first) {
$http({method : 'GET',
url : 'https://api.parse.com/1/classes/myClass',
headers: { 'X-Parse-Application-Id':'XXX','X-Parse-REST-API-Key':'YYY'},
params: {limit:queryLimit, skip:querySkip},
}).success(function(data, status) {
if(first) {
query = data.results;
first = !first;
if(query.length == queryLimit) {
querySkip += queryLimit;
$scope.getAllItems(queryLimit, querySkip, query, first);
} else {
$scope.clients = query;
}
} else {
var newQ = data.results;
for (var i = 0 ; i < newQ.length ; i++) {
query.push(newQ[i]);
}
if(query.length == queryLimit + querySkip) {
querySkip += queryLimit;
$scope.getAllItems(queryLimit, querySkip, query, first);
} else {
$scope.clients = query;
}
}
})
.error(function(data, status) {
alert("Error");
});
};
Simply pushed each element to my empty array, also I was mutating queryLimit instead of querySkip in order to iterate through all the elements.