I'm using bootstrap-table with inline editable plugin to create a bootstrap table for a list of laptop. My goal was to apply changes to my csv file after users make changes to the table like this example (Product Category: Laptop)
I have created a javascript function below to send Ajax data to my Django server.
// ajax to server
$(function () {
$( "#table" ).on("click" , 'button',function(event){
var selected_item = getSelectedRow(); //this will return selected row object
console.log(selected_item);
$.ajax({
type: "post",
url: '/update/',
data: {
'item': JSON.stringify(selected_item)
},
success: function (data) {
alert('success');
}
});
});
});
Below is the output from my console log
(pcategory has been changed to Laptop2)
However, when I try to get the data from Django. It gave me the output below, which (pcategory was not changed to Laptop2)
{'webcam': 'WebCam', 'lannum': '2', 'condition': 'Refurbished', 'video2': 'GM204M [GeForce GTX 970M]', 'memorybanks': '8G 2133MHz/8G 2133MHz/', 'cpus': '1', 'customernotes': '', 'lanmodels': 'Killer E2400 Gigabit Ethernet Controller/WLAN QCA6174 802.11ac Wireless Network Adapter/', 'internalnotes': '', 'pline': 'Alienware', 'sku': 'LEN-LT-TPEdge-03BV001', 'cddvd': '', 'hddcapacity': '0.0G', 'coresthreads': '4 | 8', 'sound': 'Sound-Yes', 'pmodel': '15 R2', 'resolution': '1230x1000', 'ptype': 'Minitower', 'grade': 'GradeB:R2-Ready for Resale', 'touchscreen': 'Yes', 'hddqty': '0', 'pcategory': 'Laptop', 'processor': 'i7-6700HQ 2.60GHz', 'memory': '16G', 'serialnum': 'BFYNM72', 'video1': 'GM204M [GeForce GTX 970M]', 'hddmodels': '', 'manufacturer': 'Alienware', 'motherboard': 'Alienware 15 R2', 'batch': '03BV', 'hddserialnum': ''}
My Django view function:
#csrf_exempt
def update_page(request):
file_path = os.path.join(CSV_BASE_DIR, CURRENT_BATCH, '{}.csv'.format(CURRENT_BATCH))
if request.method == 'POST':
item = json.loads(request.POST.get('item'))
pprint.pprint(item)
overwrite_csv(file_path,item)
else:
print('no data back!')
return HttpResponse('yes')
I noticed when I changed the input again. The value will get changed to laptop2. It seems like it didn't save the value in the way I expect it to be. I'm wondering is there any way my Django server would get the same value as soon as I click on the check mark?
Thank you all in advanced.
Make sure the data source is Same for both listing and updating.
Related
I would like to know if it will be possible to send HTML (containing multiple charts) via an AJAX method and then render them. I don't seem to have much luck and I can't find much online doing it with this approach. I would appreciate any input.
Here is my AJAX function:
$.ajax({
url: "/admin/expensereport/getgraphs",
type: 'GET',
data: { dateFrom: $("#dateFrom").val(), dateTo:$("#dateTo").val(),
expenseBuildingType: $("input[name='expenseBuildingType']:checked").val(),
expenseScheduledType: $("input[name='expenseScheduledType']:checked").val()},
cache: false,
success: function(data) {
$('#graphsDiv').html(data);
},
Here is my PHP Laravel function with one of 3 graphs included:
$chartCategories = app()->chartjs
->name('chartCategories')
->type('pie')
->size(['width' => 400, 'height' => 200])
->labels(['Label x', 'Label y'])
->datasets([
[
'backgroundColor' => ['#FF6384', '#36A2EB'],
'hoverBackgroundColor' => ['#FF6384', '#36A2EB'],
'data' => [69, 59]
]
])
->options([]);
$view = View::make('partials.CPM.expensereportgraphs', [
'chartCategories' => $chartCategories,
]);
Here is an extract of my view:
<div class="col-md-6">
<h4>Top 10 Categories</h4>
{!! $chartCategories->render() !!}
</div>
I managed to solve the problem by taking another route. I created the charts in the html page file and then sent the data via AJAX. I suppose this method is actually much better.
In my Ui5 app I have added CREATE operation using oData. But when i am trying to create entry it is getting added in backend but in table it is showing NO DATA (refer image 1). but when I refresh the same page it is there (refer image 2). With single entry ,it is automatically getting refreshed
problem is with Multiple entries.
Please refer the screenshot and code for clear view.
After Clicking CREATE button:
After Refreshing WebPage:
onCreate: function() {
var oModel = this.getView().getModel();
var contactEntry1 = {
ProductID: 'KT-1960',
TypeCode: 'AD',
SupplierID: '0100000001',
TaxTarifCode: 1,
Category: 'Notebooks',
MeasureUnit: 'EA',
CurrencyCode: 'EUR',
Name: 'Urvish',
Description: 'First batch entry',
},
contactEntry2 = {
ProductID: 'KT-1982',
TypeCode: 'AD',
SupplierID: '0100000001',
TaxTarifCode: 1,
Category: 'Notebooks',
MeasureUnit: 'EA',
CurrencyCode: 'EUR',
Name: 'Urvish',
Description: 'Second batch entry',
};
oModel.setUseBatch(true);
oModel.create('/ProductSet', contactEntry1);
oModel.create('/ProductSet', contactEntry2);
oModel.refresh(true);
},
Looks like that you use the asynchronous operation for create but think that they are synchronous.
In order to fix this out, you can send these 2 create in one $batch request, but use the createEntry method of ODataModel, in order to use the submitChanges method, the callback of which, will be called once two of items are successfully created on the backend side (the below code example should be relevant for v2.ODataModel):
var oTableItemsBinding = oTable.getBinding("items");
// define the group ID, which will be used later on
var aCurrentDeferredGroups = oModel.getDeferredGroups();
oModel.setDeferredGroups(aCurrentDeferredGroups.concat("createProductGroup"));
// create two entries one by one, specifying the 'groupId' parameter
oModel.createEntry("/ProductSet", {
properties: contactEntry1,
groupId: "createProductGroup"
});
oModel.createEntry("/ProductSet", {
properties: contactEntry2,
groupId: "createProductGroup"
});
// send 2 requests in one $batch, passing the name of the 'groupId'
oModel.submitChanges({
groupId: "createProductGroup",
success: function() {
// no need to call refresh() as the model already does it by default (See "refreshAfterChange")
}.bind(this)
});
If your service does not support $batch requests, then you can still use the create method, but make use of it's success callback to be sure that the entry has been persisted in the backend.
So I a using the node paypal-rest-sdk module and I'm trying to create a billing plan. Using the documentation here I made this JSON:
const billingPlanAttributes = {
name: 'Subscription',
description: 'Monthly subscription plan',
type: 'INFINITE',
payment_definitions: [{
name: 'Regular monthly infinite payments',
type: 'REGULAR',
frequency_interval: '1',
frequency: 'MONTH',
cycles: '0',
amount: {
currency: 'USD',
amount: '4.99',
},
}],
merchant_preferences: {
cancel_url: 'http://localhost:3000/subscribe/cancel',
return_url: 'http://localhost:3000/subscribe/return',
auto_bill_amount: 'YES',
},
};
But when using the paypal.billingPlan.create(... function I get the error 'MALFORMED_REQUEST', 'Incoming JSON request does not map to API request'. So I guess my JSON is not in the correct format or I'm missing something that is need.
The documentation has a charge_models key but it does not mention that it is required unlike other keys.
If you can point me in the right direction that would be great.
Edit: changed the return url and cancel url to include the full domain but still same error.
There could be more to this, but I noticed one thing wrong with your JSON. Remove commas for items last in a list. After 'amount' and 'merchant_preferences'. JSON is picky.
late answer, I know, but ran in exactly the same issue than you.
In the create function of the billing plan
public function create($apiContext = null, $restCall = null)
{
$payLoad = $this->toJSON();
$json = self::executeCall(
"/v1/payments/billing-plans/",
"POST",
$payLoad,
null,
$apiContext,
$restCall
);
$this->fromJson($json);
return $this;
}
I found out, that the toJSON method always returned false. Why the hell!?!
I did the same as you did and copied the complete sample code into my code. Then it worked as expected. Now I checked, what the difference was in to my code.
I realized, that I used an umlauts (ä,ü,ö) in the name and description of the billing plan. I changed the umlauts to
'ä' => 'ae',
'ö' => 'oe'
'ü' => 'ue'
Then it worked fine! Maybe someone else is running in this issue, too.
I am working on an ASP.NET MVC 4 app. In my app, I'm trying to replace my drop down lists with the Select 2 plugin. Currently, I'm having problems loading data from my ASP.NET MVC controller. My controller looks like this:
public class MyController : System.Web.Http.ApiController
{
[ResponseType(typeof(IEnumerable<MyItem>))]
public IHttpActionResult Get(string startsWith)
{
IEnumerable<MyItem> results = MyItem.LoadAll();
List<MyItem> temp = results.ToList<MyItem>();
var filtered = temp.Where(r => r.Name.ToLower().StartsWith(startsWith.ToLower());
return Ok(filtered);
}
}
When I set a breakpoint in this code, I notice that startsWith does not have a value The fact that the breakpoint is being hit means (I think) my url property below is set correct. However, I'm not sure why startsWith is not set. I'm calling it from Select 2 using the following JavaScript:
function formatItem(item) {
console.log(item);
}
function formatSelectedItem(item) {
console.log(item);
}
$('#mySelect').select2({
placeholder: 'Search for an item',
minimumInputLength: 3,
ajax: {
url: '/api/my',
dataType: 'jsonp',
quietMillis: 150,
data: function (term, page) {
return {
startsWith: term
};
},
results: function (data, page) {
return { results: data };
}
},
formatResult: formatItem,
formatSelection: formatSelectedItem
});
When this code runs, the only thing I see in the select 2 drop down list is Loading failed. However, I know my api is getting called. I can see in fiddler that a 200 is coming back. I can even see the JSON results, which look like this:
[
{"Id":1,"TypeId":2,"Name":"Test", "CreatedOn":"2013-07-20T15:10:31.67","CreatedBy":1},{"Id":2,"TypeId":2,"Name":"Another Item","CreatedOn":"2013-07-21T16:10:31.67","CreatedBy":1}
]
I do not understand why this isn't working.
From the documentation:
Select2 provides some shortcuts that make it easy to access local data
stored in an array...
... such an array must have "id" and "text" keys.
Your json object does not contain "id" or "text" keys :) This should work though i have not tested it:
results: function (data, page) {
return { results: data, id: 'Id', text: 'Name' }
}
There's further documentation following the link on alternative key binding... I believe thats where your problem lies.
Hopefully this helps.
I am trying to store an entry in a database after a click using an ajax call to a route that calls a controller function in javascript (in Laravel 4).
I have a resource "artists", that is controlled by an "ArtistsController". The view where I am making the call is called "show.blade.php" in an "artists" directory (i.e. the page shows different artists: artists/1, artists/2, etc...).
I also have a table called "fanartists", where I want to store this data. Basically, when a user clicks a button on a specific artist's page, I want the relationship to be stored in this table.
Here is the relevant code:
show.blade.php:
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '*****************',
status : true,
cookie : true,
oauth : true
//xfbml : true
});
$( '.opener' ).click(function() {
FB.ui({
method: 'feed',
link: 'http://crowdtest.dev:8888/artists/',
name: 'Hello',
caption: 'Hello',
description: 'Hello!'
});
request = $.ajax({
url: "/artists/fbclick",
type: "post",
data: serialised data
});
});
};
</script>
<a class="add-list-button-no-margin opener" style="color: white; font:14px / 14px 'DINMedium','Helvetica Neue',Helvetica,Arial,sans-serif;">Play my city</a>
ArtistsController:
public function fbclick($id) {
$artist = Artist::find($id);
$fanartist = new Fanartist;
$fanartist->artist_id = $artist->id; //the id of the current artist page (i.e. artists/1, id=1)
$fanartist->fan_id = Auth::user()->id;
$fanartist->save();
}
routes:
Route::get('/artists/fbclick', array('uses' => 'ArtistsController#fbclick'));
When I include the ajax request, the FB feed does not pop up. When I remove it, it does. Also, it is not storing the data in the database like I want it to.
Do you see anything wrong here? Your help is much appreciated. Thank you.
I see some slight mistakes in your script.
In your ajax request you are using post as the method, but you have defined your route as get so either change your route to post or change ajax method to get. I will go with post route so your new route is Route::post('/artists/fbclick', array('uses' => 'ArtistsController#fbclick')');
And ajax data field should be in json format, so now you ajax request will look some what like this
$.ajax({
url: "/artists/fbclick",
type: "post",
data: {field_name :'data'}
});
Finally coming to you controller function, with silght changes
public function fbclick() {
// $artist = Artist::find($id);
$id=Input::get('field_name'); //field_name is the field name from your Json data
$fanartist = new Fanartist;
$fanartist->artist_id = $id; //the id of the current artist page (i.e. artists/1, id=1)
$fanartist->fan_id = Auth::user()->id;
$fanartist->save();
}
Everything should work now