Django Ajax returns whole html page - javascript

I'm trying to create live search filter,with ajax
$(function() {
$('#search-item').keyup(function() {
$.ajax({
type: "GET",
url: "/toysprices/",
data: {
'query' : $('#search-toy').val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: searchSuccess,
dataType: 'html'
});
});
});
function searchSuccess(data, textStatus, jqXHR)
{
console.log(data);
}
and my views.py
f request.method == "GET":
search_text = request.GET['query']
if search_text:
search_text = request.GET['query']
statuss = Status.objects.filter(status__contains = search_text)
else:
statuss = Status.objects.all()
return render(request, 'ajax_search.html', {'statuss':statuss})
it works correctly, but it returns whole html page, how can i make to get only part which I want to render in my template.

Returning the result with JSON will solve your problem.
For Example,
# Django view
def search(request):
if request.method == "GET":
return_array = []
search_text = request.GET.get('query') # Always put request.GET.get('param') instead of request.GET['param']
if search_text:
search_text = request.GET.get('query')
statuss = Status.objects.filter(status__icontains = search_text)
else:
statuss = Status.objects.all()
for i in statuss:
return_sub_array = {}
return_sub_array['status_name'] = i.status_name
return_array.append(return_sub_array)
return HttpResponse(json.dumps(return_array))
# Jquery function
$('#search-item').keyup(function() {
$.ajax({
type: "GET",
url: "/toysprices/",
dataType: 'JSON',
data: {
'query' : $('#search-toy').val(),
'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
},
success: function(data){
if(data.length > 0 )
{
console.log(data);
for (var i = 0; i < data.length ; i++) {
var obj = data[i]['status_name'];
console.log(obj)
// further logic goes here
}
}
else {
console.log("No result found");
}
},
error:function(data){
console.log('error')
console.log(data)
}
});
});

In most cases it is the url which you are using to call, assuming you have the following path in the url.py
path('Import/', views.Import, name='import'),#.....1
path('getMetaData/', views.metaData, name='metadata'),#....2
and your url: http://127.0.0.1:8000/folder/Import/ is using the first path which is showing the page, if you wish to get data from ajax from the metaData function in views.py, if you use path 2 above it will give you html, so your path should be as follows:
path('Import/getMetaData/', views.metaData, name='metadata'),#....3

You are rendering html and returning it in your view. Here's nothing to expect from this view other than html. In order to return JSON object as a response, your view should return response like this:
return JsonResponse({'statuss':statuss})

Related

How can I send localstorage data from JavaScript ajax call and print return data from views in Django template

I have stored some data on localStorage( Itemnames and ItemIds), now I want to send itemid's to django views from ajax. I have basics knowledge of django and learning Javascript. I tried to figureit out by myself but its been more than 4 days I could not succeed, any help will be highly appreciated.
My Javascript:
$(document).ready(function() {
var compare = localStorage.getItem("comparisionItems");
var compareObj = JSON.parse(compare);
var data_url = window.location.href;
console.log(compare)
console.log(compareObj)
$.ajax({
url: './compare',
type: "POST",
data: {'compare_id': compareObj },
headers: { "X-CSRFToken": $.cookie("csrftoken") },
dataType: "json",
success: function (data) {
console.log(data)
},
error: function () {
alert("Some problem on passing data");
}
});
});
My views:
def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
compare_id= request.POST.getlist('compare_id[itemIds]')
"""compare_id=request.POST.getlist('itemIds[]') """
"""compare_id = request.POST.get('compare_id')"""
product = get_object_or_404(Products, id=compare_id)
context={ 'product':product}
""" return render (request, './ecommerce/compare.html', context)"""
return render (request, './compare.html', context)
else:
context = None
return render(request,'./compare.html', context)
How can I get the products which have id's pass by ajax? And is there any different ways to pass those products to the template or I can do it just like the regular Django context process?
Pass json string from your ajax request.
$.ajax({
url: './compare',
type: "POST",
data: JSON.stringify({'compare_id': compare }),
headers: { "X-CSRFToken": $.cookie("csrftoken") },
dataType: "json",
contentType : "application/json",
success: function (data) {
$.each(data, function (key, value) {
if (key == "products") {
for (var i = 0; i < data[key].length; i++) {
var wishlistUrl = "{% url 'ecommerce:add_to_wishlist' %}";
var div = '<div class="compare-col compare-product">';
div += '<i class="w-icon-times-solid"></i>';
div += '<div class="product text-center"><figure class="product-media">';
div += '<a href="product.html"><img src="' + data[key][i].product_feature_image.image.url + '" alt="Product" width="228" height="257" />';
div += '</a><div class="product-action-vertical">';
div += '<a href="#" class="btn-product-icon btn-wishlist w-icon-heart" title="Wishlist" attr_id="' + data[key][i].id + '" ';
div += ' action_url="' + wishlistUrl + '">';
div += '</a></div></figure><div class="product-details"><h3 class="product-name">' + data[key][i].name + '</h3>';
div += '</div></div></div>';
$('#parentDivElementId').append(div); #--- your parent div element id
}
}
})
},
error: function () {
alert("Some problem on passing data");
}
});
And in your views.py
Get POST data first
import json
from django.shortcuts import get_list_or_404, render
def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
data = json.loads(request.body)
compare_ids = data['compare_id']["itemIds"] if 'itemIds' in data['compare_id'] else []
# since here multiple ids may come you need to use `filter` instead you will get
get() returned more than one Products -- it returned 2!
products = Products.objects.filter(id__in=compare_ids).values()
return JsonResponse({'products ': list(products) }, safe=False) #---- since Queryset is not JSON serializable
else:
context = None
return render(request,'./compare.html', context)
In your console you can see your products data.
In your ajax you should stringify the data part like this:
$.ajax({
// rest of the code
data: JSON.stringify({'compare_id': compareObj}),
headers: { "X-CSRFToken": $.cookie("csrftoken") },
dataType: "json",
contentType: "application/json",
success: function (data) {
console.log(data);
// access your response as data.product
},
// rest of the code
});
And then in you view:
import json
from django.http import JsonResponse
def compare(request):
is_ajax = request.headers.get('X-Requested-With') == 'XMLHttpRequest'
if is_ajax and request.method == "POST":
compare_id = json.loads(request.POST.get('compare_id'))
ids = compare_id.get('compare_id')
# ids will be list of ids and you can get first id with index
product = get_object_or_404(Products, id=ids[0])
# rest of code
return JsonResponse({'product': product})

AJAX Callback Not Showing Success Message - ASP.NET MVC C#

I have some AJAX code in my JavaScript which is not showing any success or failure alert.
function AttemptHouseViewingAppointment(house) {
var imgOfHouse = $(house).attr("value");
$.ajax({
type: "POST",
url: '#Url.Action("AttemptHouseViewingAppointment", "Viewing")',
dataType: "json",
data: ({
userId: #Model.UserId,
appointmentKey: '#Model.Key',
chosenHouse: imgOfHouse
}),
success: function (data) {
alert(data);
if (data.success) {
alert(data.message);
} else { alert(data.Message) }
},
error: function (xhr) {
alert(xhr.responseText);
}
});
};
The above function is called when I click an image on the screen. This part works fine as I have set a breakpoint on my ASP controller and I can see the relevant action being called. C# code below:
public ActionResult AttemptHouseViewingAppointment(int userId, string appointmentKey, int chosenHouse)
{
string selecteHouseName = $"./house-code-icons/{chosenHouse}.png";
var house =
_ctx.houses.Where(x => x.HouseID == userId && x.Icon == chosenHouse)
.FirstOrDefault() ?? null;
if(house != null)
{
var member = _ctx.User.FirstOrDefault(x => x.Id.Equals(userId));
_ctx.Appointments.Add(new ViewingModel
{
House = chosenHouse,
UserId = userId
});
_ctx.SaveChanges();
return Json(new { success = true, message = "Appointment Confirmed!" });
}
else
{
return Json(new { success = false, message = "Sorry, a booking has already been made!" });
}
}
Even though, the return Json lines are being hit and returned to the page, there is no alert popup on my page to let user know if success or not. Please let me know if any questions.
Thanks
Add the done function to the end of Ajax
$.ajax({
.
.
.
}).done(function( response ) {
alert(response);
...
});

Call Laravel Model Function from Blade Button OnClick Javascript Function and Stay On the Page

Goal:
A user will have a list of games in a table with text boxes for each team's score. I want the user to be able to change the score of a single game, click Save (Model function updates the record), and continue saving more games while never leaving the page.
How:
After a Laravel Blade view has been rendered, I want to execute a Model function from a Javascript function on-button-click, but stay on the same page.
admin.blade.php (Javascript section in Head tag)
/* Save game from inline list on Admin page */
function inlineSaveAdmin(gameId) {
var homeScoreTxt = document.getElementById("homeScoreTxtBox");
var homeScore = homeScoreTxt.value;
var awayScoreTxt = document.getElementById("awayScoreTxtBox");
var awayScore = awayScoreTxt.value;
{{ App\Models\Game::inlineSave(gameId, homeScore, awayScore) }}
}
admin.blade.php (body of view)
<button type="button" onclick="inlineSaveAdmin({{ $game->id }});" class="btn btn-outline-success">Save</button>
So far, the Model function only executes when the page loads, not when I click the button. That is the main problem I wish to solve. Thanks for any help!
(and yes, I believe that I will need to create identical Javascript functions for each gameId that exists to be able to reference the correct homeScoreTxtBox{{ game->id }} since I don't think I could otherwise dynamically pull the text box IDs based on the Javascript function's input parameter)
1.make an ajax function on that blade file
2.call that ajax on click pass the id and updated data
3.define a route for that ajax function in web.php and
4.make a controller function on that route.
Code:
$(document).ready(function() {
$("#button").on('click', function() {
**//get id and score**
var homeScoreTxt = document.getElementById("homeScoreTxtBox");
var homeScore = homeScoreTxt.value;
var awayScoreTxt = document.getElementById("awayScoreTxtBox");
var awayScore = awayScoreTxt.value;
var game_id = gameId;
$.ajax({
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: '{{ route('update') }}',
//all the data you need to pass to controller function
data: {
'id': gameId,
'homescore': homeScore,
'awayscore' : awayScore
},
// dataType: 'json',
success: function(data) {
//data returned from php
// update the values
if (data) {
homeScoreTxt.value=data.homeScore,
awayScoreTxt.value=data.homeScore
}
},
fail: function() {
alert('NO');
}
});
});
});
web.php
Route::post('update', 'UpdateController#update')->name('update');
Update the values in the controller function by simple model queries.
Send updated data like this:
$response = [
'homeScore' => $homeScore,
'awayScore' => $awayScore
];
return response()->json($response);
I have followed Daniyal Ishaq's answer, and I think I'm getting closer, but I'm getting an error from the Ajax call.
Error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
(jquery-3.5.1.js:10099) xhr.send( options.hasContent && options.data || null );
Per Google debugger, it appears to be after/inside this call:
(jquery-3.5.1.js:9682) transport.send( requestHeaders, done );
I did some debugging, and a "status" variable is getting set to 500. Then, "isSuccess" is set to False when it gets to this line:
(jquery-3.5.1.js:9723) isSuccess = status >= 200 && status < 300 || status === 304;
That line that sets isSuccess is inside the following function, but I cannot seem to find where it's getting called from to trace where status is getting set exactly.
(jquery-3.5.1.js:9696) function done( status, nativeStatusText, responses, headers ) {
The last line I can find before the error appears is 5233:
(jquery-3.5.1.js:5233) jQuery.event.dispatch.apply( elem, arguments ) : undefined;
Shortly before that line, it is here, where event.rnamespace = undefined, and handleObj.namespace = "" (I don't know if this is relevant):
(jquery-3.5.1.js:5422) if ( !event.rnamespace || handleObj.namespace === false ||
Shortly after that, "ret" is still undefined after this line: (again, I don't know what this does, but it seems important?)
ret = ( ( jQuery.event.special[ handleObj.origType ] || {} ).handle ||
handleObj.handler ).apply( matched.elem, args );
Then on 5446, it returns event.result, which is undefined.
return event.result;
That is where my debugging skills hit a dead end with jQuery. So now I ask for more help.
Ajax function in blade:
$(document).ready(function() {
#foreach($games as $game)
$("#SaveBtn{{ $game->id }}").on('click', function() {
var gameId = "{{ $game->id }}";
var saveBtn = document.getElementById("SaveBtn{{ $game->id }}");
var homeScoreTxt = document.getElementById("homeScoreTxtBox{{ $game->id }}");
var homeScore = homeScoreTxt.value;
var awayScoreTxt = document.getElementById("awayScoreTxtBox{{ $game->id }}");
var awayScore = awayScoreTxt.value;
$.ajax({
url: "{{ route('inlineSave') }}",
type: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
//all the data you need to pass to controller function
data: {
'gameId' : {{ $game-> id }},
'homeScore': homeScore,
'awayScore' : awayScore
},
dataType: "json",
traditional: true,
success: function(data) {
//data returned from php
// update the values
if (data) {
homeScoreTxt.value = data.homeScore;
awayScoreTxt.value = data.awayScore;
saveBtn.innerText = 'Resave';
alert('Success!');
}
},
error: function() {
alert('An error has occurred!');
}
});
});
#endforeach
});
Resulting HTML for Ajax function:
$(document).ready(function() {
$("#SaveBtn11870").on('click', function() {
var gameId = "11870";
var saveBtn = document.getElementById("SaveBtn11870");
var homeScoreTxt = document.getElementById("homeScoreTxtBox11870");
var homeScore = homeScoreTxt.value;
var awayScoreTxt = document.getElementById("awayScoreTxtBox11870");
var awayScore = awayScoreTxt.value;
$.ajax({
url: "http://mbcathletics/admin",
type: "POST",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
//all the data you need to pass to controller function
data: {
'gameId' : 11870,
'homeScore': homeScore,
'awayScore' : awayScore
},
dataType: "json",
traditional: true,
success: function(data) {
//data returned from php
// update the values
if (data) {
homeScoreTxt.value = data.homeScore;
awayScoreTxt.value = data.awayScore;
saveBtn.innerText = 'Resave';
alert('Success!');
}
},
error: function() {
alert('An error has occurred!');
}
});
});
... many more of the same function for different button IDs ...
});
Button in blade: (calls its respective function successfully)
<button id="SaveBtn{{ $game->id }}" type="button" class="btn btn-outline-success">Save</button>
Route in web.php: (remember, I do not want to leave the page, I just want it to execute the Controller function... I don't know what to put in the first parameter - the URL)
Route::post('/admin', [App\Http\Controllers\HomeController::class, 'inlineSave'])->name('inlineSave');
Controller function: (it doesn't really do anything right now, I'm just trying to test connectivity before I do the heavy lifting)
public static function inlineSave()
{
$game = Game::find($gameId);
$score = $game->home_score;
$game->home_score = $score;
$response = [
'homeScore' => $homeScore,
'awayScore' => $awayScore
];
return response()->json($response);
}
Thank you! I am sorry for the detail, but it's the only I know how to help.

Django JSON Response to HTML Page Not Working

I have a Django project where I am trying to get AJAX working. I can't seem to send the JSON response to the HTML page. When I check the chrome console the JSON data is not returned only parses the HTML.
This is my Views.py where I have the cart logic defined:
def cart_home(request):
cart_obj, new_obj = Cart.objects.new_or_get(request)
return render(request, "carts/carts.html", {"cart": cart_obj})
def cart_update(request):
print("Hello")
product_id = request.POST.get('product_id')
if product_id is not None:
try:
product_obj = Product.objects.get(id=product_id)
except Product.DoesNotExist:
print("Product is gone")
return redirect("cart:home")
cart_obj, new_obj = Cart.objects.new_or_get(request)
if product_obj in cart_obj.products.all():
cart_obj.products.remove(product_obj)
added = False
else:
cart_obj.products.add(product_obj)
added = True
request.session['cart_items'] = cart_obj.products.count()
if request.is_ajax():
print("Ajax request")
json_data = {
"added": added,
"removed": not added,
}
return JsonResponse(json_data)
return redirect("cart:home")
This is javascript for the Ajax:
<script>
$(document).ready(function(){
var productForm = $(".form-product-ajax")
productForm.submit(function(event){
event.preventDefault();
console.log("Form is not sending")
var thisForm = $(this)
var actionEndpoint; thisForm.attr("action");
var httpMethod; thisForm.attr("method");
var formData; thisForm.serialize();
$.ajax({
url: actionEndpoint,
method: httpMethod,
data: formData,
success: function(data){
console.log("success")
console.log(data)
console.log(data.added)
console.log(data.removed)
console.log("Added", data.added)
console.log("Removed", data.removed)
var submitSpan = thisForm.find(".submit-span")
if (data.added){
submitSpan.html("<button>Remove</button>")
} else {
submitspan.html("<button>Add to Basket</button>")
}
},
error: function(errorData){
console.log("error")
console.log(errorData)
}
})
})
})
</script>
Added screenshot of Chrome Inspector (Network Tab)

Passing an array Of Objects Into An MVC .net core Controller Method Using jQuery Ajax

am using .netcore 1.1 , Visual studio 2017 , Jquery version = "3.2.1"
,am trying to make the MVC controller to get data from my page ,
i have 2 arrays in java , one is an array of Object (model view) and one is an array of strings
objects array always return error 400 (bad request)
2- string array ,always send null to the controller
i followed the below answers with no success
https://stackoverflow.com/a/13255459/6741585
and
https://stackoverflow.com/a/18808033/6741585
below is my chtml page
//#region send data back t oserver
$('#Savebtn').click(function () {
console.log(editedRows);
var UpdatedRows = JSON.stringify({ 'acActivityed': editedRows });
console.log(UpdatedRows);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/acActivity/Edit",
//traditional: true,
data: UpdatedRows ,
dataType: "json",
success: function (data) {
// here comes your response after calling the server
alert('Suceeded');
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error : " + jqXHR.responseText);
}
});
});
//#endregion
//#region deleted all selected
$('#DeleteSelectedbtn').on('click', function () {
if (confirm("Are you sure to delete All Selected ?????")) {
var selectedData = [];
var selectedIndexes;
selectedIndexes = grid.getSelectedRows();
jQuery.each(selectedIndexes, function (index, value) {
selectedData.push(grid.getDataItem(value).id);
});
console.log(selectedData);
var SelectedIds = selectedData.join(',') ;
console.log(SelectedIds);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/acActivity/DeleteSelected",
data: JSON.stringify({ "ids": SelectedIds }),
dataType: "json",
success: function (data) {
grid.render();
},
error: function (err) {
alert("error : " + err);
}
});
}
});
//#endregion
and both do have data as below console shots
the selected ID's one
my Controller
this one should expect the list of object and always return bad request ,
[HttpPost]
[ValidateAntiForgeryToken]
//public jsonResult Edit( List<acActivitytbl> acActivityed)
public ActionResult Edit( List<acActivitytbl> acActivityed)
{
foreach (acActivitytbl it in acActivityed)
{
logger.Log(LogLevel.Info, it.ID);
logger.Log(LogLevel.Info, it.Name);
logger.Log(LogLevel.Info, it.IsActive);
}
//return View(acActivityed);
return Json(new { success = true, responseText = "end of Page" });
}
that one should expect the delimited string ,but always receive null
public ActionResult DeleteSelected(string ids)
{
try
{
char[] delimiterChars = { ' ', ',', '.', ':', ' ' };
string[] words = ids.Split(delimiterChars, StringSplitOptions.RemoveEmptyEntries);
if (words != null && words.Length > 0)
{
foreach (var id in words)
{
bool done = true; //new acActivitiesVM().Delete(Convert.ToInt32(id));
logger.Log(LogLevel.Info, " acActivities ID {0} is Deleted Scussefully ", id);
}
return Json(new { success = true, responseText = "Deleted Scussefully" });
}
return Json(new { success = false, responseText = "Nothing Selected" });
}
catch (Exception dex)
{
..... removed to save space
});
}
}
i know there is something missing here ,but i cannot find it ,any help in that ??

Categories

Resources