I want to render html page after ajax success. but i am not getting the proper path for the file. I am using django backend. I am not using django inbuilt function to authenticate. this is my python code.
this is the error
this is my project structure
//this is my javascript code
function admin_login(){
username = document.getElementById("username").value;
password = document.getElementById("password").value;
console.log(username+password);
data={
"username":username,
"password":password
}
$.ajax({
type: 'POST',
url: "http://127.0.0.1:8000/admin_login/",
data:JSON.stringify(data),
success: function(data) {
console.log('sucessfully loggedin')
window.location.href = "/chat/templates/user.html";
}
});
}
You're trying to redirect to a template. Django doesn't work like that.
With or without a redirect, a request from the browser always needs to go to a URL that is handled by a view. Your redirect should be to an actual URL listed in your urls.py.
Alternatively, given that this is a completely standard form that has no need for Ajax, you could remove the script completely. Just let the form submit in the normal way and redirect as the Django code determines.
Related
I have a login form includes password field. I show this login form in modal way and I would like to handle the form submit response is a special way(actually update the login bar to a account menu), so i prevent the default form submit by
$("#myformid").submit(function(event){
var form = $(this);
console.log(form.serialize());
event.preventDefault();
jQuery.ajax({
url: "http://localhost:5782/login",
success: function (data) {
login_form_modal.style.display = 'none';
},
data: {
form: form.serialize(),
},
type:"POST",
async: false,
});
})
I noticed that in the browser debug console, the password is plain text. My question is, is it safe to submit a serialized form using ajax?
'csrf_token=IjI4ODJZjJmMWI5MGU1ZMjM1Y2Y0M2QxNzY3ZGUwZmI5MDki.YcCuVA.3D_79wx6Lp2-hbZWRT04z_eGhbc&username=myusername&password=MyPlainTextPassword'
Thanks,
You have to send the password from the client to the server.
Both the client and the server need to know what it is — the client because it produces it and the server because it has to pass it through the right hash algorithm and compare it to whatever is in the database.
What you don't want is for the password to be intercepted in transit. The way to do that is to use HTTPS and not plain HTTP. (This obviously doesn't matter when you are working with localhost URLs and the data is development data and not production data, but needs to be dealt with for your production deployment).
I was using antiforgerytoken within my razor view, and it was working fine. Then I moved the same code to AJAX, and it has started giving weird problems.
The AJAX POST request works fine, but the action SendData() which is called from the AJAX has a redirect to a different View (return View("Close");), which does not work anymore. It worked perfectly fine when the SendData() was called from the form directly.
Working code:
#using(Html.BeginForm("SendData", "Controller", FormMethod.Post)) {
#Html.AntiForgeryToken():
}
Not working code:
#using(Html.BeginForm("", "", FormMethod.Post, new
{
id = "__AjaxAntiForgeryForm"
}))
{
#Html.AntiForgeryToken()
}
JS File:
var form = $('#__AjaxAntiForgeryForm');
var token = $('input[name="__RequestVerificationToken"]', form).val();
$.ajax({
type: 'POST',
url: '/Controller/SendData',
data: {
__RequestVerificationToken: token
},
cache: false,
success: function(result) {}
});
The Action SendData() executes fine, but the redirect within this action doesn't work anymore.
I advise you use .serialize() instead of the following line.
var token = $('input[name="__RequestVerificationToken"]', form).val();
It is generic and thus will automatically adapt to any model changes.
For a working example of Antiforgery used alongside Ajax check this answer. The question was asked for MVC3 but it should work perfectly well as long as you're using an MVC version above 3.
The result param in the success: function (result) part of the ajax call will receive whatever was returned by your SendData action. If the SendData action uses a return View([...]); then you will probably get some html code in your result var. You could also return json data as follow return Json([...]).
If you actually want to have a redirect be made by the result of your Ajax call you should return the URL that you want to use as the redirection's target as follow return Content("http://target.url.for.redirect.com"); and then in your success callback, using the location.replace method, do this:
success: function(result)
{
document.location.replace(result);
}
This way the URL returned by the Ajax controller will be used to execute a redirection.
NOTE if you wish to ALWAYS redirect the user after the form is sent you should not use ajax at all ! A regular POST form would be far better suited for the job.
I figured out the problem, as per the comment from Stephen Muecke. The AJAX calls don't allow redirects, as the whole point behind AJAX is to stay on the same page and make a background JS call.
I have a bootstrap form that takes user input, I want it to send data as json to an arbitrary HTTP endpoint. Can it be achieved without reloading of the page? So the form just floats away and nothing else happens? I'm no sure what to google for.
I'm using ASP.NET MVC 5.2.3.0 WebApp on Azure.
Using Jquery
$.ajax({
url: "Your End Point",
context: document.body,
success: function(){
'Whatever you need it to do'
}
});
Or make a HTTPRequest in JavaScript
I run a wordpress website. There is a button on the homepage that pushes a new state:
<button onclick="javascript:window.history.pushState('test','','?id=123')"
class="modalopen" </button>
After I click the button a modal contact form opens that needs to use the id parameter to decide who the email recipient will be in PHP.
I am trying to get the parameter:id from:
http://example.com/?id=452
Using the $_GET function.
I understand that pushState is client-side and that the URL has not updated server-side. How would I go about updating the url server-side without reloading the page.
I assume it would involve ajax. Unfortunately, I have no knowledge on it.
Alternatively, perhaps there is another way to retrieve the id.
For obtaining the email recipient the contact form uses this code:
$post_id = $_GET['id'];
$val = get_post_meta($post_id, $key, true);
Thank you in advance!
Using history.pushState() changes the referrer that gets used in the HTTP header, this will cause the URL bar to display http://example.com/?id=452, but won't cause the browser to load the url, so you cannot access to $_GET['id'], since the page is not actually requested to the server with that parameter.
If you want to use the id after it is created and without reloading the page you definitely need an ajax call.
Doing it is simpler than what you might think, you can try to do it using jQuery.
a sample call is
$.ajax({
type: "POST",
url: "doSomething.php",
data: {id:id},
cache: false,
success: function(result){
// do something with the data returned by the doSomething.php script
}
});
Google jQuery ajax for more details.
This can be a useful starting point http://www.tutorialspoint.com/jquery/jquery-ajax.htm
This is doubtless a newbie question but I cannot find one that's similar. I want to pass a model to an action through a JS function. I have the Ajax script:
var modelDataJSON = '#Html.Raw(Json.Encode(Model))';
$.ajax({
url: '#Url.Action("Action1", "Home")',
type: 'POST',
data: modelDataJSON,
dataType: 'json'
});
And I have for the action:
public ActionResult Action1(MyModel modelDataJSON)
{
return Content(modelDataJSON.ToString());
}
It's not doing anything. What have I missed? Again, sorry for the newbie question but I have already been stuck for too long on it.
Perhaps there's a misunderstanding. What I'm asking is how you redirect to the Action1 URL using a JS script. If it runs then it will display the content because it's a content action.
Don't use Ajax if you want to load a new page.
To make a POST request, you need to submit a form.
The best way to approach this is to use a plain, regular HTML form and not involve JS at all.
If you really want to involve JS then you can generate a form.
var f = document.createElement("form");
f.action = myURL;
f.method = "POST";
// append inputs to the form to pass the data in modelDataJSON here
document.body.appendChild(f);
f.submit();
Note that you can't send a JSON payload this way (but despite the variable name being modelDataJSON, your Ajax would have been sending standard form encoded data anyway).