Rendering mathjax content with data loaded from ajax response - ajax

In case like pagination gems like [will_paginate][1]
content that was loaded from ajax doesn't render MathJax symbols.

So something like this would fix.
$( document ).ajaxSuccess(function( event, xhr, settings ) {
let url = new URL(event.target.URL);
let params = new URLSearchParams(url.search.slice(1));
if (params.get('page') != null) {
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
}
});
In my case it pase will_paginate which could be identified by a param - page
It may be just a url in your case so checking like
event.target.URL == 'something'
should do good.

Related

Context from Django Render Not Displaying Till Refresh?

I am using an AJAX call to POST a value to my views.
From my views I am finding the product based on the value(id) passed to my view. I add it to my invoice and apply it to my context which I render at the bottom of my view. The context will not be displayed until I refresh, but I can't have that. I am stuck.
...
elif request.is_ajax():
product_id = request.POST.get('value')
if product_id:
product_info = Product.objects.get(id=product_id)
new_invoice_product = InvoiceProduct.objects.create(invoice_product_set=product_info)
invoice.attached_products.add(new_invoice_product)
context['attached_products'] = invoice.attached_products.all()
...
return render(request, 'inventory/invoice_create.html', context)
You can't just re-render client's HTML DOM by your server directly.
Through DjangoTemplate Engine, it just render then respond with HTML itself. This means you can't update client's DOM with ajax unless you update root element, <html>. (and this will be as same as reloading page!)
So you may want to update DOM tree with some data, do with ajax call then update with jsonfile only. If you use JsonResponse, then you can get it with AJAX response object.
Then What you have to do is NOT django template but JavaScript programming.
In your views.py, do like this:
# in your views.py
...
elif request.is_ajax():
product_id = request.POST.get('value')
if product_id:
product_info = Product.objects.get(id=product_id)
new_invoice_product = InvoiceProduct.objects.create(invoice_product_set=product_info)
invoice.attached_products.add(new_invoice_product)
context['attached_products'] = invoice.attached_products.all()
# return render(request, 'inventory/invoice_create.html', context) # NOT render but do like this:
return JsonResponse({
'new_data': {
'id': new_invoice_product.id
# and other informations you want...
}
})
In your HTML, do like this:
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script>
// in your HTML
// guessing you're using jquery..
$.ajax({
url: "test.html",
context: document.body
}).done(function (json) {
$('yourSelector').append(json['new_data']['id']);
});
</script>
Remember, this code is just snippet not Fully working code. If you want to know further examples, take a look at link:
https://simpleisbetterthancomplex.com/tutorial/2016/08/29/how-to-work-with-ajax-request-with-django.html

how do we use request.session.setAttribute for already existing session variable to UI

