EDIT: url is culprit I think. In working login.html case I got in log:
FINE: Security checking request POST /SesamaMaven/protected/admin/j_security_check
And in AJAX-version I got:
FINE: Security checking request POST /SesamaMaven/
I configured authentication in Glassfish with JDBCRealm and it seems to be working with normal login.html like that:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Login Form</title>
</head>
<body>
<form method="post" action="j_security_check">
<p>You need to log in to access protected information.</p>
<table>
<tr>
<td>User name:</td>
<td><input type="text" name="j_username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input type="password" name="j_password" /></td>
</tr>
</table>
<p><input type="submit" value="Login" /></p>
</form>
</body>
</html>
My problem is that when I try to implement same with AJAX, it is not working. Is there any possibility to get that working?
HTML
<form class="navbar-form pull-right">
<input class="span2" type="text" placeholder="Email" name="j_username" id="username">
<input class="span2" type="password" placeholder="Password" name="j_password" id="password">
<button type="button" class="btn" id="btnSignIn">Sign in</button>
</form>
JS
$('#btnSignIn').click(function() {
$.ajax({
type: "POST",
contentType: "application/text",
url: "j_security_check",
// This is the type what you are waiting back from the server
dataType: "text",
async: false,
crossDomain: false,
data: {
j_username: "admin",
j_password: "paSSWORD"
},
success: function(data, textStatus, xhr) {
alert('Thanks for your signin in! ' + xhr.status);
window.location = "/SesamaMaven/protected/adminWelcome.html";
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
window.location = "/SesamaMaven/index.html";
alert(' Error in signIn-process!! ' + textStatus);
}
});
});
QUESTIONS
1) What is the correct contentType: "application/text"?
2) Is the URL tag correct one or should I use action?
3) How about parameters username and password in case like that?
Glassfish tries to authenticate but there is no user and password.
contentType: "application/text" is the culprit. I just commented that line out and everything started to work.
One problem there still is. When there is an error in authentication, it does redirect to index.html but there is no css and the address bar includes the address where it should go in succeeded case /protected/adminWelcome.html.
I add those code in login.html file.
On development process, I feel lazy to type username and password
xhttp.open("POST", "j_security_check", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("j_username=MY_USERNAME&j_password=MY_PASSWORD");
location.reload(true);
It seems that, you are try to infor user when they input wrong credential.
In my case, I have login.html and error-login.html exactly the same,
except the error-login.html has a text "You are input wrong password or username"
Related
Previously I have some code like this to send a message to the user
<button class="notif btn btn-success"
href="https://api.telegram.org/bot{{ config('app.token') }}/sendMessage?chat_id={{ $rp->report_idsender }}&text=Halo%20{{ $rp->sender_name }}%20permintaan%20anda%20dengan%20id%20{{ $rp->id }}%20sudah%20di%20close%20">Notif</button>
and I am using jquery & js to get URL from href and execute HTTPS post request it works perfectly for me
<script type="text/javascript">
$(".notif").unbind().click(function() {
var url = $(this).attr("href");
console.log(url);
var exe = $.post(url, function() {
alert('Success');
})
});
</script>
But now I want to send a photo to a group on Telegram with reply id and the codes looks like this:
<form method="POST"
action="https://api.telegram.org/bot{{ config('app.token') }}/sendPhoto" enctype="multipart/form-data">
<input type="text" name="chat_id" value="{{ config('app.idgroup') }}" hidden />
<input type="text" name="reply_to_message_id" value="{{ $rp->msg_id }}" hidden />
<input type="text" name="allow_sending_without_reply" value="true" hidden />
<br />
<label for="caption"> Caption</label>
<input type="text" name="caption" placeholder="caption" />
<br />
<input type="file" name="photo" />
<br />
<input type="submit" value="sendPhoto" />
</form>
The problem with this code is that after I submit the form it's opening a page that contains the JSON response whereas I just want to alert it as I did in the previous code.
json response tab picture
The question is, how can I send a photo with the form with telegram bot using js/jquery with reply id in the URL ??
Your code is working fine, but redirecting to page as set in action, you can use following code to prevent default submit button behavior and ajax to stay on the same page and display success message.
<script type="text/javascript">
$(document).on("submit", "form", function (event) {
event.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: $(this).attr("method"),
dataType: "JSON",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status) {
alert('Success');
},
error: function (xhr, desc, err) {
alert('Error');
}
});
});
</script>
Add this code on head section of your page.
I'm trying to create a simple login feature for my website. I'm using JAVA as backend and I'm trying to use restservices. My school gave me an example of a login system with authication. Unfortunately I'm getting this error: java.lang.IllegalStateException: The #FormParam is utilized when the content type of the request entity is not application/x-www-form-urlencoded].
#POST
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response authenticateUser(#FormParam("username") String username,
#FormParam("password") String password) {
<form id='inlogForm' enctype="application/x-www-form-urlencoded" >
<input type='text' placeholder='username' id='username' />
<input type='text' placeholder='password' id='password' />
<input type='button' value='login' id='login' />
</form>
</header>
</body>
<script src="https://code.jquery.com/jquery-3.2.0.min.js"></script>
<script>
$("#login").click(function(event) {
var data = $("#loginForm").serialize();
$.post("restservices/authentication", data, function(response) {
window.sessionStorage.setItem("sessionToken", response);
$("#loginForm").hide();
}).fail(function(jqHXR, textStatus, errorThrown) {
console.log(textStatus);
console.log(errorThrown);
alert("Wrong Username/Password")
});
});
From the looks of it, you should be using #FormDataParam instead of #FormParam.
I found it here: https://groups.google.com/forum/#!topic/dropwizard-user/bYyG-Pvk29Y, but still don't quite understand the reasoning.
I'm trying to make user registration process via ajax in laravel. But I'm unable to do that.
Routes
Route::get('/register', 'Auth\AuthController#getRegister')->name('register');
Route::post('/register', 'Auth\AuthController#postRegister')->name('postRegister');
HTML form
<form action="{{ route('postRegister') }}" method="POST" id="registerForm">
<h4>REGISTER NOW</h4>
<hr><br>
<input type="text" name="name" class="form-control" placeholder="Name">
<br>
<input type="number" name="student_id" class="form-control" placeholder="Student ID">
<br>
<input type="email" name="email" class="form-control" placeholder="Email address">
<br>
<input type="number" name="phone" class="form-control" placeholder="Phone no">
<br>
<input type="password" name="password" id="password" class="form-control" placeholder="Choose password">
<br>
<input type="password" name="password_confirmation" class="form-control" placeholder="Confirm password">
<br>
<div class="row">
<div class="col-md-12 text-right">
<button type="submit" class="mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect" id="registerButton"><span id="regLoader" style="display: none"><i class="fa fa-spinner fa-pulse"></i><span class="sr-only">Loading...</span> </span>
Register</button>
</div>
</div>
{{ csrf_field() }}
</form>
JS
$('#registerForm').submit(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '/register',
data: $(this).serialize(),
dataType: 'json',
success: function(data){
},
error: function(data){
}
});
});
I think you need to change your code like:
jQuery(function($) {
$('#registerForm').submit(function(e){
e.preventDefault();
$.ajax({
url: $form.attr('action'),
data: $(this).serialize(),
dataType: 'json',
success: function(data){
},
error: function(data){
}
});
});
});
Your code looks perfect.
1) Maybe some form validation goes failed and which prevents data to be stored in the database.
Comment out your server side validations(if you have) and check again.
2) If this didn't work, comment out dataType: 'json' in AJAX and check again.
Also, print console.log() in your success method of ajax to troubleshoot.
If none of it work, show your controller code.
Thanks
1) Can you able to see the xmlhttp request passing to the server through network tab of chrome/mozilla.
If so there is no error in your ajax/front end,
2) Before going to route write a anonymous function in the action route to see whether the request comes till the route
Route::post('/register', function(Illuminate\Http\Request, $request) {
dd($request);
});
If You have Auth Routes enabled then there is a possibility
for the request to point RegistrationController inside Auth folder, do a
dd($request) inside the constructor of that controller. hence you can figure it out whether the request is coming there.
3) Try regenerating the APP key (It is just a try if nothing works)
4) Try writing a new post route and call that route in ajax to post the data to the server,if that works the old route which you wrote may overridden by some other route.
Try in the above order , you will somewhere catch the error.
I'm trying to submit a form using PHP and Ajax. But the problem is that sometimes it inserts one value, sometimes 2, sometimes all, and now it is inserting nothing. Why is it happening? How can I correct it?
Here's my code:
Ajax
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: "submitform.php",
type: "POST",
data: $("form").serialize(),
success: function(data){
alert("well");
},
error: function(){
alert("Error");
}
});
});
});
HTML
<form id="signupform" name="form1" method="post" enctype="multipart/form-data">
<table>
<tr>
<td><input type="text" name="name" placeholder="Enter your name" required /></td>
<td rowspan="3"><div class="propic"><img id="imgid" src="images/dp.png" /></div>
<input id="imgInput" type="file" name="image"/></td>
</tr>
<tr>
<td><input type="text" name="username" placeholder="Enter username" required /></td>
</tr>
<tr>
<td><input id="digits" type="text" name="phone" maxlength="10" placeholder="Enter your phone no." required /></td>
</tr>
<tr>
<td><input type="password" name="password" maxlength="12" placeholder="Enter password" required /></td>
<td><input id="button" type="submit" name="submit" value="Sign Up" /></td>
</tr>
</table>
</form>
PHP
<?php
$conn=mysqli_connect("localhost", "root", "", "winkcage");
//$im=$_SESSION["pathsession"];
$nam=""; $usernam=""; $phon=""; $pass="";
$nam=$_POST["name"];
$usernam=$_POST["username"];
$phon=$_POST["phone"];
$pass=$_POST["password"];
$signquery="INSERT INTO signup(name, username, phone, password) VALUES('$nam', '$usernam', '$phon', '$pass')";
$signqueryrun=mysqli_query($conn, $signquery);
?>
NOTE: I don't want to insert image value right now. I'll insert it later when this problem is fixed.
You may have entered a ' quote and it killed your sql statement. This is called sql injection. To prevent sql injection you can use pdo prepared statements. You will also want to hash passwords to prevent people from stealling them if they get access to your database. Hashing password is a one way encryption that is easy to check.
$pdo = new PDO("mysql:host=$db_host;dbname=$DB_name", $user, $pass);
$sql = "INSERT INTO signup(name, username, phone, password) VALUES(':name', ':username', ':phone', ':pass')";
if ($con = $pdo->prepare($sql)) {
$con->execute([
':name' => $_POST["name"],
':username' => $_POST["username"],
':phone' => $_POST["username"],
':pass' => $_POST["password"]
]);
}
As far as the html and javascript goes. Catch the submitted form with jquerys .submit() function.
$('form').submit(function(e){
e.preventDefault();
$.post('submit.php',$(this).serialize(),function(response){
alert('complete');
}).error(function(){
alert('wrong');
});
});
This makes sure than any submit event triggers the ajax.
Since you are using a form with a submit button, when you click the button it will submit the form. You may be having a conflict between the AJAX action and the form submit. Try preventing the default action on the button click and see if it works as follows:
$(document).ready(function(){
$("#button").click(function(event){
if($("form").get()[0].checkValidity()){
$.ajax({
url: "submitform.php",
type: "POST",
data: $("form").serialize(),
success: function(data){
alert("well");
},
error: function(){
alert("Error");
}
});
});
}
event.preventDefault();
});
You assign your onclick to a button element, but there is no button element on your page, your button is an input element. Change that to a button and it may work. I personally would advise using ids, rather than element types, I think it makes things clearer, and will allow you to have more than one element of the same type without breaking your code.
Change
$("button").click(function(){
to
$("#button").click(function(){
and
data: $("form").serialize(),
to
data: $("#signupform").serialize(),
I am using Jquery 1.7.1 and am having issues.. I'm working with a CRM in my script and am working to get the page finished but I'm stuck with this issue..
my html:
<form class="collector" action="https://www.domain.biz/admin/transact.php" method="POST">
<input type="hidden" name="method" value="NewProspect">
<input type="hidden" name="campaignId" value="3">
<input type="hidden" name="ipAddress" value="<?php echo $_SERVER['REMOTE_ADDR']; ?>">
<fieldset>
<div style=" padding-left: 50px">
<table>
<tr>
<td><span style="color:red;">*</span>Your First Name:
<span id="rfvFirstName" style="display:none;">*</span>
</td>
<td><span style="color:red;">*</span>Your Last Name:
<span id="rfvFirstName" style="display:none;">*</span>
</td>
<td><span style="color:red;">*</span>Your Phone Number: </td>
<td><span style="color:red;">*</span>Primary Email: </td>
</tr>
<tr>
<td>
<input name="firstName" type="text" id="firstName" style="width:150px;" value="">
</td>
<td>
<input name="lastName" type="text" id="lastName" style="width:150px;" value="">
</td>
<td>
<input name="phone" type="text" id="phone" class="" style="width:150px;" value="">
</td>
<td>
<input name="email" type="text" id="email" class="required email" style="width:150px;" value="">
</td>
</tr>
</table>
</div>
<div class="clear"></div>
<center>
<input type="submit" name="continue" id="imgbtnSubmit" class="button" style="background-image: url('<?php echo base_url();?>inc/img/button-check.png');
background-repeat: no-repeat; width: 348px; height: 46px; border:none; background-color:transparent;" value="" />
</center>
</fieldset>
<p align="center" style="font-size:12px;">
</p>
</form>
the JS:
$('.collector').submit(function(){
validate = true;
$(this).find("input:text:visible:enabled").each(function() {
if ($(this).attr("value") == "") {
alert("Please fill in all fields!");
$(this).focus();
validate = false;
return false;
}
else if ($(this).hasClass("email") && !$(this).attr("value").match(/#/)) {
alert("Please enter an email address...");
$(this).focus();
validate = false;
return false;
}
});
if (validate != false) {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data: $(this).serialize(),
success: function(response) {
alert(response);
}
});
}
return false;
});
Now both of these things work, and they work together fine... the issue comes in that I don't get any response and I'm not sure why. I imagine it is because of what firebug is saying... POST https://www.domain.biz/admin/transact.php 200 OK 1.04s jquery.js (line 8102)
This line in my firebug is displayed as red, and the line 8102 in jquery.js is: xhr.send( ( s.hasContent && s.data ) || null );
Here are some suggestions that might help you find the error:
In your ajax call, after the success, add the following code:
success: function(response) {
alert(response);
},
error: function(response) {
console.log(response.status + " " + response.statusText);
}
That will print in your console a clue to what is causing this error.
By the way, there are some other suggestions, your validations can be achieved with the new HTML5 input types (email, phone), if you have to maintain compatibility with browsers that don't support these, you can find a jQuery plugin that handles this.
Do you make an cross domain ajax request ? I downloaded your code and make a simple test:
Code in
localhost:8080/domain1/a.php
Make a ajax request to
localhost:8080/domain2/b.php
Error happens
Code in
localhost:8080/domain1/a.php
Make a ajax request to the page itself
(localhost:8080/domain1/a.php)
No error happens and get the expected response.
Then I googled the answer for [jquery.ajax cross domain request],and find some links may helps:
jQuery AJAX cross domain
Soluation is : dataType: 'JSONP'
$.ajax({
url:"testserver.php",
dataType: 'JSONP', // Notice! JSONP <-- P
success:function(json){
// do stuff with json (in this case an array)
alert("Success");
},
error:function(){
alert("Error");
},
});
I'm not sure about using $(this).serialize(). Have you tried using $('.collector').serialize() (or whichever the form is) since inside the ajax request the context may change. It's just a quick guess, hope it helps.
The same thing happened to me.And I used the same version of JQuery (1.7.1)
And the weirdest thing is that after adding "asyn:false ",it worked out.
I guess this might be a bug of JQuery.