Laravel - CSRF for custom ajax posts - laravel

To pull partial views dynamically in laravel, you would use ajax. From a security standpoint, you would normally use a token that laravel provides to avoid csrf attacks.
Many times, you don't need an entire HTML form, you just use jquery to post data, so you can retrieve a partial view as a response, and inject it into your HTML.
I understand that in an HTML form, you can include a token for laravel to avoid csrf, but if it's an ajax request via jquery without a form, and you have many elements on the same page doing different things via ajax on their individual click events for example, do you need multiple different tokens for each when you do the post to protect yourself from csrf attacks, or can you create a single global line in HTML like:
<div style="display: none;" data-token="{{ csrf_token() }}">
In a certian area on the page, that you can use for all your non-form ajax requests when you write jquery post request for. What I am asking is, for non form element jquery post requests, can you use a single data-token attribute, or should each non form jquery element have its own csrf_token data attribute sent to the route to prevent a csrf attack?

Try to create a global variable in javascript that will hold the current value of _token, you can add this code to your html header
<script> var _token = '<?php echo csrf_token(); ?>'; </script>
then put that _token to each ajax request
(assuming that you filtered the route with csrf checking)

Related

codeignighter redirect issues to refresh

I have a registration page.after completing the registration the user will redirect to a new page. In new page when I click the back button I redirect to last page with last data filled up.how to refresh the page to delete form data. The framework is codeignighter.
To refresh or redirect page in codeigniter there is function redirect(YOUR_URL).
Have a Look in Helper class for more details
If you are referring to browser back button keep autocomplete off for the form fields in your first form
You can use autocomplete for the complete form
<form action="/action_page.php" autocomplete="off">
Or specifically to each control as
<input type="email" name="email" autocomplete="off">
You can also make it on for specific controls/entire form if you need it
if your problem still persists you could use
<body onload="document.refresh();">
This shall refresh the page on loading for the first time
include this in your page if required to force reset the form on load if you need you can bind this with a javascript onload function
<script type="text/javascript">
document.getElementById("myForm").reset();
</script>
in case of application back button {if used with href or redirect()}
Shall keep form clean even if autocomplete is not set unless the user takes from browser autofill or you fill them with code

Ajax helper in ASP.net MVC

