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.
Related
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(),
as title suggests, I am having issues running my script:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#subbut").click(function(e){
e.preventDefault();
$.ajax(
{
url : 'http://jsonplaceholder.typicode.com/users?email=Sincere#april.biz',
method : 'GET'
})
.then(
function(data) {
document.getElementById("street").value = data[0].address.street;
});
});
});
</script>
And my form is here:
<form id="myForm"
action="<%=response.encodeURL(request.getContextPath()
+ "/upisKorisnika.html")%>"
method="POST">
<table id='userInput' class="display" border="0"
style="font-family: Arial; font-size: 18px;">
<tr>
<td><c:out value="E-mail: " /></td>
<td><input type="text" name="email" id="email"></td>
</tr>
<tr>
<td colspan="2" style="text-align: center">
<input type="submit" name="subbut" class="btn btn-default" id="subbut" value="Submit">
</td>
</tr>
</table>
<input type="hidden" id="street" name="street" />
</form>
My first question is why doesn't anything happen when I click submit, what am I doing wrong?
And I would also like to know how could I get value of text field "Email", so I could use something like this:
url : 'http://jsonplaceholder.typicode.com/users?email='+mail,
First, is confusing the use of a form that not send data to the server and a submit button without submit form behavior.
Second you need use a debug tool like chrome developer tool. It will give you the trace of your calls.
To debug, add to the promise.then the error callback with a simple alert or a console.log to view what is happen with your call.
And responding your question,your code seen be right.
Background: jQuery mobile phonegap build multipage-ajaxload sisyphus enabled form with a ajax POST loop to a GUI database. There are 171 section posts, plus 1 summary post to a different table. (This data should probably be one post with the backend handling the logic, unfortunately I don't have the access or the time to fix this on the backend). About 80% of the time, this function does post 171 intended sections (plus the 1 summary post). However 20% of the time, there are 6 duplicate posts for a total of 177 posts. I've tried async:false, but there was a significant hit in performance.
Why are there 6 random duplicate posts roughly 20% of the time?
What is the best way to fix this ajax post loop so that there is not any skipped post or any duplicate post?
HTML Submit Section:
<form id="submit_section" encoding="multipart/form-data" encType="multipart/form-data">
<br>
<input type=hidden name=fform value=1>
<input type="hidden" name="_fid_40" id="_fid_40" value="" />
<input type="hidden" name="_fid_48" id="_fid_48" value="" />
<input type="hidden" name="_fid_6" id="uniquetoktok" value="" />
<input type="hidden" name="sentstatus" id="sentstatus" value="" />
<input type="text" placeholder="ID" required name="_fid_8" id="thisId" />
<input type="hidden" required name="_fid_7" required />
<input type="text" placeholder="Your First & Last Name" required name="_fid_7" disabled="disabled"/>
<ul id="suggestions" data-role="listview" data-inset="true"></ul>
<input name="_fid_41" id="_fid_41" type="hidden" required>
<div class="custom-select">
<select name="_fid_41" type="text" required disabled="disabled">
<option value=""></option>
<option value="locationOne">locationOne</option>
<option value="locationTwo">locationTwo</option>
<option value="locationThree">locationThree</option>
<option value="locationFour">locationFour</option>
<option value="locationFive">locationFive</option>
</select>
</div>
<div id="notyetsent">
Submit Site Walk
</div>
<div id="alreadysent">
<span style="color:red;"><center>* This form has already been sent.</center></span><br>
<a data-icon="plus" data-role="button" data-theme="b" href="#" class="photobutton" id="morephotos" rel="external">Add Photos</a>
</div>
</form>
HTML Form Format:
<form id="check-2" encoding="multipart/form-data" encType="multipart/form-data">
<div class="sendsendsend">
<h4 style="display:none;">C1:</h4>
<input type="hidden" name="_fid_14_C1" />
<textarea style="display:none;" name="_fid_15_C1" /></textarea>
</div>
<div class="sendsendsend">
<h4 style="display:none;">C2:</h4>
<input type="hidden" name="_fid_14_C2" />
<textarea style="display:none;" name="_fid_15_C2" /></textarea>
</div>
<div class="sendsendsend">
<h4 style="display:none;">C3:</h4>
<input type="hidden" name="_fid_14_C3" />
<textarea style="display:none;" name="_fid_15_C3" /></textarea>
</div>
</form> ... 168 more '.sendsendsends' ...
jQuery Ajax 171 Post Loop:
var totalRequests = 0;
var totalSuccess = 0;
var totalError = 0;
// Serialize #submit_section data and set to var formData to inject in sendsendsend loop
var formData = $('#submit_section').find("input, select").serialize();
// Posts each .sendsendsend divs (171 in total)
$('.sendsendsend').each(function() {
var taskOrderData = $(this).find("input, textarea").serialize();
var h4String = $(this).children('h4').html();
var colonPosition = h4String.indexOf(':');
var taskOrderId = h4String.substr(0, colonPosition);
var postData = taskOrderData + '&' + formData + '&_fid_25=' + taskOrderId;
$.ajax({
type: 'POST',
url: 'url',
data: postData
}).done(function(data, textStatus, jqXHR) {
totalSuccess++;
}).fail(function(jqXHR, textStatus, errorThrown) {
totalError++;
}).always(function(a, textStatus, b) {
totalRequests++;
if (totalRequests >= 171) {
if (totalError >= 1) {
$("#sentstatus").val("failed");
$.mobile.changePage('#failpop', {
transition: 'pop',
role: 'dialog'
})
}
if (totalSuccess >= 171) {
summaryPost();
}
}
});
function summaryPost() {
$.ajax({
type: 'POST',
url: 'url',
data: formData
}).done(function(data, textStatus, jqXHR) {
totalSuccess++;
}).fail(function(jqXHR, textStatus, errorThrown) {
totalError++;
}).always(function(a, textStatus, b) {
totalRequests++;
if (totalRequests >= 172) {
if (totalError >= 1) {
$('.senderbutton').show();
$("#sentstatus").val("failed");
$.mobile.changePage('#failpop', {
transition: 'pop',
role: 'dialog'
})
};
if (totalSuccess >= 172) {
$("#sentstatus").val("yes");
$.mobile.changePage('#successpop', {
transition: 'pop',
role: 'dialog'
});
};
};
});
};
})
It's a challenge just trying to replicate this issue on a mobile device. Any advice or suggestions would be wonderful!
Edit: Forgot to include the "Submit_Section"
Apparently unrelated code wrapping your HTML form could be stimulating this behaviour.
In particular, if you have empty SRC or URL values, this can result in multiple page requests. One quick way to see if this is the case is to deliberately add an element with one of these mis-set values to your code and see if the incidence of multiple posts increased.
This can also be caused by these values being set inappropriately in your CSS definitions.
This is by design on some browsers; there's one request you ask for explicitly, and another that the browser itself kicks off as part of the process to try to resolve those empty values.
I got bitten by this a while back in a classic ASP application stack and it results in bizarrely chaotic behaviour when requesting / paging through results.
I've posted on here previously, however, the answers received were of no help as they did not work.
I have a form that is using AJAX but the error or success messages don't appear.
Can anyone see what I may have overlooked? Thanks.
HTML
<form id="newsletter" action="http://app.bronto.com/public/webform/process/" method="post">
<input type="hidden" name="fid" value="gmy3v1ej883x2lffibqv869a2e3j9" />
<input type="hidden" name="sid" value="37ea72cebcc05140e157208f6435c81b" />
<input type="hidden" name="delid" value="" />
<input type="hidden" name="subid" value="" />
<script type="text/javascript">
var fieldMaps = {};
</script>
<label for="nameField">Name:</label>
<input id="nameField" type="text" id="field_66663" name="39829[66663]" value="" />
<label for="emailField">Email:</label>
<input id="emailField" type="text" name="39821" value="" />
<input type="submit" value="Submit" />
<div id="newsletter-message" style="display:none;"></div>
</form>
JS
//ajax subscribe
$(document).ready(function(){
$("#newsletter").submit(function(event) {
event.preventDefault();
alert("submitting");
alert(data); //it doesn't alert here??
console.log($("#newsletter").serialize());
$.post($("#newsletter").attr("action"), $("#newsletter").serialize(), function(data){
alert(data); //doesn't alert here either
if(data == 'success'){
$('#newsletter-message').html('You have been signed up.').removeClass('error').css('visibility','visible');
} else {
$('#newsletter-message').html('Please complete the fields and re-submit').addClass('error').css('visibility','visible');
}
});
//Stop the normal POST
return false;
});
});
EDIT
I've now tried this but still no luck..
$("#newsletter").submit(function(event) {
event.preventDefault();
var $form = $( this ),
ufname = $form.find( 'input[name="39829[66663]"]' ).val(),
uemail = $form.find( 'input[name="39821"]' ).val(),
url = $form.attr( 'action' );
var posting = $.post( url, { name: ufname, email: uemail } );
posting.done(function( data ) {
$('#newsletter-message').html('You have been signed up.').removeClass('error').css('visibility','visible');
});
});
The visibility and display are 2 different things in CSS.
You are creating your display div with display:none;, but then you try to make it visible with .css('visibility','visible');, so you just end up with:
<div style="display: none; visibility: visible;" id="newsletter-message">...</div>
Which is still not visible because of the display:none;.
You should replace the actions in your if by:
if(data == 'success'){
$('#newsletter-message').html('You have been signed up.').removeClass('error').show();
} else {
$('#newsletter-message').html('Please complete the fields and re-submit').addClass('error').show();
}
Here is the documentation about the .show() jQuery function: http://api.jquery.com/show/
Small thing i noticed, you are using 2 id attribute for name field which makes your input invalid and may cause the problem.
<input id="nameField" type="text" id="field_66663" name="39829[66663]" value="" />
Also do as #Thierry said and avoid using numbers in name field if possible.
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"