I have a login form and I am looking to post the input values to a RESTful web service and then the credentials are correct I show elements and hide the form but if they are incorrect an error message appears.
I want to do this via AJAX but I am hitting a stumbling block as all i am returning is an alert box with undefined inside. Any help would be greatly appreciated.
<div class="cp_LoginPanel fade-in form">
<div class="in">
<h1>Login</h1>
<form name="login-form" id="login-form" method="post">
<label id="error">Sorry it seems your credentials are incorrect</label>
<div class="inputBlock">
<label for="username">Username</label>
<input type="text" id="username" />
</div>
<div class="inputBlock">
<label for="password">Password</label>
<input type="password" id="password" />
</div>
<input type="submit" value="Login" id="submit" />
</form>
</div>
</div>
$(document).ready(function () {
var username = $("#username").val();
var password = $("#password").val();
$("#submit").click(function () {
$.ajax({
type: 'POST',
url: "Service Here",
dataType: JSON,
data: {
"username": username,
"password": password
},
success: function (data) {
alert("success");
},
error: function (e) {
alert(e.Message)
}
});
});
});
Not that this is the answer to your problem. But im guessing you get and error and therefore try using the correct error parameters to get more information about your error.
The error function is called if the request fails. This functions receives 3 parameters.
The jqXHR object
A string describing the type of error that occurred
An optional exception object, if one occurred
Try using the code below to print out your error the correct way. Look at the example below:
error: function(jqXHR, textStatus, errorThrown) {
console.log('What is my error ' + textStatus);
console.log('Is an exception thrown ?? ' + errorThrown)
}
Hope that you get more information about your error :)
PS.
You could also look at the answer in this question. It the excact same problem as yours :)
jQuery Ajax - how to get response data in error
Related
I want a user to be able to edit the order and delete some items. To do this, for each item I added a delete button (you can see it in the code below).
Partial view Views/Shared/EditorTemplates/Item.cshtml (Attribute data-id is hardcoded, because I have no idea how to pass the current OrderItem Id):
#model TimeTracker.Models.OrderItem
<div asp-validation-summary="ModelOnly" class="text-danger"></div>
<div class="form-group">
<label asp-for="Product" class="control-label"></label>
<input asp-for="Product" class="form-control" />
<span asp-validation-for="Product" class="text-danger"></span>
<input class="btn btn-default" type="button" id="btnDel" data-id="1" value="Remove" />
</div>
In ajax call comes the error in the console, which refers to the controller method. Here I am assuming I filled in the parameter data in ajax call incorrectly. I really don't know how to fill it in correctly in my case.
Failed to load resource: the server responded with a status of 405 ()
:5001/Orders/RemoveItem:1
Ajax call:
$("#btnDel").on('click', function () {
$.ajax({
async: true,
data: { order: $('#form').serialize(), orderItemId: $('#btnDel').data('id') },
type: "DELETE",
url: '/TaskTypes/RemoveItem',
success: function (partialView) {
console.log("partialView: " + partialView);
$('#itemsContainer').html(partialView);
}
});
});
Controller method:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> RemoveItem([Bind("OrderItems")] Order order, int orderItemId)
{
order.OrderItems.RemoveAll(c => c.Id == orderItemId);
return PartialView("Items", order);
}
When you use ValidateAntiForgeryToken You have to pass RequestVerificationToken in your ajax header to validate your request.
Please visit https://learn.microsoft.com/en-us/aspnet/core/security/anti-request-forgery?view=aspnetcore-3.1 for more details about prevent cross site request.
I have a simple "login" form and ajax is working. But every time I load the page freshly in new tab, and "login" page loads, I input the username and password, press "login" button and for some reason page just reloads, but on the reloaded page when I press "login" button, ajax works just fine. Anyone know what does this mean?
Here is simple login form:
<form id="login_form" name="login_form" data-ajax="false">
<label for="basic">Username:</label>
<input type="text" name="usr" id="usr" value=""/>
<label for="basic">Password:</label>
<input type="password" name="psw" id="psw" value=""/>
<input type="submit" value="Login" id="login" name="login"/>
<label><input type="checkbox" name="remember_me" id="remember_me" value="checked_remember"/>Remember me!</label>
</form>
<div id="login_message"></div>
And here is my ajax script:
$(document).ready(function(){
$("#login").click(function(){
username=$("#usr").val();
password=$("#psw").val();
$.ajax({
type: "POST",
url: "http://imes.jzpersonal.com/php/login_check.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='true')
{
$("#login_message").html("Logged in, congratulation.");
}
else
{
$("#login_message").html("Wrong username or password");
}
},
beforeSend:function()
{
$("#login_message").html("Loading...")
}
});
return false;
});
});
Also I'm using POST method but I still get address in address bar like this:
http://imes.**********.com/login_page.php?usr=Jakub&psw=********&login=Login
Is this an jQueryMobile thing?
Reason for this is you cant use $(document).ready(function(){ with jQuery Mobile. You should use :
$(document).on('pageinit'){
});
or if your page has an id then use it like this:
$('#page_id').on('pageinit'){
});
More info about this problem can be found here: http://jquerymobile.com/test/docs/api/events.html
Read this article to find more about this and jQM page events: https://stackoverflow.com/a/14010308/1848600
I have this simple submission form and I want to "ajaxify" it so the user isn't redirected to this page thanks.php after submission. I want the content from thanks.php to respond and show inside the div.
What jquery code will plug right into this to show the response.
<div ><form method="post" action="http://domain.com/thanks.php">
<input type="text" placeholder="Enter Email" name="email" id="email" >
<input type="submit" name="submit" value="Submit" ></form></div>
I would give 'form' and 'div' a class or id so it is not so generic, but this should work.
$("form").submit(function (){
$.ajax({
url: "http://{url}/thanks.php",
type: 'POST',
data: {email: $("#email").val()},
success: function ( data ) {
$("div").html(data);
}
});
return false;
});
I am trying to make an Ajax call using JQuery to a servlet that returns a JSON object.
In the JSP page I have a form, at first I didn't know how the get the data from the form,
then I found .serialize.
I have the following JavaScript:
$(document).ready(function() {
$("#submit").click(function blabla() {
var formData = $('form').serialize();
$.ajax({
type: "POST",
url: "/ArchiveSearch/Search",
dataType: "json",
data: formData,
});
});
});
The information comes from the following form:
<form method= post">
<div class="searchCiteria">
<div id="searchValueBlock1">
<div><span class="label">Case ID:</span><input type="text" name="messagecaseid" size="25"/></div>
<div><span class="label">Onderwerp:</span><input type="text" name="messagesubject" size="25" /></div>
<div><span class="label">Afzender:</span><input type="text" name="messagesender" size="25"/></div>
<div><span class="label">Ontvanger:</span><input type="text" name="messagereceiver" size="25"/></div>
</div>
<div id= "searchValueBlock2">
<div><span class="label">Datum:</span><input type="text" name="date1" size="25"/></div>
<div><span class="label"></span><input type="text" name="date2" size="25"/></div>
<div class="submit">
<input type="submit" value="Search">
</div>
</div>
</div>
</form>
When I use the action parameter in the form the servlet repondes like it should.
But I can't seem to get the Ajax call to work.
What am I doing wrong?
you must add the success param to ajax function
$.ajax({
type: "POST",
url: "/ArchiveSearch/Search",
dataType: "json",
data: formData,
success: function(data) {
$('.result').html(data);
alert('Load was performed.');
}
});
The default behavior of the submit button is to POST the form, which will redirect the user to a URL of the action attribute ond the form. When you don't(which you should...) have an action attribute it will reload the page. To prevent the page from reloading you need to prevent the default behavior by returning false at the end of your $("#submit").click function.
Basically i have a value from a database ($learner->idnumber)
I then have a form which posts using submithandler to process.php (this edits database)
Now this is the bit im stuck on, im trying to get the php db value $learner->idnumber to update without page refresh once the form has been processed.
I have found:
$("#pinnumber").load("profile.php #pinnumber");
but im not quite sure on how to implement this.
This is my code:
<a id="pinlink">edit</a>
<div id="results"><div>
<div id="pinnumber">
'.$learner->idnumber.'
<div>
<div id="pincontent" style="display:none;">
<form name="myform" id="myform" method="POST">
<input type="text" name="idnumber" id="idnumber" size="20" value=""/>
<input type="submit" name="submit" value="Update">
</form>
<div>
$(document).ready(function(){
$("#pinlink").click(function () {
$("#pincontent").show();
});
$("#myform").validate({
debug: false,
rules: {
idnumber: "required",
},
messages: {
idnumber: "Please enter your PIN",
},
submitHandler: function(form) {
$("#pincontent").hide();
// do other stuff for a valid form
$.post('process.php', $("#myform").serialize(), function(data) {
$('#results').html(data);
});
}
});
});
Any help would be greatly appreciated.
I included:
print "".$_POST['idnumber']."";
in process.php before the save to db code.
this then printed into:
<div id="results"><div>
when form was submitted.