How to fix a MultiValueDictKeyError - javascript

I am trying to get the time spent on each page in a Django project using Javascript. I keep getting an error so I am trying to fix it
the error:
MultiValueDictKeyError at /backendurl/
'timeSpent'
Highlighted line of error in views.py:
timeSpent = request.POST['timeSpent']
Here is the javascript in template:
<script>
$(document).ready(function() {
var startDate = new Date();
$(window).unload(function() {
var endDate = new Date();
$.ajax({
type: POST,
url: "backendurl", // be mindful of url names
data: {
'timeSpent': endDate - startDate || 'none' // defaults to a string
},
success: function(response) {
// unpack response:
status = response.status
}
})
</script>
Here is the views.py:
def my_view_function(request):
timeSpent = request.POST['timeSpent']
response = json.dumps({
'timeSpent' : timeSpent,
})
return HttpResponse(response)
Here is the url.py
path('backendurl/', views.my_view_function, name='backendurl'),

In most probability, the key 'timeSpent' is not present in request.POST.
To get the key's value from request.POST dict you need to use the MultiValuedDict's get method.
You can also put a default to know that you have not got the key in your request, -1 in this case below.
timeSpent = request.POST.get('timeSpent', -1)

Related

Javascript Ajax: how to get the Id of something?

Right now I'm trying to do a simple delete / update / get through the User Id but I'm not getting the data correctly and I don't know if it's because of the ajax function, if it's for my web Api or if it's because of gRPC ,
My question is similar to this link I already asked, so I'll maybe show the simplest part which is the delete and also show the ajax call
Old Link: gRPC and/or WebAPI: How to do a simple Update but using an Id
gRPC Delete:
public override async Task<Empty> Delete(UserFilter requestData,
ServerCallContext context)
{
var data = await _context.Users_5.FindAsync(requestData.UserID);
if(date == null)
{
throw new Exception("User Not Found");
}
_context.Users_5.Remove(data);
await _context.SaveChangesAsync();
return await Task.FromResult(new Empty());
}
WebApi:
[HttpDelete("{Id_user}")]
public async Task<ActionResult<Empty>> DeleteUser([FromBody] UserFilter Id_user)
{
_logger.Log(LogLevel.Information, "Request Received for AuthController::Delete");
/**
if(Id_user == null)
{
return BadRequest("Id not Found idk why");
}
if(Id_user.ToString() != Request.Cookies["LoginUserId"])
{
return BadRequest("Id's is Different");
}
*/
var results = await _userClient.DeleteAsync(Id_user);
_logger.Log(LogLevel.Information, "Sending Response from AuthController::Delete");
return Ok(results);
}
The Javascript Code:
var $users_A = $('#users_A');
var $Id_user = $('#Id_user')
$users_A.delegate('.remove', 'click', function () {
var $li = $(this).closest('li');
var self = this;
debugger;
$.ajax({
url: uri_7 + $Id_user,
type: 'DELETE',
success: function() {
$li.fadeOut(300, function () {
$(this).remove();
});
},
error: function (xhr, textStatus, errorThrown) {
console.log('XHR:' + JSON.stringify(xhr) + '\nTextStatus:' + textStatus + '\nErrorThrown:' + errorThrown);
}
});
});
The stupid error:
XHR:{"readyState":4,"responseText":"{"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title" :"One or more validation errors occurred.","status":400,"traceId":"00-82ac37132e06d497f2f7ec082e382273-ba6109fbfa7fd9f8-00","errors":{"$\ ":["The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0."],"Id_user":["The Id_user field is required."]}}","responseJSON":{"type":"https://tools.ietf.org/ html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"00-82ac37132e06d497f2f7ec082e382273-ba6109fbfa7fd9f8-00","errors":{ "$":["The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0."],"Id_user": ["The Id_user field is required."]}},"status":400,"statusText":"error"}
--Conclusion--
Idk what's happening, I have the post and the getAllUsers correct but getting a specific user it gives me a lot of pain, so how to correct this code??
Any Answer/Help is always welcome

capturing and updating variable values after ajax request in url

I would really appreciate some help on this. I have a page that shows products in a store using laravel pagination. I have filters on the page based on brands, category, and available products. for filtering the products I am using a checkbox. if a checkbox is checked I use ajax get request and send status via URL to a controller to filter available products.
status = 1 is for available products, and status = 0 is for all products.Url is looks like this:
/Collections/Newest_Items?status=1&page=2
Here is the situation. I want to know if is it possible to change the variable value in URL and regenerate the URL base on the page number and new filters dynamically? Is it a way to get the URL of the page using jquery and change the values and then change the Url with window.history.pushState("", "", URL);?
Here is my ajax:
$(document).on('click', "#only_available", function () {
if ($('#only_available').is(':checked')) {
var status = 1;
url = '/Collections/Newest_Items?status='+status;
} else {
var status = 0;
url = '/Collections/Newest_Items';
}
window.history.pushState("", "", url);
$.ajax({
url: '/Collections/Newest_Items',
type: "GET",
data: {status: status},
cash: false,
success:
function (response) {
$('#products-load').html(response);
}
});
});
});
I do this by writing the URL by myself. In this situation, I must write the URL after every filter applied to the page. this way I cant get the page the user currently in and it goes back to the first page. But what I want to achieve here is, I want to make the Url dynamically with page number the user currently on with all filters applied to it.
You can use window.location.search which will give you something like: status=1&page=2 in your example. Then you will need to parse out those variables to get the page number you're looking for.
Ok I think I understand what you are asking for. So with each unique filter event that you are firing you need to query the current url before pushstate and get the values with something like this.
For instance if someone clicks Brand then you would get the new brand variable as well as the current status and page variables to pass with ajax like this
also just POST it instead of GET
$(document).on('click', ".brand", function () {
var brand = $(this).attr('id);
//Example how to use it:
var params = parseQueryString();
var status = params["status"]);
var page = params["page"]);
// if you have more variables than this then you would add them here and make sure you pass them along to the ajax data.
url = '/Collections/Newest_Items?status='+status+'&page='+page+'&brand='+brand;
window.history.pushState("", "", url);
$.ajax({
url: '/Collections/Newest_Items',
type: "POST",
data: {status: status, page: page, brand: brand},
cash: false,
success:
function (response) {
$('#products-load').html(response);
}
});
});
var parseQueryString = function() {
var str = window.location.search;
var objURL = {};
str.replace(
new RegExp( "([^?=&]+)(=([^&]*))?", "g" ),
function( $0, $1, $2, $3 ){
objURL[ $1 ] = $3;
}
);
return objURL;
};
tnx to #CesarBielich and #Sokies I finally manage to solve the problem. they give me part of the answer but not all.I made it unique to my question:
what we need here is the path and the parameters that nested in URL. so for getting the path of the route, we must use window.location.pathname and for getting all the parameters must use window.location.search. after that, we must combine the path and params so that the URL comes out of it. then we must add the new parameter like status after that. So that all the parameters can be accessed by the controller. both the old params and the new one. this way laravel pagination knows what url to make, in the href links to other pages.
$(document).on('click', "#only_available", function () {
if ($('#only_available').is(':checked')) {
var status = 1;
} else {
var status = 0;
}
var params = window.location.search;
var path = window.location.pathname;
var old_url = path+params;
var url = old_url+'&status=' + status;
window.history.pushState("", "", url);
$.ajax({
url: url,
type: "GET",
cash: false,
success:
function (response) {
$('#products-load').html(response);
}
});
});
});

Using cookies to check if anonymous user voted

I'm working on a webapp that uses Flask as the backend server. There are posts that I'm storing in an SQLAlchemy database, and I want the users to be able to upvote/downvote them without having to log in. I wrote a JavaScript function for upvoting/downvoting that increments the current vote count and then updates the count in the database using Ajax. I want to make sure that the same user doesn't vote on the same post twice; it doesn't have to be robust. I read that cookies could be used for that purpose, or a combination of cookies and IP. I'm having a hard time understanding how to get started: do I assign a cookie to a user in JS or in Flask? How do I check whether the user already voted? I'd appreaciate if someone could show me a simple example or direct me to a good resource. Thanks a lot.
Here's my Javascript part for upvoting:
$(document).ready(function() {
$('#{{ upbtnID }}').click(
function() {
var postID = "{{ answer.id }}";
var data = {
'id': "{{ answer.id }}"
};
var score = document.getElementById('{{ scoreID }}');
var scoreText = score.textContent;
var scoreToInt = parseInt(scoreText, 10);
var newScore = ++scoreToInt;
var scoreToStr = newScore.toString();
$(this).css('border-bottom-color', '#26EDEB');
score.textContent = scoreToStr;
$.ajax({
url: "/upvote",
data: JSON.stringify(data, null, '\t'),
contentType: 'application/json;charset=UTF-8',
type: 'POST',
success: function(response) {;
},
error: function(error) {
alert("Awww");
}
});
});
And the corresponding function in Flask:
# upvote a post
#app.route('/upvote', methods=["GET", "POST"])
def upvote():
if request.method =="POST":
thePostID = int(request.json["id"])
thePost = Answer.query.get(thePostID)
thePost.score += 1
db.session.commit()
data = thePost.score
return ('', 204)
Quoting from Flask snippets:
#app.route('/set_cookie')
def cookie_insertion():
redirect_to_index = redirect('/index')
response = current_app.make_response(redirect_to_index )
response.set_cookie('cookie_name',value='values')
return response
Link: http://flask.pocoo.org/snippets/30/

How to call server side function from json?

this is my code
<script type="text/JavaScript">
var myarray = new array();
function getsvg1() {
$.ajax({
alert("hello");
type: "post",
url: "WebForm1.aspx/getsvg1",
alert("abc");
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var cars = response.d;
alert(cars);
alert("hi");
},
failure: function (msg) {
$('#output').text(msg);
}
});
}
</SCRIPT>
webservices
[System.Web.Services.WebMethod]
public static ArrayList getsvg1()
{
XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/NewFolder1/10000.svg"));
//XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/Orders/100001_PRO/2/svg0.svg"));
//XNamespace ns1 = "http://www.w3.org/2000/svg";
//Namespace of a root element can also be retrieved like this:
//XNamespace ns1 = doc.Root.GetDefaultNamespace();
//var g = doc.Descendants(ns1 + "image").FirstOrDefault();
// XDocument doc = XDocument.Load(Server.MapPath("~/excelfiles/svg0.svg"));
XNamespace ns1 = "http://www.w3.org/2000/svg";
//Namespace of a root element can also be retrieved like this:
//XNamespace ns1 = doc.Root.GetDefaultNamespace();
var retrieveimage = doc.Descendants(ns1 + "image").FirstOrDefault();
var retrivetext = doc.Descendants(ns1 + "g").FirstOrDefault();
ArrayList arlelem = new ArrayList();
foreach (XElement element in doc.Descendants(ns1 + "g"))
{
//string[] parts = element.Split(',');
Console.WriteLine(element);
arlelem.Add(element);
}
// var retrivetext1 = doc.Descendants(ns1 + "text").SelectMany(i => i.ElementExtensions.Select(e => e.GetObject<XElement>().Attribute("url").Value)).ToArray();
//var retrivetext = doc.Descendants(ns1 + "text").All();
string v = arlelem[1].ToString();
string values = retrieveimage.ToString();
string values1 = retrivetext.ToString();
char[] delimiterChars1 = { ' ', ',', '"', '\\', '\t', '=' };
//string text = "one\ttwo three:four,five six seven";
//System.Console.WriteLine("Original text: '{0}'", text);
string[] words = values.Split(delimiterChars1);
string[] words2 = values1.Split(delimiterChars1);
string[] newword = v.Split(delimiterChars1);
//Session["newimgwidth"] = words[15];
return arlelem;
}
alert is not coming for cars values and breakpoint not going for success and failure. in this example i m calling server side function from
json that function result
To start with your ajax request is filled with syntax errors.
The $.ajax({ }) block cannot have a alert("hello"); inside it
Remove alert("abc"); too
use console.log() instead of alerts in your success method, this is not one of the error but a suggestion/advice.
What is your method returning in case of error ? In your ajax error method it seems to be expecting a string value.
Why are you using type: "post" when you are not posting any data to your method. Use a 'get' instead.
To debug your server side code, try opening the WebForm1.aspx/getsvg1 url in your browser window and see if you get the expected response. If all is well next try sending an ajax request using a client like postman rest client to check the response again.
Hope this helps.
you can use jQuery for this:
$.getJSON( "http://server.com/webservice", function( data ) {
console.log(JSON.stringify(data));
}
See more details at: http://api.jquery.com/jquery.getJSON/
{key,value } it allow json data.means already availble options or new define json value only. you can enter,if you try to alert("hello") it doest allow.so it stopped.so,try without alert message use inside brackets {}.

Accessing a controller method from javascript file(MVC3)

I have a method in the controller which returns a JASON output as given below.
public JsonResult GetJSONDateData()
{
JsonResult startDate = new JsonResult();
var Mystartdate = "02/01/2011";
startDate.Data = Mystartdate;
startDate.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
return startDate;
}
And I try to access this method in javascript using
var query = '';
query = getDomainURL() + "/ControlelrName/GetJSONDateData";
jQuery.ajaxSetup({ async: false });
var startDate = ''; //The max size if nothing is coming from config...
$.post(query, function (response) {
startDate = response;
});
jQuery.ajaxSetup({ async: true });
IS there anything wrong in my functions? I am not getting anything in the response. Pls help
Thanks,
Adarsh
I suspect that you are making a GET request and it's not allowed.
In your action method try the following:
return JSON(startDate, JsonRequestBehavior.AllowGet);

Categories