Datatable from server json object - javascript

I submitted a form data to a backend Flask application as ajax post request. Backend process uses data to query database then returns json object back to Ajax. How to construct datatable from this json object?
My Ajax post request:
$(document).ready(function() {
$("#submit").click(function(event) {
$.ajax({
type: 'POST',
url: '/process',
data: $('#myform').serialize(),
success: function(response) {
//response looks like this:
//[{"country": "USA", "code": "1007-01" },{"country": "UK", "code": "1100-04" }]
}
});
event.preventDefault();
});
});
My flask application
#app.route('/process', methods=["POST"])
def process():
if request.method == 'POST':
country = request.form['id'].encode("utf-8")
#query database and store result in dict
result = query_database(country)
return jsonify(result)

Initialize your datatable with your ajax call as datasource
let datatable = $('#my-table').DataTable({
ajax: {
url: '/process',
method: 'POST',
data: {
$('#myform').serialize()
}
}
});
now you just need to format your response like this
{
data:[/*your Data*/]
}

Related

Passing a complex model to controller using AJAX in ASP.NET Core MVC

I'm trying to pass the model from the view to controller using AJAX, the AJAX call works with a hard-coded JSON string but fails with the actual JSON and I don't know why, any help is very appreciated. Step by step this is what I did:
In the view I have
<script>
var FeedData = #Html.Raw(Json.Serialize(Model));
</script>
In My JavaScript file
var index= $(this).val();
var test = window.FeedData[index];
var json = {
prop1: 'test',
prop2: 'test2',
};
var data = {
json: JSON.stringify(json)
};
var data2 = {
json: JSON.stringify(test)
};
$.ajax({
type: 'GET',
dataType: 'json',
url: "/Feed/GetFeedDetails",
data: data,
success: function (json) {
if (json) {
alert('ok');
} else {
alert('failed');
}
},
});
Ok, Both data and data2 variables are JSON stringified..
data: data, // Works
data: data2,//this does not work
My Controller
public async Task<PartialViewResult> GetFeedDetails(string json)
{
Feed feedData = JsonConvert.DeserializeObject<Feed>(json);
return PartialView("FeedDetailsModal", feedData );
}
Any help is much appreciated.
the AJAX call works with a hard-coded JSON string but fails with the actual JSON and I don't know why
In your code, we can find that you set Ajax request method to 'GET', so the data would be passed through query string, if you can not get expected data in action method, please use browser developer tools Network tool to capture request and check if well-formatted data is passed.
Besides, your action method accepts string-type parameter and manually convert to a Feed object, to achieve same, you can try to make action method accept Feed type parameter and make it automatically bind value to properties of model class via model binding feature.
public IActionResult GetFeedDetails([FromBody]Feed feed)
{
//...
Pass complex data through request body instead of in query string, like below.
var data2 = window.FeedData[index];
$.ajax({
type: 'Post',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
url: "/Feed/GetFeedDetails",
data: JSON.stringify(data2),
success: function (json) {
if (json) {
alert('ok');
} else {
alert('failed');
}
},
});
Test Result

Posting JSON to Django views with AJAX

I am trying to post a JSON object from my client side Javascript to my Django View.
I receive a "500 (Internal Server Error)" When attempting to Post. Does this have to do with the CSRF token? And how can I get around this?
My AJAX
$.ajax({
type: 'POST',
dataType: 'json',
url: '/demo/saved/',
data: {'data': JSON.stringify(finalSelection)},
success: function() {
console.log("Success")
}
});
views.py
def show(request):
data = json.loads(request.POST.get('data', ''))
context = {
'data': data
}
return render(request, 'bill/saved.html', context )
urls.py
urlpatterns = [
path('bill/', views.bill_view, name = 'bill-view'),
path('saved/', views.show, name = 'selected-view'),
]
Appreciate any help!
Assuming its really the CSRF problem you mentioned, since you didn't post the 500 error output, you can simply add the csrf token to your data that is sent in POST request:
$.ajax({
...
data: {
'data': JSON.stringify(finalSelection),
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
...
});

How to solve JSONdecode error in ajax django?

I'm receiving JSONdecode error when sending the POST request from ajax to django views.py. The POST sends an array of json. The data from this POST will be used to create the model. Appreciate for any hints.
Error:
Exception Type: JSONDecodeError at /order-confirmation
Exception Value: Expecting value: line 1 column 1 (char 0)
Request information:
USER: ledi12
GET: No GET data
POST: No POST data
FILES: No FILES data
AJAX Request:
var new_array = JSON.stringify(array)
$.ajax({
url: 'http://localhost:8000/order-confirmation',
type: 'POST',
data: '{"array":"' + new_array+'"}',
processData: false,
contentType: "application/json",
dataType: "json",
headers: {"X-CSRFToken":'{{ csrf_token }}'},
success: function (result) {
console.log(result.d);
},
error: function (result) {
console.log(result);
}
});
Views:
#csrf_exempt
def order_confirmation(request):
if request.method == 'POST':
data = json.loads(r"request.body").read()
print(data)
return HttpResponse(status=200)
else:
return render(request, 'main_templates/order_confirmation.html')
The reason you are getting this error is because the JSON library is not able to properly compile the string. There are a couple of things that your code needs to change. Remove 'r' character which is near request.body(). There is no need for 'read()' function in json.loads(). You can preprocess your array into a string and once done, and pass it to ajax. The data field will only have the string. So the ajax code field should look like
data: new_array

Ajax request to Django returns 404 not found

I am writing my first project in Django where I now want to make an Ajax request using jQuery to get some data. The problem is that the Ajax request returns:
GET http://localhost:8000/ajax/teams_for_issue/?medIssue=MI6 404 (Not Found)
I am rather certain that the problem is with the URL, and I have gotten the URLs wrong several times before in this project. My Ajax code looks as follows:
var medIssue = _this.issueSelector.val();
$.ajax({
url: '/ajax/teams_for_issue/',
data: {
'medIssue': medIssue
},
dataType: 'json',
success: function(data) {
_this.setTeams(data.teams)
}
});
This is the Django function that I want to send the answer:
def teams_for_issue(request):
medIssue = request.GET.get("medIssue", none)
teams = Team.objects.filter(has_competence=medIssue)
data = {
"teams":teams
}
return JsonResponse(data)
I have defined the following URL
url(r'newpatient/', views.newpatient, name='newpatient'),
url(r'ajax/teams_for_issue/', views.teams_for_issue, name='teams_for_issue'),
Any help on where I go wrong would be much appriciated :)
define type in your ajax request.
$.ajax({
url: '/ajax/teams_for_issue/',
type: "POST",
data: {
'medIssue': medIssue
},
dataType: 'json',
success: function(data) {
_this.setTeams(data.teams)
}
});
also your view should read data from request.POST
def teams_for_issue(request):
medIssue = request.POST.get("medIssue", none)
teams = Team.objects.filter(has_competence=medIssue)
data = {
"teams":teams
}
return JsonResponse(data)

Use client side values in second php file via Ajax

I have three php files.
filter.php - to send Ajax request and get response
insert.php - to store Ajax response
getResponse.php - to use stored Ajax response.
Primary purpose of doing all these thing is to use client side values using PHP code because server and client can't exchange variable values each other.
Expected: Response should be stored in php variable in getResponse.php.
I got array response in insert.php but how can I use in getResponse.php?
For e.g.
---------- filter.php ----------
<script>
$.ajax({
type: "POST",
url: "filter.php",
data: { name: tp, country:"test"},
success:function(response) {
var res = response;
$.ajax({
type: "POST",
url: "insert.php",
data: { res: res },
success:function(data){
alert(data);
}
});
});
<script>
-------- insert.php ----------
if ($_POST) {
if ($_POST['id1'] !== "") {
echo $_POST['id1'];
}
}
-------- getResponse.php ----------
Code to get array response from Ajax via filter.php and insert.php.
Need to store these array value and do manipulation accordingly.
Here is the answer:
<script>
$.ajax({
type: "POST",
url: "filter.php",
data: { name: tp, country:"test"},
success:function(response) {
var res = response;
$.ajax({
type: "POST",
url: "getResponse.php",
data: { res: res },
success:function(data){
alert(data);
}
});
});
</script>

Categories

Resources