This question already has answers here:
Javascript POST not working - Sending Javascript array to PHP
(4 answers)
Closed 4 years ago.
I have a form and I want it to be send to my email. This is my HTML script with the form:
<form id="contact-form" class="contact-form style-2">
<div class="form-row">
<div class="form-col-2">
<input type="text" name="cf-name" placeholder="Naam*">
</div>
<div class="form-col-2">
<input type="text" name="cf-email" placeholder="Email*">
</div>
</div>
<div class="form-row">
<div class="form-col-2">
<input type="tel" name="cf-phone" placeholder="Telefoonnummer">
</div>
<div class="form-row">
<div class="form-col">
<textarea name="cf-message" rows="2" placeholder="Vragen/verzoeken"></textarea>
</div>
</div>
<button type="submit" class="btn style-3" data-type="submit">Verzend</button>
<p class="text-size-small2">Velden met een * zijn vereist.</p>
</form>
I want to make use of AJAX and this is my script.
if ($('#contact-form').length) {
var cf = $('#contact-form');
cf.append('<div class="message-container"></div>');
cf.on("submit", function (event) {
var self = $(this),
text;
var request = $.ajax({
url: "bat/mail.php",
type: "post",
data: self.serialize()
});
request.then(function (data) {
if (data == "1") {
text = "Your message has been sent successfully!";
cf.find('input:not([type="submit"]),textarea').val('');
$('.message-container').html('<div class="alert-box success"><i class="icon-smile"></i><p>' + text + '</p></div>')
.delay(150)
.slideDown(300)
.delay(4000)
.slideUp(300, function () {
$(this).html("");
});
} else {
if (cf.find('textarea').val().length < 10) {
text = "Message must contain at least 10 characters!"
}
if (cf.find('input').val() == "") {
text = "All required fields must be filled!";
}
$('.message-container').html('<div class="alert-box error"><i class="icon-warning"></i><p>' + text + '</p></div>')
.delay(150)
.slideDown(300)
.delay(4000)
.slideUp(300, function () {
$(this).html("");
});
}
}, function () {
$('.message-container').html('<div class="alert-box error"><i class="icon-warning"></i><p>Connection to server failed!</p></div>')
.delay(150)
.slideDown(300)
.delay(4000)
.slideUp(300, function () {
$(this).html("");
});
});
event.preventDefault();
});
}
And this is my PHP file:
<?php
$user_email = "fr.sven.fr#hotmail.com";
$mail = array(
"name" => htmlspecialchars($_POST['cf-name']),
"email" => htmlspecialchars($_POST['cf-email']),
"subject" => htmlspecialchars($_POST['cf-subject']),
"message" => htmlspecialchars($_POST['cf-message'])
);
function validate($arr){
return !empty($arr['name']) && strlen($arr['message']) > 20 && filter_var($arr['email'],FILTER_VALIDATE_EMAIL);
}
if(validate($mail)){
echo mail($user_email, $mail['subject'],
"Name : {$mail['name']}\n"
."E-mail : {$mail['email']}\n"
."Message : {$mail['message']}"
);
}
?>
When I submit the file without typing filling in the form I get the correct error. When I fill in the message with less than 10 characters, I get the correct error, but when I fill in everything correctly I get the error:
Notice: Undefined index: cf-name in /Applications/MAMP/htdocs/Klus spanje/php/mail.php on line 7
Notice: Undefined index: cf-email in /Applications/MAMP/htdocs/Klus spanje/php/mail.php on line 8
Notice: Undefined index: cf-subject in /Applications/MAMP/htdocs/Klus spanje/php/bat/mail.php on line 9
Notice: Undefined index: cf-message in /Applications/MAMP/htdocs/Klus spanje/php/bat/mail.php on line 10
I have no idea what I do wrong, can someone help?
EDIT:
Ah, you added the php errors now, great!
So it is not seeing the right post variables. As you didn't provide the html of your form (which would be helpful next time!) I can only provide you a way to figure this out yourself :)
To figure out the right names that are posted, you can use
print_r($_POST);
in your php code. This will show you the key-value pairs that are sent from the client. Most likely the keys are just a bit different than you thought, but changing them to the ones printed by the above code should solve this error!
ORIGINAL: (because I am proud of making the screenshot ;))
My guess is, that the data returned by php is not exactly "1". You can confirm in the chrome console, under network the network tab:
The green circle is just to find the requests made by javascript.
You can also use console.log(data); but then what did I make this screenshot for? ;)
Now the problem with your code is that, when your javascript doesn't get "1", it will get to this code (with comments by me)
// These two conditions are both not met (as you fill in the form correctly)
if(cf.find('textarea').val().length < 10){
// So text doesn't get set here
text = "Message must contain at least 10 characters!"
}
if(cf.find('input').val() == ""){
// Neither does this one
text = "All required fields must be filled!";
}
// So at this point, the variable `text` has not gotten any value assigned,
// making it `undefined`. Which wouldn't be a problem,
// if it weren't for the fact you try to use it as is in the html here
$('.message-container').html('<div class="alert-box error"><i class="icon-warning"></i><p>'+text+'</p></div>')
.delay(150)
.slideDown(300)
.delay(4000)
.slideUp(300,function(){
$(this).html("");
});
Something you could do for now is, at least, provide a default error message:
$('.message-container').html('<div class="alert-box error"><i class="icon-warning"></i><p>'+(text || 'Default error message')+'</p></div>')
But the thing is to either
Make the php return the right value and run without an error, and if that is already working
Make sure the javascript does match the correct data, without any spaces in the data. Maybe even using data.trim() (which removes whitespaces at the start and end of the string) could help here.
Hope this gives you a good point to start debugging the issue :)
Related
I have the following html:
<div class="form-outline mb-4">
<input type="text" id="PlanID" asp-for="PlanID" name="PlanID" class="form-control form-control-lg" value="#Model.PlanID" />
<label id="errorLabel" name="errorLabel" class="form-label text-danger" for="PlanID"></label>
</div>
<button class="btn btn-primary btn-lg btn-block" type="button" disabled id="nextButton" name="nextButton" onclick="DisplayProgressMessage(this, 'Next');">Next</button>
And I have the following jquery:
$.ajax({
type: "POST",
url: "#Url.Action("CheckPlanID")",
data: {PlanID: planID},
dataType: "text",
success: function (msg) {
if (msg.length > 4) {
console.log(msg.length);
$("#nextButton").prop("disabled", true);
$("#errorLabel").text = msg;
}
},
error: function (req, status, error) {
console.log(msg);
}
});
I have additional jquery that keeps the button disabled until the length of the data in the input is 4. When the length is 4, I enable the button.
When running the code, as soon as the length of the data in the input box is 4, the button is enabled and I click on it. the ajax executes and sends the data to my controller. The controller processes the data and will send back a string. If the length of the returned string is greater than 4, then the string being returned is an error string and that error string should get displayed to the user.
When I run the code and force an error, I can see the length of the error string being displayed in the console so I know this section of code is being executed. The button gets disabled, but the text of the errorLabel is not changing.
The text of the errorLabel should change to the error message. Is there something else that needs to be done? Am I missing something?
Thank you!
In jQuery, text is a method not an attribute so to fix your issue you'd simply change this
$("#errorLabel").text = msg
into this
$("#errorLabel").text(msg)
Also it seems, based on your code if (msg.length > 4), you only change the text if msg length is greater than 4. That means, unless msg has 5 characters or more the text won't change.
Learn more about text() method on jQuery docs.
I created an instant search similar to google search using JQuery. The highlighted code doesn't work. It is weird since they work fine by its own and everything else works fine. Any idea why this is happening?
Q1.
searchq() works fine, but the createq() function doesn't work, and the variable txt could be posted to other files(search.php). However, the function createq() can't POST. It does get the global variable txt after testing, but the php file(create_object.php) can't get it no matter what POST method I used. Could anyone helps to write a bit POST code which can work in my code.
Q2
I want to create a function that,when the enter is pressed, the user will be redirected to the first search result(which is anchored with an url) . To achieve this, I create a function that variable redirectUrl got the anchored url as string, however, the redirect function window.location.href doesn't work, the page simply refreshed. I tested window.location.href function by its own in another file, it works though. It is so weird that my page simply refreshed, It even refreshed when I direct to google. window.location.href("www.google.com").
Note that I didn't include the connect to database function here. Coz I think the database username and password setting would be different to yours.So please create your own if you want to test it. The mysql is set with a table is called "objects", and it has one column named "name".
Thanks in advance!
<html>
<!-- google API reference -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my own script for search function -->
<center>
<form method="POST">
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<div id="output">
</div>
</form>
</center>
<!-- instant search function -->
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("input").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
};
function createq(){
// allert for test purpose: test if the txt has got by the createq function
alert(txt);
**$.post( "create_object.php",{creatVal:txt} );**
}
// if enter key pressed, redirect page to the first search result
$("#search").keypress(function(evt){
if (evt.which == 13) {
// find the first search result in DOM and trigger a click event
var redirectUrl = $('#search_output').find('a').first().attr('href');
alert(redirectUrl);
**window.location.href = "www.google.com";
window.location.href = "www.google.com";**
}
})
</script>
</html>
PHP file (search.php)
<?php
if(isset($_POST["searchVal"])){
//get the search
$search=$_POST["searchVal"];
//sort the search
$search=preg_replace("#[^0-9a-z]#i","",$search);
//query the search
echo "<br/>SELECT * from objects WHERE name LIKE '%$search%'<br/>";
$query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
$count=mysqli_num_rows($query);
//sort the result
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'>".$object_name."</a></div>";
}
}
echo $output;
}
?>
php file (create_object.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
var_dump($name);
}
?>
Try to bind the input with id
var txt = $("input").val();
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
Change above to this
var txt = $("#searchinput").val();
<input type="text" id="searchinput" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
and I think you are trying to show the search result here
<div id="output"></div>
and the jQuery binding is this in your code
$("#search_output").html("");
So change the HTML to this
<div id="search_output"></div>
also this in our code
$("#search").keypress(function(evt){
there is not HTML element bind with it and I think you are trying to bind it with search input so change above to this
$("#searchinput").keypress(function(evt){
The above change should also resolve the window.location.href not working problem
So the HTML will be;
<form method="POST">
<input type="text" id="searchinput" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<div id="search_output"></div>
</form>
and Script will be
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("#searchinput").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
}
function createq(){
// allert for test purpose: test if the txt has got by the createq function
alert(txt);
**$.post( "create_object.php",{creatVal:txt} );**
}
// if enter key pressed, redirect page to the first search result
$("#searchinput").keypress(function(evt){
if (evt.which == 13) {
// find the first search result in DOM and trigger a click event
var redirectUrl = $('#search_output').find('a').first().attr('href');
alert(redirectUrl);
**window.location.href = "www.google.com";
window.location.href = "www.google.com";**
}
});
</script>
Note: If you check browser console, you may see some errors, there are some typo mistakes like missing ; in your JS too.
In the PHP, here
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'>".$object_name."</a></div>";
}
}
$output. is wrong with dot, so change it to following
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output="<div><a href='#'>".$object_name."</a></div>";
}
}
Two things:
Input search id is not defined, $("#search").keypress won't work. Change to:
< input type="text" name="search" id="search" style="width:400px " placeholder="Search box" onkeyup="searchq();" >
Div id "output", should be "search_output", as required in $("#search_output"). Change to:
< div id="search_output" >
< /div >
I'm trying to compare two form inputs "password" and re-enter-password" to make sure there the same. I validate the password by sending it to a separate PHP that echoes back the results(which works fine)
<script type="text/javascript">
$(document).ready(function() {
$('#password_feedback').load('password-check.php').show();
$('#password_input').keyup(function() {
$.post('password-check.php', {
password: form.password.value
},
function(result) {
$('#password_feedback').html(result).show();
});
});
});
</script>
I tried sending password and re-enter=password to a PHP to compare with no luck. Can I compare the two with every keyup.
What are you checking for in your PHP script? Anything in particular that justifies the use of PHP?
You could do that only with JS, you don't need the AJAX part.
HTML :
<input type="password" id="password">
<input type="password" id="password_cf">
<div class="result"></div>
JS (jQuery) :
$('#password_cf').on('keyup', function(){
if($('#password_cf').val()== $('#password').val())
$('.result').html('They match');
else
$('.result').html('They do not match');
});
Fiddle : http://jsfiddle.net/2sapjxnu/
You can use the blur event if you want to only check once the focus is lost on that field. It's a bit less "responsive" than verifying on every key, but more performant I guess.
Not necessary jQuery, add the function:
function checkPass(input) {
if (input.value != document.getElementById('re-enter-password').value) {
input.setCustomValidity('Passwords should match.');
} else {
input.setCustomValidity('');
}
}
Add this to your re-enter-password: oninput="checkPass(this)"
OR
just call this function in the part where you want to make the comparison:
function checkPass() {
var input = document.getElementById('password');
if (input.value != document.getElementById('re-enter-password').value) {
input.setCustomValidity('Passwords should match.');
} else {
input.setCustomValidity('');
}
}
How about adding a class to each input and then:
if($(".password").val() == $(".re-enter-password").val()){
alert("it matches")
} else {
alert("no match yet");
}
Quick and dirty -
Given this markup -
<input type="password" name="pw1" />
<input type="password" name="pw2" />
You could check it client side without muliple round trips to the server using code like this -
$('[name="pw2"]').blur(function() {
var pw1 = $('[name="pw1"]').val();
var pw2 = $('[name="pw2"]').val();
if(pw2 != pw1) {
alert('passwords do not match');
}
});
Matching 2 form input fields with JavaScript by sending it off to the server to get an assertion response could render a bad user experience, because if you're doing this on each keyPress, then it generates unnecessary internet traffic - while the user is waiting.
So, instead, why not match these 2 fields directly with JavaScript?
If you are using a specific regular expression on the server for validation check as well, you can have the server put that regex "pattern" in the HTML fields - (no JavaScrpt needed for that). Then, onkeyup event you can simply do something like:
form.field2.onkeyup = function()
{
if (form.field1.value !== form.field2.value)
{
/* some code to highlight the 2 fields,
or show some message, or speech bubble */
return;
}
}
form.field1.onkeyup = form.field2.onkeyup;
I am trying to create one of those standard new password forms, where you type the new password once and then a second time to confirm. I would like it so that once you blur away from these fields, if they don't match, both will be marked invalid, as in the following scenario:
User enters password abc into #newpassword1.
User tabs to #newpassword2.
User enters password def into #newpassword2.
User tabs away.
Validation detects a mismatch, and marks both #newpassword1 and #newpassword2 as invalid.
I know that i can mark the target of an event as invalid by using e.target.setCustomValidity(...), but i don't understand JavaScript's event model very well and can't figure out how to mark a different element as invalid based on the event target's own invalidity.
This is the relevant excerpt of (non-working) code that i am trying to use:
if ( $('#newpassword1').val() != $('#newpassword2').val() ) {
errorMessage = "The new passwords you've entered don't match.";
$('#newpassword1, #newpassword2').setCustomValidity(errorMessage);
}
This seems like it should work, intuitively, but of course it does not. The error is simply TypeError: $(...).setCustomValidity is not a function.
Please note: I am not asking how to add a red ring or whatever to a field, i want it to actually be invalid (as in, have its validity.valid property return false).
Is it possible to do this?
Thanks!
Try the below code. You are getting that error because jQuery returns an array of selected objects and since setCustomValidity is supported by native input elements and not jquery objects, you are seeing that error.
$('#newpassword1, #newpassword2').each(function() {
this.setCustomValidity(errorMessage)
});
<div class="cabinet_settings_header cabinet_header">Список регионов работы для выбора</div>
<div class="registration_region_select checkbox-group required">
<?for($i = 0; $i < sizeof($regions); $i++):?>
<label for="region_id_<?=$regions[$i]['region_id']?>">
<input type="checkbox" name="region_id[]" value="<?=$regions[$i]['region_id']?>" id="region_id_<?=$regions[$i]['region_id']?>" />
<?=$regions[$i]['name']?>
</label>
<?endfor;?>
</div>
<div class="cabinet_settings_header cabinet_header">Проверка выбора регионов работы (разрешмет отправку формы, если минимум 1 выбран)</div>
$('.checkbox-group.required input').on('change', function(){
checkRegions();
});
function checkRegions(){
checked_counter = $('.checkbox-group.required :checkbox:checked').length;
if(checked_counter > 0){
$('.checkbox-group.required #region_id_2')[0].setCustomValidity('');
}else{
$('.checkbox-group.required #region_id_2')[0].setCustomValidity('Выберите хотябы 1 из вариантов');
}
}
$(document).ready(function() {
checkRegions();
$("form").submit(function(event){
if($('.checkbox-group.required :checkbox:checked').length <= 0 ){
$('.checkbox-group.required #region_id_2').focus();
event.preventDefault();
}
})
});
I have just started with JavaScript and want to validate a form. All the tutorials I've found create an alert for feedback, but I'd like to use onblur and give an error message next to the field. I managed to do the two functions separately but can't merge them. I'd really appreciate your help!
This is what I came up with, but it doesn't do what I need:
function validateFirstName()
{
var x=document.forms["demo"]["firstname"].value;
if (x==null || x=="" || x==)
{
function addMessage(id, text)
{
var textNode = document.createTextNode(text);
var element = document.getElementById(id);
element.appendChild(textNode);
document.getElementById('firstname').value= ('Firstname must be filled out')
}
return false;
}
}
So the following is a simple way to validate a form field by checking the value of an input when the form is submitted. In this example the error messages are just sent to the div element about the form but this should still help you out.
The HTML code looks something like this:
<div id="errors"></div>
<form onSubmit="return validate(this);">
<input type="text" name="firstName" placeholder="What's your first name?">
<button type="submit" value="submit">Submit</button>
</form>
The Javascript code looks something like this:
function validate(form) {
var errors ='';
if(form.firstName.value =="") {
errors += '<li>Please enter your first name</li>';
}
if(errors !='') { //Check if there are any errors, if there are, then continue
var message = document.getElementById("errors"); //assigns the element with the id of "errors" to the variable "message"
message.innerHTML = "<ul>" + errors + "</ul>"; //adds the error message into a list with the error message into the HTML
return false;
} else {
return true;
}
}
Once you understand this you should be able to figure the rest out on your own or go to http://www.w3schools.com/ and check out the javascript section to help you out.
I'm not sure what you really looking for. If I understood right (and I can be very wrong) you are looking for something like:
var x = undefined; // Can be undefined, null, or empty string
if (x==null || x=="" || x==undefined) { // do no forget to check for undefined
function addMessage(id, text) {
// Your validation code goes here
alert(id + text);
};
addMessage(1234, "Mandatory field!");
}
Note, there are several ways to do it. I just showing the simplest way I can think of...