jQuery Ajax Post keep adding username and password on the URL - javascript

I am using the Login Dialog as mentioned here on jQWidgets which I think is not the problem I am having and hence it shouldn't matter if someone has used it before or not for answering my question:
When testing the login functionality by putting login credentials, the username and password keep getting added on the URL of the page which I don't want. I am not sure why it's happening. Am I doing something wrong with the jQuery Ajax Post Webservice call?
Say for example, my home page URL of the webapp is : https://example.com/home.html
After entering loging credentials, it gets added to the URL for some reason like this:
https://example.com/home.html?username=myname&password=mypassword
Here is my HTML:
<!-- Login HTML Begins -->
<div id="wrap">
<div id="window" caption="Login">
<div>
<form >
<table>
<tr>
<td>Username:</td>
<td><input style="width: 150px;" type="text" name="user" id = "username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><input style="width: 150px;" type="password" name="password" id = "password" /></td>
</tr>
<tr>
<td colspan="2" align="right" valign="bottom">
<input type="submit" id="submit" value="Login" />
</td>
</tr>
</table>
</form>
</div>
</div>
<!-- Login HTML ends -->
Here is my Javascript Code:
<script type="text/javascript">
$(document).ready(function () {
$('#window').jqxWindow({ theme: "shinyblack", width: 250, height: 130, isModal: true });
$('#submit').jqxButton({ theme: "shinyblack" });
var loginUrl = "https://example.com:8443/Webservice/loginCheck"
$( "#submit" ).click(function() {
var userName = $("#username").val();
var passWord = $("#password").val();
var ajaxRequest = jQuery.ajax({
//beforeSend: TODO: show spinner!
data: {
username: userName,
passWord: passWord
},
dataType: "json",
method: "POST",
url: loginUrl
})
.done(function (data_, textStatus_, jqXHR_) {
// Validate the web service and retrieve the status.
if (typeof (data_) === "undefined" || data_ === null) { alert("Invalid data returned from LoginCheck Web Service"); return false; }
if (isEmpty(data_.webservice_status) || isEmpty(data_.webservice_status.status)) { alert("Invalid Web Service Status for LoginCheck Webservice!"); return false; }
if (data_.webservice_status.status != "SUCCESS") { alert(data_.webservice_status.message);
return false; }
})
.fail(function (jqXHR_, textStatus_, errorThrown_) {
alert("Hitting the Fail function : Error in LoginCheck webservice: " + errorThrown_);
return false;
});
}
});
</script>

The default protocol used by forms are GET so you need to override it using POST protocol
so you need something like this:
<form action="url" method="post">
..
..
..
</form>
also the embedded click function you should prevent some default by putting this code :
$("#submit").click(function(e){
e.preventDefault();
<!-- your statement !>
...
})
also the butto type :
<button type="button" id="submit"></button>
or
<input type="button" id="submit">

The way you've set it up, you're submitting the form data in the traditional way rather than via AJAX.
One option is to add:
$('form').on('submit',function(event){
event.preventDefault();
});
(A common error is to try to prevent form submission in a click handler attached to the submit button. There are a number of ways to submit a form and the submit button is only one of them.)
Another option is to just remove the form element.

Your form may be sending a get request, because you haven't prevented the default functionality of a form button. Try adding these two lines to your click handler:
$( "#submit" ).click(function(event) {
event.preventDefault();
event.stopPropagation();
}

Related

'undefined' data submited when using ajax

I'm using HTML form to send data to google sheet, it work great. But when i add ajax code, the data send to google sheet always is "undefined", remove the code it'll work but it show the code really ugly after that, so i want using ajax.
$(document).ready(function() {
var submit = $("button[type='submit']");
submit.click(function() {
var data = $('form#test-form').serialize();
$.ajax({
type: 'GET',
url: 'https://script.google.com/macros/s/AKfycby8PCL7hef6N35QAEe7CcGWEVLeONJfy8ATXIsM5Sn7icTDMw8/exec',
dataType: 'json',
crossDomain: true,
data: data,
success: function(data) {
if (data == 'false') {
alert('Oopps! Đã có lỗi. Quý khách hãy thử lại hoặc liên hệ trực tiếp qua hotline nhé.');
} else {
alert('Đã tiếp nhận thành công! Cát Tiên sẽ liên hệ lại trong thời gian sớm nhất. Cám ơn quý khách');
}
}
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="https://script.google.com/macros/s/AKfycby8PCL7hef6N35QAEe7CcGWEVLeONJfy8ATXIsM5Sn7icTDMw8/exec" method="GET">
<input type="text" name="SDT" id="ip2" placeholder=" SĐT hoặc Email">
<button type="submit" id="submit-form" class="button">Nhận</button>
</form>
<script type="text/javascript">
</script>
I don't know about code, all i using tutorial in web. Many thanks for your help.
You forgot to add an ID to your form.
Your script is trying to serialize the form with the id test-form with this function:
var data = $('form#test-form').serialize();
The form isn't found, because you forgot to add the id to the form.
Just replace your form's HTML with the following:
<form
id="test-form"
action="https://script.google.com/macros/s/AKfycby8PCL7hef6N35QAEe7CcGWEVLeONJfy8ATXIsM5Sn7icTDMw8/exec" method="GET">
<input type="text" name="SDT" id="ip2" placeholder=" SĐT hoặc Email">
<button type="submit"id="submit-form" class="button">Nhận</button>
</form>

Submit 2 forms with 1 button, form1 after form 2 is complete

I have the following problem:
2 forms that need to be submitted with one button. I will explain how it should work.
And of course my code so far.
#frmOne contains a url field where I need to copy the data from to my #frmTwo, this works.
(it forces the visitor to use www. and not http:// etc)
When I press 1 submit button
Verify fields #frmOne (only url works now, help needed on the others)
Call #frmTwo and show result in iframe. result shows progress bar (works)
But Div, modal or any other solution besides iframe are welcome.
Close #frmOne (does not work)
Finally process (submit) #frmOne if #frmTwo is done (does not work)
Process completed code of #frmTwo in iframe =
<div style='width' id='information'>Process completed</div>
<ol class="forms">
<iframe width="100%" height="50" name="formprogress" frameborder="0" scrolling="no" allowtransparency="true"></iframe>
<div id="txtMessage"></div>
</ol>
<div id="hide-on-submit">
<form id="frmOne" method="post">
<input type="text" name="company" id="company" >
<input type="text" name="url" id="url" >
<input type="text" name="phone" id="phone" >
<input type="text" name="occupation" id="occupation" >
<textarea rows="20" cols="30" name="summary" id="summary" >
<button type="submit" class="btn btn-danger">Submit</button>
</form>
</div>
<form id="frmTwo" method="post" target="formprogress"></form>
<script>
jQuery(document).ready(function(){
//Cache variables
var $frmOne = $('#frmOne'),
$frmTwo = $('#frmTwo'),
$txtMessage = $('#txtMessage'),
frmTwoAction = 'http://www.mydomainname.com/form.php?url=';
//Form 1 sumbit event
$frmOne.on('submit', function(event){
event.preventDefault();
var strUrl = $frmOne.find('#url').val();
//validation
if(strUrl === ''){
$txtMessage.html('<b>Missing Information: </b> Please enter a URL.');
}
else if(strUrl.substring(0,7) === 'http://'){
//Clear field
$frmOne.find('#url').val('');
$txtMessage.html('<b>http://</b> is not supported!');
}
else if(strUrl.substring(0,4) !== 'www.'){
//Clear field
$frmOne.find('#url').val('');
$txtMessage.html('<b>Invalid URL</b> Please enter a valid URL!');
}
else{
//set form action and submit form
$frmTwo.attr('action', frmTwoAction + strUrl).submit();
$('#hide-on-submit').hide(0).fadeIn(1000);
$('form#frmOne').submit(function(e) {
$(this).hide(1000);
return true; // let form one submit now!
}
return false;
});
});
</script>
read here https://api.jquery.com/jQuery.ajax/. basically you need to submit the first one with $.ajax and then, when you get the server response (in the success() function ) you need to send the second form, again width ajax().
Something like:
$form1.on('submit', function(e) {
e.preventDefault(); //don't send the form yet
$.ajax(
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize()
).success(function(data) {
alert('form one sent');
$.ajax(
url: $('#form2').attr('action'),
type: $('#form2').attr('method'),
data: $('#form2').serialize()
).success(function(data) {
alert('form two sent');
})
});
});
This code isn't ready to be copy/pasted, it's just to give you a guideline of how I would solve it. It's a big question, try going with this solution and come back with smaller question if you find yourself blocked.

Post Dynamic Inputs that are Appended with jQuery

I have found multiple questions that are the same, these include:
dynamically inserted form inputs aren't posted
jQuery not posting all inputs of a form after the .append()
Most problems are caused by opening the form within a table / div or some other problem with the HTML. I don't believe I have either of these problems; I suspect my javascript needs to be tweaked.
I am using jQuery as so:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
</head>
When the add link is clicked a new table row is appended to tbody.newRow
When clicking .remove, you are asked for confirmation. Upon confirmation the row is removed.
The form is submitted via ajax when input.Value loses focus.
jQuery:
$(document).ready(function() {
$(".add").on('click', function() {
$("tbody.newRow").append(
'<tr><td><input type="text" name="NewJobLeviesId[]" class="JobLeviesId" /><input type="text" name="NewValue[]" class="Value" /><input type="text" name="MasterId[]" class="Values" /><input type="text" name="LUPChoiceId[]" class="Values" /><input type="text" name="SortOrder[]" class="Values" /></td><td class="removeSelection">Remove</td></tr>'
);
});
$("tbody").on('click', '.remove', function() {
$(this).parent().append($(
'<div class="confirmation">YesNo</div>'
))
$(this).remove();
});
$("tbody").on('click', '.removeConfirm', function() {
$(this).parent().parent().parent().remove();
});
$("tbody").on('click', '.removeCancel', function() {
$(this).parent().parent().append(
'Remove');
$(this).parent().remove();
});
var formTwo = $('.ajaxTwo'); // contact form
// form submit event
$(".Value").blur(function() {
$.ajax({
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: formTwo.serialize(), // serialize form data
success: function(data) {
url: 'functions.php'; // form action url
},
error: function(e) {
console.log(e)
}
});
});
});
The html form. The ajax works wonderfully with the existing row that is not added dynamically. The add row is located in the table footer looking pretty. The form is posted as an array.
<form class="ajaxTwo" method="post">
<table>
<tbody class="newRow">
<tr>
<td>
<input type="text" name="NewJobLeviesId[]" class="JobLeviesId" />
<input type="text" name="NewValue[]" class="Value" />
<input type="text" name="MasterId[]" class="Values" />
<input type="text" name="LUPChoiceId[]" class="Values" />
<input type="text" name="SortOrder[]" class="Values" />
</td>
<td class="removeSelection">
Remove
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
Add Row
</td>
</tr>
</tfoot>
</table>
</form>
Finally the php. Each row is inserted into my database table with a PDO prepared statement.
if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
if(isset($_POST['NewJobLeviesId'])) {
for($i=0; $i<count($_POST['NewJobLeviesId']); $i++) {
$NewJobLeviesId = $_POST['NewJobLeviesId'][$i];
$NewValue = $_POST['NewValue'][$i];
$MasterId = $_POST['MasterId'][$i];
$LUPChoiceId = $_POST['LUPChoiceId'][$i];
$SortOrder = $_POST['SortOrder'][$i];
$sql = "INSERT INTO joblevies (JobLeviesId,Value,MasterId,LUPChoiceId,SortOrder) VALUES (:JobLeviesId,:Value,:MasterId,:LUPChoiceId,:SortOrder)";
$q = $db->prepare($sql);
$q->execute(array(':JobLeviesId'=>($NewJobLeviesId),':Value'=>($NewValue),':MasterId'=>($MasterId),':LUPChoiceId'=>($LUPChoiceId),':SortOrder'=>($SortOrder)));
}
}
}
Again, this works wonderfully well. Only the dynamically added inputs have a problem. What am I missing?
The dynamically created dom elements don't have any of the events that you attach on $(document).ready(... because they didn't yet exist when you were attaching events. So the $('.Value').blur(... stuff is only attached to the first form, and not any future ones. So attach the event every time you create a new row, so maybe something like this:
First, delegate the binding action to its own function
function attachSubmitEvent() {
// form submit event
//remove old events first
$(".Value").off();
$(".Value").blur(function () {
var formTwo = $('.ajaxTwo'); // contact form
$.ajax({
type: 'POST', // form submit method get/post
dataType: 'html', // request type html/json/xml
data: formTwo.serialize(), // serialize form data
success: function (data) {
url: 'functions.php'; // form action url
},
error: function (e) {
console.log(e)
}
});
});
}
then in your document.ready, call that function
attachSubmitEvent();
then, to make sure they are also attached to the new elements, call it again when creating new elements
$(".add").on('click', function () {
$("tbody.newRow").append('<tr><td><input type="text" name="NewJobLeviesId[]" class="JobLeviesId" /><input type="text" name="NewValue[]" class="Value" /><input type="text" name="MasterId[]" class="Values" /><input type="text" name="LUPChoiceId[]" class="Values" /><input type="text" name="SortOrder[]" class="Values" /></td><td class="removeSelection">Remove</td></tr>');
attachSubmitEvent(); //now everyone has the event attached.
});
For your form submit event, try:
$("tbody").on('focusout', '.Value', function() {
...
});
You could also use blur in this event handler, but the documentation recommends using focusout for clarity (See 'Additional Notes' section of jQuery on() method documentation: http://api.jquery.com/on/)

Stop 2 Instances of an Ajax form on the same page interfering with each other

I've the following form twice on my homepage:
<form id="get-consultation-form" action="javascript:alert('success!');" >
<h3 class="sub-heading">Book a Consultation</h3>
<div id="message"></div>
<div id="fields">
<input type="text" maxlength="" name="Consultation[name]" placeholder="NAME" />
<input type="text" maxlength="" name="Consultation[number]" placeholder="NUMBER" />
<input type="text" maxlength="" name="Consultation[email]" placeholder="EMAIL" />
<button type="submit" class="btn">Submit</button>
</div>
</form>
The form uses jQuery/Ajax/PHP to forward the data via email:
$(document).ready(function() {
$("#get-consultation-form").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "http://novicecoder.co.uk/priestley/consultation-process.php",
data: str,
success: function(msg) {
$(document).ajaxComplete(function(event, request, settings) {
NProgress.set(0.0);
if (msg === 'OK') {
result = '<div class="thanks" id="thanks">Thank you, we will contact you <span>shortly.</span></div>';
$(this).find("#fields").hide();
NProgress.set(0.5);
$("#message").hide();
$("#message").html(result).slideDown(100);
$("#message").html(result);
}
else
{
result = msg;
$("#message").hide();
$("#message").html(result).slideDown(200);
$("#message").html(result);
}
NProgress.set(1.0);
});
}
});
return false;
});
});
The first form is working perfectly, however as you'll see in my working example, the 2nd is not:
My website
Any ideas why this is happening????
IDs are unique.
Try to change form elements to diferent ids.
Or instead use classes.
If you use classes you can use $('.messages-class').closest() inside the form submit() for only interact in the current form.
You can't have an element with the same ID on a page twice. Replace your #get-consultation-form ID with a class, that should solve your issue. This also applies to the elements within the form like #fields and #message.

ajax call with html form won't work properly

I'm stuck.
It's like the script doesn't have any function at all.
<script>
$("#continue").click(function () {
$.ajax({
type: "POST",
url: "dbc.php?check=First",
data: {full_name : $('#full_name').val()
usr_email : $('#usr_email').val()},
success: function(msg){
if(msg==1){
$("#First_1").hide();
$("#Next_2").toggle();
}else{
alert(msg)
}
}
});
return false;
});
</script>
<form action="index.php?page=checkin" method="post" name="regForm">
<div id="First_1">
<table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td>
<table cellpadding="0" cellspacing="5">
<tr>
<td style="padding: 5px;">
Fullständiga namn:
</td>
<td>
<input name="full_name" type="text" id="full_name" class="required">
</td>
</tr>
<tr>
<td style="padding: 5px;">
Email:
</td>
<td>
<input name="usr_email" type="text" id="usr_email" class="required email">
</td>
</tr>
<tr>
<td style="padding: 5px;">
Sex:
</td>
<td>
<select name="sex">
<option value="male">Kille</option>
<option value="female">Tjej</option>
</select>
</td>
</tr>
<td>
<input type="submit" id="continue" value="Continue">
</td>
</table>
</td>
</tr>
</table>
</div>
With this when i press continue it should send ajax call, but it doesn't. When i press Continue it just takes me to the form´s action="index.php?page=checkin", even if theres return false; on click(in the script)? I even tried to change the form line and inserted onsubmit="return false;" but then nothing happens at all when i click on the button.
The problem is it's doing the default action, because none of your jQuery code is running :) When your code runs, the id="continue" element isn't there yet, so $("#continue") doesn't find anything to bind a click handler to. It's an easy fix, wrap your code in a document.ready call, like this:
$(function() {
$("#continue").click(function () {
$.ajax({
type: "POST",
url: "dbc.php?check=First",
data: {full_name : $('#full_name').val()
usr_email : $('#usr_email').val()},
success: function(msg){
if(msg==1){
$("#First_1").hide();
$("#Next_2").toggle();
}else{
alert(msg)
}
}
});
return false;
});
});
By doing this it'll wait until the DOM is ready, and your elements are there to find/bind to. Also instead of attaching to the #continue button's click event, it's usually better to attach to the form's submit handler, so it's caught there, so instead of this:
$("#continue").click(function () {
You would do this:
$("form[name='regForm']").submit(function() {
With everything else staying the same.
Sounds to me like a typo and it looks like in your data field.
I would suggest doing
data: "value1="+$("#val1").val()+"&value2="+$("#val2").val()
Also a good way to debug javascript is to open up chrome's console or in firefox use firebugs console and when you perform the action it will usually inform you of a problem or lack thereof.
One last note: I would suggest using json in your return from php, this way you can provide user with a more catered message. For example, lets say your form doesnt validate server side (you are validating server side right?) you can return to client a nice message explaining to them waht did not validate. How to do this?
$.ajax({
type: "POST",
url: "dbc.php",
data: "val1="+$(#val1).val()+"&val2="+$(#val2).val(),
success: function(json){
if(json.error){
//notify user of error message
$(#statusDiv).(json.message);
}else{
//perform success
}
}
});
And on the server side to use something such as
echo json_encode(array("error"=>1, "message"=>"<insert validation problems here>"));
This will on success function have access via json.error, or json.message.
In your new code on phpbin you need a comma after the line:
data: "full_name="+$("#full_name").val()+"&usr_email="+$("#usr_email").val(), // <-- COMMA HERE
Or, in your old code (which is nicer since you don't have to deal with concatenating the data url yourself), you were missing a comma also, between the two lines:
data: {full_name : $('#full_name').val(), // <-- COMMA HERE
usr_email : $('#usr_email').val()},
ALSO, you need a semicolon after this line:
alert(msg); // <-- SEMICOLON HERE
;)

Categories