I know that this question may not be fit for stack overflow. I've been searching for an example on how to use the ajax helper but most toturials have only gone through the helper and they have not provided any practical example. I already know how to make use of ajax the javascript way but just want to know how I can use the ajax helper that microsoft has provided.
To describe how this GitHUb branch works:
First, let's define an action we're going to request. To keep things simple, let's just make a very basic POST action:
//
// POST: /Home/Ajax
[HttpPost]
public PartialViewResult Ajax()
{
// use partial view so we're not bringing the entire page's theme
// back in the response. We're simply returning the content within
// ~/Views/Home/Ajax.cshtml
return PartialView();
}
Next, setup a destination for your content and give it an id (here I've named it "update-me"):
<div class="well" id="update-me">
Click the button to see some AJAX content.
</div>
Moving on from there we setup the form. The below demonstrates the standard AJAX functionality, but you could bind your own functions to some of the events specified by AjaxOptions.
#using (Ajax.BeginForm("Ajax", new AjaxOptions {
HttpMethod = "POST", // HttpPost
InsertionMode = InsertionMode.Replace, // empty the target first
UpdateTargetId = "update-me" // place content within #update-me
}))
{
<button type="submit" class="btn btn-default">
<i class="glyphicon glyphicon-refresh"></i>
Click Me!
</button>
}
And finally, we need to specify our script libraries responsible for most of the ["automatic"] wiring up of the form functionality:
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
That's it. As you begin playing with it you'll find it's pretty simple to extend it. For example, if you wanted to show a "working" icon you could specify custom functions in the OnBegin and OnComplete properties.
Ajax helper of ASP.NET MVC essentially provides Ajax functionality to your web applications. AJAX Helpers are used to create AJAX enabled elements like as Ajax enabled forms and links which performs request asynchronously. Using Ajax helper you can submit your HTML form using Ajax so that instead of refreshing the entire web page only a part of it can be refreshed. Additionally, you can also render action links that allow you to invoke action methods using Ajax. AJAX Helpers are extension methods of AJAXHelper class which exist in System.Web.Mvc.Ajax namespace.
AJAX-enabled link based on action/controller example:-
Following example shows how to use AJAX action link using action and controller in Asp.Net MVC.
#Ajax.ActionLink("Fatch Data", "GetData", new AjaxOptions {UpdateTargetId = "Data-container", HttpMethod = "GET" })
Here is the html output of above code block.
Output:
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#Data-container" href="/Home/GetData"> Fatch Data </a>
Do you know Unobtrusive AJAX in MVC?
The Unobtrusive Validation and AJAX support in ASP.NET MVC follow many best practices that enable Progressive Enhancement and are also super easy to use. The unobtrusive AJAX library (not the unobtrusive validation library) is admittedly a bit limited in functionality, but if it satisfies the requirements of the application you are writing, then by all means use it. And because the source code of it is in your app (it's JavaScript, after all), it's generally straightforward to make any updates or changes to it as you see fit.

How to recognaize which ajax form it is in Django?

I have view which takes care of all the Ajax submits from the client side. And to differentiate them by I uses different submit button names such as this one
<input type="submit" value="Send" name="send_message">
Suggested from this question.
The only problem is that from the view side it doesn't seems to carry the name to the server side so I cannot use the following if-statement
if 'send_message' in request.POST:
It works if I send it normally with page fresh. But I want to use it with Ajax.
I came up with a hack that you can add this name with jQuery. Simply by after serializing() your data you then concatenate the name attribute by data += "&send_message"
Then the if statement will work. But it doesn't seems so clean. So I wonder if there's a better way to handle this? Or should I make different views to handle the different Ajax calls I have?
You really should post each form to a different URL.
If not, you could add a hidden input with the name of the form as the value.
<input name="form_name" type="hidden" value="form_1" />
views.py:
form_name = request.POST['form_name']

Explicit POST in JSP page

<FORM NAME="form1" METHOD="POST" action="some.jsp">
<INPUT TYPE="text" NAME="first" VALUE="First">
<INPUT TYPE="text" NAME="second" VALUE="Second">
</FORM>
When the form is submitted in the background a POST method is sent to that jsp page with the parameters.
What I am trying to do is that I have an ajax call to a local mediator jsp page which should then take those parameters and post to a page on another domain (this is for me to circumvent the cross-domain problem with ajax calls in IE8).
How would I do an explicit post? Something that takes a URL and the parameters?
If all you are having issue with is posting the form, it is as simple as
document.forms['form1'].submit()
EDIT: In that case, see Using java.net.URLConnection to fire and handle HTTP requests for how to make a POST or GET request. I would recommend using request.getParameterMap() and iterating over that, dropping those parameters into the new outbound request.
http://tomcat.apache.org/tomcat-5.5-doc/catalina/docs/api/org/apache/catalina/connector/Request.html

Executing Javascript functions from an AJAX - HTML response

I have a web page that displays comments, and users can click a 'Flag' link to report an inappropriate comment.
When they click the Flag link, I use AJAX and innerHTML to display a dropdown box underneath the comment with a reason code, e.g. Spam, Offensive, Unrelated to topic, etc., as well as a Cancel button.
If the user clicks Submit, I want to use another AJAX request to send their response to a PHP file, where the database is updated, and they receive a "Thank you" on their end (without reloading the page). I essentially want the DIV that displays the dropdown box to be replaced with "Thank you" using another AJAX request.
That's where the problem is. It seems that I cannot execute an AJAX request from within the HTML response from the first AJAX request. The JavaScript functions fail -- even a simple Alert('hello world') doesn't work. I tried placing the JavaScript functions in the main page that calls the first AJAX request, as well placing it in the PHP file that displays as the HTML response from the first AJAX request, but I did not have any luck -- the functions just do not run when they are called.
Everything works fine if I load the PHP file externally, so I know the JavaScript is correct. It just doesn't work when I load the PHP file into the HTML response DIV and then call the JavaScript from there.
So to sum everything up, how do you execute JavaScript functions from the HTML response of an AJAX request?
EDIT: here is a sample of what I want to do:
This is the AJAX part that populates the DIV when the person clicks the Flag link:
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4)
{
document.getElementById(whichdiv).innerHTML=xmlhttp.responseText;
}
};
The value of xmlhttp.responseText comes from this external file:
<input type="hidden"/>
<script type="text/javascript" language="javascript">
function displayalert()
{
alert ('Hello World!');
}
</script>
<form name="myform" id="myform">
<input type="text" name="myfield" value="teststring"/><br/>
<input type="button" name="button" value="Submit"
onclick="displayalert();"/>
</form>
Note: the <input type="hidden"/> above comes from a suggestion I found off of http://msdn.microsoft.com/en-us/library/ms533897%28VS.85%29.aspx.
When the user clicks the button, the javascript displayalert() function doesn't run. The alert box never pops up. If I load the file externally instead of calling it with innerHTML, the script works fine.
Can the xmlhttp.responseText contain JavaScript code?
depends on the browser:
IE doesnt support scriptEval on html that is loaded with ajax, which means that if you have script blocks in your html, they wont be called.
Firefox supports script eval.
What i usually do is shove some json into an input, then check if the browser supports scriptEval, if it doesnt, pull the json, eval it, and call some method passing json.
if the browser supports scriptEval, i also include a script block that contains a call to the same method with the json.
you may also want to read this:
http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html

Resources