While loading the view page I am setting a session variable as:
request.session.setAttribute("list",list);
after that onclick of a button I am using ajax call to refresh the list. in backend I am able to see the latest list contents. But in UI I am using :
List<String> cList = (List<String>)session.getAttribute("list");
but even after the list is changed I am not able see the latest list contents.Still the old list contents are displaying on the page. Need some suggestions on how to resolve this issue.
var refreshThisDiv= "refreshThisDiv";
var goUrl= "unametest/getUserNamesList;
var httpRequest=null;
var refreshContent = "null";
httpRequest = XMLHTTPObject();
httpRequest.open("POST", goUrl, true);
httpRequest.onreadystatechange = function () {ajaxFcuntion(refreshThisDiv,httpRequest); } ;
httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
httpRequest.send(null);
//ajaxFcuntion
function ajaxFucntion(refreshThisDiv,httpRequest){
if (httpRequest.readyState == 4)
{
if(httpRequest.status == 200)
{
results = httpRequest.responseText;
if(results!=null){
<%
List<String> list = (List<String>)request.getSession().getAttribute("list"); %>
//display data from list
}
}
Actually as expected, you are mixing two different codes. You have to realize, where and when each code is executed - JSP on the server when the page is requested and rendered (i.e. before the response is send to the browser) and Javascript in the browser, after the browser receives the already generated response. For more details how to use AJAX, JSP and servlets together, read this question and answer carefuly.

AJAX response returns current page

I was searching for a similar issue for a while now, but none of the solutions worked for me (and I couldn't find exactly the same issue).
First of all, the website I'm working on is running on Zend Framework. I suspect that it has something to do with the issue.
I want to make a pretty basic AJAX functionality, but for some reason my response always equals the html of the current page. I don't need any of Zend's functionality, the functions I need to implement could (and I'd prefer them to) work separately from the framework.
For testing purposes I made it as simple as I could and yet I fail to find the error. I have a page "test.php" which only has a link that triggers the ajax call. Here's how this call looks:
$('.quiz-link').click(function(e){
e.preventDefault();
$.ajax({
URL: "/quiz_api.php",
type: "POST",
cache: false,
data: {
'test': 'test'
},
success: function(resp){
console.log(resp);
},
error: function(resp){
console.log("Error: " + reps);
}
});
});
And this quiz_api.php is just:
<?php
echo "This is a test";
?>
When I click on the link I get the entire HTML of the current page. "This is a test" can't be found there. I'm also getting an error: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/."
I reckon it has to do with the JS files that are included into this HTML response, but I've also tried setting "async: true" and it didn't help.
I would like to avoid using Zend Framework functions for this task, because I'm not well familiar with it and even making a simple controller sounds rather painful. Instead I want to find out what's causing such behavior and see if it can be changed.
PS: I've also tried moving quiz_api.php to another domain, but it didn't change anything.
I know that it might be an older code but it works, simple and very adaptable. Here's what I came up with. Hope it works for you.
//Here is the html
Link Test
<div id="test_div"></div>
function test(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// This is the php file link
var url = "quiz_api.php";
// Attaches the variables to the url ie:var1=1&var2=2 etc...
var vars = '';
hr.open("POST", url, true);
//Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange =
function(){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
console.log(return_data);
document.getElementById('test_div').innerHTML = return_data;
}else{
document.getElementById('test_div').innerHTML = "XMLHttpRequest failed";
}
}
//Send the data to PHP now... and wait for response to update the login_error div
hr.send(vars); // Actually execute the request
}
you can change the whole page with a document.write instead of changing individual "div"s

Laravel render for differend controller method

I'm struggling with the render() method in Laravel 5.
When $whatever->render() is runned, it takes the controller method name as the route by default.
Example:
When i run this command in DelasController#updateFilter, the pagination route is set to whatever.com/marketplace/updateFiler?page=2, which does not make a sense to me.
Problem:
I want to keep the route as simple as whatever.com/marketplace?page=2.
Question:
Can anybody gives me a hint on how to solve this?
Thank you for your time and a discussion.
Looking forward for a reply.
I have an application in which various paginated lists are displayed in "windows" on the page and are updated via AJAX calls to the server. Here's how I did it:
Set up a route to render the whole page, something like this:
Route::get('/marketplace', function ($arguments) {
....
});
Set up a route which will return the current page of the list. For example, it might be something like this:
Route::get('/marketplace/updateFiler', function ($arguments) {
....
});
In your Javascript code for the page, you need to change the pagination links so that, instead of loading the new page with the URL for the link, it makes the AJAX request to the second route. The Javascript could look something like this:
$('ul.pagination a').on('click', function (event) {
// stop the default action
event.stopPropagation();
event.preventDefault();
// get the URL from the link
var url = $(event.currentTarget).attr('href');
// get the page number from the URL
var page = getURLParameterByName(url, 'page');
$.get('marketplace/updateFiler', { page: page }, function (data){
// do something with the response from the server
});
});
The getURLParameterByName function is simply a helper that extracts the named parameter from a URL:
var getURLParameterByName = function (url, name, defaultValue) {
// is defaultValue undefined? if so, set it to false
//
if (typeof defaultValue === "undefined") {
defaultValue = false;
}
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(url);
return results === null ?
defaultValue :
decodeURIComponent(results[1].replace(/\+/g, " "));
};
I adapted this code from an answer I found here on Stack Overflow: https://stackoverflow.com/a/901144/2008384.

How do I get the correct URL for an MVC action when using Jquery/AJAX?

So I have my first MVC2 site that I'm working on and naturally I'd like to throw some AJAX in there. The problem is, is that I don't know how to get the URL for the action when passing in a URL parameter. Let me explain. The examples I've seen so far show the developer passing in strings like '/MyController/MyAction'. That's great, except if your controllers are not in the root directory of your website (as is the case in my situation). I could always use relative URLs like 'MyAction' except if the URL contains parameters that doesn't work either. Consider http://example.com/myroot/MyController/MyAction vs http://example.com/myroot/MyController/MyAction/PageNumber/SomeOtherValue. Now the relative URL will be incorrect.
In the ASPX code, this is easy. I just write in <%= Url.Action("MyAction") %>. But how do I do this in my javascript file?
This is part of the long-standing issue that including server-sided code in JavaScript files is not really possible :(. (Without serious hacks, that is.)
The best solution is to include the action URL inside your HTML file somewhere, then get that value from JavaScript. My suggestion would be something like this:
<!-- in your view file -->
<form id="MyForm" action="<%: Url.Action("MyAction") %>"> ... </form>
<!-- or -->
<a id="MyLink" href="<%: Url.Action("MyAction") %>"> ... </a>
combined with
// In your .js file
$("#MyForm").submit(function ()
{
$.post($(this).attr("action"), data, function (result) { /* ... */ });
return false;
});
// or
$("#MyLink").click(function ()
{
$.getJSON($(this).attr("href"), data, function (result) { /* ... */ });
return false;
});
This feels semantically clear to me, and in some cases even creates degradable fallback behavior for when JavaScript is turned off.
You can't do this in your JavaScript file directly, however you can pass these dynamic values into your script by way of a script initializer. Consider the following example:
External Js file
ShoppingCart = function() {
this.settings = {
AddProductToCartUrl: '',
RemoveFromCartUrl: '',
EmptyCartUrl: '',
UpdateCartUrl: ''
};
};
ShoppingCart.prototype.init = function(settings) {
this.settings = jQuery.extend(this.settings, settings || {});
};
HTML/View
<script type="text/javascript">
var cart = new ShoppingCart();
cart.init({ AddProductToCartUrl: '<%=Url.Action("MyAction")%>' });
alert(cart.settings.AddProductToCartUrl);
</script>
Simple: tell your javascript what the correct URL is.
Tactically, you can get there alot of ways, but they basically break down into two techniques:
Have a server-side generated javascript "configuration" so you can do something like var url = siteConfiguration.SITEROOT + 'products/pink-bunny-slippers' Note this file can be a normal MVC view, the only trick is you have to tell the controller to send a text/javascript header rather than text/html.
Basically, dependency inject it into your script. IE function wireUpAjaxLinksToService(linkIdentifier, serviceEndpoint) where you call using something like wireUpAjaxLinks('a.ajax', '<%= Url.Action("MyService", "Services") %>')

Resources