Site pulled on WordPress.
The usual forms on the site work, but in the modal window does not.
The console shows nothing. The send button does not respond.
Broke my head. Help find the problem.
Code JS:
$(document).on("submit", "form", function () {
var formID = $(this).attr('id');
var formNm = $('#' + formID);
$.ajax({
type: "POST",
url: 'mail.php',
data: formNm.serialize(),
success: function (data) {
$(formNm).html(data);
},
error: function (jqXHR, text, error) {
$(formNm).html(error);
}
});
return false;
});
Html form on pop-up (id different):
<form action="mail.php" method="POST" id="formModal1">
<input type="text" name="t-number" placeholder="Ваш телефон" required />
<input type="submit" placeholder="Получить консультацию" />
</form>
Php :
<?php
if (isset($_POST['t-number'])) {$phone = $_POST['t-number'];}
if (isset($_POST['email'])) {$email = $_POST['email'];}
$address = "";
$mes = "Тема: Заказ обратного звонка!\nТелефон: $phone\nE-mail: $email";
$sub='Заказ';
$mail='Заказ <Центр юридической помощи>';
$send = mail ($address,$sub,$mes,"Content-type:text/plain; charset = utf-8\r\nFrom:$mail");
ini_set('short_open_tag', 'On');
?>
Related
I am trying to get get my form to submit without having the page refreshing everytime
However, when I insert the ajax and place the php into a new file the form doesnt submit and I dont understand why?
Any advice would be appreicated!
PHP
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['phone'], $_POST['message'])){
//Post data
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
//mail settings
$to = "arshdsoni#gmail.com";
$subject = 'Soni Repairs - Support Request';
$body = <<<EMAIL
Hi There!
My name is $name.
Message: $message.
My email is: $email
Phone Number: $phone
Kind Regards
EMAIL;
$header = "From: $email";
if($_POST) {
if($name == '' || $email == '' || $phone == '' || $message == '') {
echo $feedback = "<font color='red'> *Please Fill in All Fields!";
}
else {
mail($to, $subject, $body, $header);
echo $feedback = "<font color='green'> *Message sent! You will receive a reply shortly!";
}
}
}
else{
echo $feedback = "<font color='red'> Missing Params";
}
?>
AJAX
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("#submitBtn").click(function( event ) {
//values
var name=document.getElementById('name').value;
var email=document.getElementById('email').value;
var phone=document.getElementById('phone').value;
var message=document.getElementById('message').value;
var occasion=document.getElementById('occasion').value;
var dataString = $("#contact").serialize();
$.ajax({
type:"post",
url:"php.php",
data: dataString,
success: function(html) {
$('#feedback').html(html);
}
});
event.preventDefault();
});
});
</script>
HTML CODE HERE: http://www.codeply.com/go/e3jAo1WrPl
The .bind() function may be the way to go with this form, since it binds the action of clicking the button to the event handler.
It also may be beneficial to have the event.preventDefault() before your ajax call.
$(document).ready(function(){
$("#submitBtn").bind([boundElement],function( event ) {
event.preventDefault();
var name=document.getElementById('name').value;
var email=document.getElementById('email').value;
var phone=document.getElementById('phone').value;
var message=document.getElementById('message').value;
var occasion=document.getElementById('occasion').value;
var dataString = $("#contact").serialize();
$.ajax({
type:"post",
url:"php.php",
data: dataString,
success: function(html) {
$('#feedback').html(html);
}
});
return true;
});
});
I would recommend double-checking the syntax for the bound element in the .bind() parameters. It is single quote marks for referring to a named form element
Example HTML:
This might help you with your problem:
$(document).ready(function() {
$("#contact").submit(function(event) {
event.preventDefault();
var name = $('#name').val(),
email = $('#email').val(),
phone = $('#phone').val(),
message = $('#message').val(),
occasion = $('#occasion').val(),
dataString = $(this).serialize();
$.ajax({
url: 'php.php',
type: 'post',
data: dataString,
})
.done( function( html ) {
$( '#feedback' ).html( html );
})
.fail( function( response ) {
console.log( response );
});
});
});
Firs of all, you have the form and the submit button, so when you press the button, the event 'submit' is triggered, so you prevent the event to be fired, then you do your coding, the variables, but I cannot understand why you declare all those, if you don't use them, but that's up to you.
Here is a suggestion with using a button in stead of a submit. I commented out the preventDefault, because it is unnecessary in this case -- we are not actually submitting the form. This gives us more control.
The request is submitted. In this case, it obviously fails. In your case, whether or not it fails is going to depend on what you have going on server side.
http://plnkr.co/edit/txuxaFUkgFq9SFDcqUdp
<form action="http://www.yahoo.com" id="contactForm" method="get" target="_blank">
<div class="innerForm">
<label for="name">Name:</label>
<input id="name" name="name" type="text" />
<label for="phone">Phone:</label>
<input id="phone" name="phone" type="text" />
<label for="email">Email:</label>
<input id="email" name="email" type="text" />
<label for="occasion">Occasion:</label>
<input id="occasion" type="text" name="occasion" />
<label id="messageLabel" for="message">Message:</label>
<textarea id="message" name="message"></textarea>
<button id="test">test</button>
<!--input type="submit" value="Submit" id="submitBtn" name="submit" onclick="return chk();"/ -->
</div>
<div id="feedback"></div>
</form>
$(document).ready(function(){
$("#test").click(function (event) {
//values
alert("test clicked");
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var phone = document.getElementById('phone').value;
var message = document.getElementById('message').value;
var occasion = document.getElementById('occasion').value;
var dataString = $("#contactForm").serialize();
$.ajax({
type: "get",
url: "http://www.yahoo.com",
data: dataString,
success: function (html) {
alert("success");
//$('#feedback').html(html);
},
error: function(result){
alert("failure");
}
});
//event.preventDefault();
});
});
The goal is that once a the submit button is clicked, instead of going to send.php, it will just keep the page, I don't even want the page reloaded. If you guys have another way of doing this, that would be perfectly fine too.
My Ajax code
$("#sendtxt").click(function(e) {
e.preventDefault();
var phonenum = $("#phonenum").val();
var provider = $("#provider").val();
var message = $("#message").val();
$.ajax({
type : 'POST',
data : dataString,
url : 'send.php',
success : function(data) {
alert(data);
}
});
});
My Form code
<form name="reqform" action="" method="post">
<h1>Phone Number:
<input name="phonenum" id="phonenum" type="text" class="txtbox-style" onkeyup="if (/\D/g.test(this.value)) this.value = this.value.replace(/\D/g,'')" required/>
<select name = "provider" id ="provider" class="txtbox-style" required>
<option value="#sms.mycricket.com">Cricket Wireless</option>
</select>
<br/>
Message:
<input name="message" id="message" type="text" class="txtbox-style"/>
<br/>
How many times?
<input name="amount" id="amount" type="number" min="1" max="20" class="txtbox-style" required/>
<br />
<input type="submit" id="sendtxt" name="sendtxt" class="btn-style" value="Start Sending" />
</h1>
</form>
My send.php
<?php
$to = $_POST["phonenum"];
$provider = $_POST["provider"];
$subject = 'Hi';
$message = $_POST["message"];
$headers = 'From: Hello' . phpversion();
mail($to . $provider, $subject, $message, $headers);
?>
Your data attribute wasn't correct, there was nothing being sent. You can try it like this, this will work:
You have to have jQuery included in your page, you can do this with this line and place it above your script:
<script>
$(document).ready(function(){
$('input[name="phonenum"]').keyup(function(e) {
if (/\D/g.test(this.value)) {
// Filter non-digits from input value.
this.value = this.value.replace(/\D/g, '');
}
});
$("#sendtxt").click(function(e) {
e.preventDefault();
var phonenum = $("#phonenum").val();
var provider = $("#provider").val();
var message = $("#message").val();
$.ajax({
type : 'POST',
data : {
provider : provider,
// ^key that appears in post
message : message,
// ^var you fetched before from the input
phonenum : phonenum
},
url : 'send.php',
success : function(data) {
alert(data);
console.log('Success');
},
error : function(xhr, err) {
console.log("readyState: " + xhr.readyState + "\nstatus: " + xhr.status);
console.log("responseText: " + xhr.responseText);
}
});
});
});
</script>
EDIT:
Check your console for errors (F12 in chrome), if there's an error, it will look like this, or similar:
If ajax succeeds, there will be at least "Success"
ANOTHER EDIT:
Put your form out of the <h1> tag, use it like this:
<h1>Phone Number:</h1>
and delete the </h1> at the end of your form...
I prefer binding form's submit event (Because user may hit enter on focused <input> element, not submitting by clicking <input type="submit">), additionally there is an easier data colletion approach:
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
data : $(this).serialize(),//Here we collect all entered data
url : 'send.php',
success : function(data) {
alert(data);
}
});
});
I think that the best Approach is to use the jquery $.post method
$("form").submit(function(e) {
e.preventDefault();
$.post('send.php', $( this ).serialize()).done(function(data){
alert(data);
});
}
http://api.jquery.com/serialize/
http://api.jquery.com/jQuery.post/
** update **
example js fiddle:
http://jsfiddle.net/de71ju0r/1/
I know this has been asked before, but I can seem to find an solution that fixes the problem in my case. I'm trying to post data to a Mysql database with an an Ajax post
HTML
<form action="" method="post">
<input type="text" id="message" name="message">
<<input type="submit" value="Send" id="submit">
</form>
Ajax post
$(document).ready(function(){
$("#submit").click(function(){
var message = $("#message").val();
var data = "message=" + message;
console.log(data);
if(message != ''){
console.log(data);
$.ajax({
type: "POST",
url: "classes/messages.php",
data: data,
succes: function(){
alert("succes");
}
});
}
return false;
});
});
PHP code
class messages{
function getMessages(){
$con = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);
$message = $_POST['message'];
mysqli_query($con, "INSERT INTO messages(message, time, user_id)
VALUES('$message', 'now()', '12')")or die(mysqli_error($con));
mysqli_close($con);
}
}
$messages = new Messages();
$messages->getMessages();
Everytime I submit the form nothing happends, not even an php error appears. I've checked the Ajax post and both console.logs return the correct value, so I think the variable is reachable.
I've also checked if the php function is executed at all, which is the case.
Try this
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#submit").click(function(){
var message = $("#message").val();
var data = "message=" + message;
console.log(data);
if(message != ''){
console.log(data);
$.ajax({
type: "POST",
url: "classes/messages.php",
data: data,
success: function(){
alert("succes");
}
});
}
return false;
});
});
</script>
</head>
<body>
<form action="" method="post">
<input type="text" id="message" name="message">
<input type="button" value="Send" id="submit">
</form>
</body>
</html>
and
<?php
class messages{
function getMessages(){
$con = mysqli_connect(HOST, USERNAME, PASSWORD, DATABASE);
$message = $_POST['message'];
mysqli_query($con, "INSERT INTO messages(message, time, user_id)
VALUES('$message', 'now()', '12')")or die(mysqli_error($con));
mysqli_close($con);
}
}
$messages = new Messages();
$messages->getMessages();
Basically I changed input type='button' from `'submit' . Since it was a submit button, the ajax call was never done, instead the form was submitting.
You could try this shorthand method instead:
var message = "message=" + $("#message").val();
$("#submit").on("click", function(ev)){
$.post("classes/messages.php", {message: message}, 'json').done(function (data, textStatus, jqXHR) {
console.log("succes");
}).fail(function () {
console.log("Fail");
return false;
}).always();
}
Use on it's better and recommended than just trigger the function on the selector itself.
I have a form in a modal window. When I submit the form through ajax I don't get the success message. My aim is to see the message created in the php file in the modal after submitting the form. Here is the code:
<p><a class='activate_modal' name='modal_window' href='#'>Sign Up</a></p>
<div id='mask' class='close_modal'></div>
<div id='modal_window' class='modal_window'>
<form name="field" method="post" id="form">
<label for="username">Username:</label><br>
<input name="username" id="username" type="text"/><span id="gif"><span>
<span id="user_error"></span><br><br>
<label for="email">Email:</label><br>
<input name="email" id="email" type="text"/><span id="gif3"></span>
<span id="email_error"></span><br><br>
<input name="submit" type="submit" value="Register" id="submit"/>
</form>
</div>
The modal.js
$('.activate_modal').click(function(){
var modal_id = $(this).attr('name');
show_modal(modal_id);
});
$('.close_modal').click(function(){
close_modal();
});
$(document).keydown(function(e){
if (e.keyCode == 27){
close_modal();
}
});
function close_modal(){
$('#mask').fadeOut(500);
$('.modal_window').fadeOut(500);
}
function show_modal(modal_id){
$('#mask').css({ 'display' : 'block', opacity : 0});
$('#mask').fadeTo(500,0.7);
$('#'+modal_id).fadeIn(500);
}
The test.js for the registration of the user
$(function() {
$('#form').submit(function() {
$.ajax({
type: "POST",
url: "test.php",
data: $("#form").serialize(),
success: function(data) {
$('#form').replaceWith(data);
}
});
});
});
And the PHP FILE
<?php
$mysqli = new mysqli('127.0.0.1', 'root', '', 'project');
$username = $_POST['username'];
$email = $_POST['email'];
$mysqli->query("INSERT INTO `project`.`registration` (`username`,`email`) VALUES ('$username','$email')");
$result = $mysqli->affected_rows;
if($result > 0) {
echo 'Welcome';
} else {
echo 'ERROR!';
}
?>
Try putting the returncode from your AJAX call into
$('#modal_window')
instead of in the form
$('#form')
BTW: Why not use the POST or GET method of jQuery? They're incredibly easy to use...
Try something like this.
First write ajax code using jquery.
<script type="text/javascript">
function submitForm()
{
var str = jQuery( "form" ).serialize();
jQuery.ajax({
type: "POST",
url: '<?php echo BaseUrl()."myurl/"; ?>',
data: str,
format: "json",
success: function(data) {
var obj = JSON.parse(data);
if( obj[0] === 'error')
{
jQuery("#error").html(obj[1]);
}else{
jQuery("#success").html(obj[1]);
setTimeout(function () {
jQuery.fancybox.close();
}, 2500);
}
}
});
}
</script>
while in php write code for error and success messages like this :
if(//condition true){
echo json_encode(array("success"," successfully Done.."));
}else{
echo json_encode(array("error","Some error.."));
}
Hopes this help you.
I'm new to jQuery / AJAX.
I'm trying to send single input with jquery/ajax/php.
LIVE EXAMPLE
But, after pressing submit nothing is happening, where is my error?
Any help much appreciated.
HTML:
<form action="submit.php">
<input id="number" name="number" type="text" />
<input id="submit" name="submit" type="submit" />
</form>
JQUERY / AJAX:
$(document).ready(function(e) {
$('input#submit').click(function() {
var number = $('input[name=number]');
var data = 'number=' + number.val();
$.ajax({
url: "submit.php",
type: "GET",
data: data,
cache: false,
success: function(html) {
if (html == 1) {
alert('wyslane');
}
else {
alert('error');
}
}
});
return false;
});
});
PHP:
<?php
$mailTo = 'email#gmail.com';
$mailFrom = 'email#gmail.com';
$subject = 'Call Back';
$number = ($_GET['number']) ? $_GET['number'] : $_POST['number'];
mail($mailTo, $subject, $number, "From: ".$mailFrom);
?>
HTML:
<form id=submit action="">
<input id="number" name="number" type="text" />
<input name="submit" type="submit" />
</form>
The action URL is irrelevant as you want to submit your data via AJAX. Add the submit id to the form and override the default submit behavior, instead of overriding the onclick handler of the submit button. I'll explain in the JS section.
JS:
var number = $('input[name="number"]');
Quotes were missing.
$(document).ready(function(e) {
$('#submit').submit(function() {
var number = $('input[name=number]');
var data = 'number=' + number.val();
$.ajax({
url: "submit.php",
type: "GET",
data: data,
cache: false,
success: function(html) {
if (html == 1) {
alert('wyslane');
}
else {
alert('error');
}
}
});
return false;
});
});
I don't really understand your success callback, why do you expect that html should be equal to 1?
Atleast I got 404 error when pressed your submit button:
Not Found
The requested URL /index.php was not found on this server.
Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.
When you get it to work, remember to add mysql_real_escape_string function to avoid SQL injections http://php.net/manual/en/function.mysql-real-escape-string.php
Since you are also using ID for number, you could just use: var data = 'number=' + $('#number').val()
Also if you add ID to your form, you can use:
$('#formId').submit(function(){
});
instead of that click. This function will launch when that form is submitted. This is better way because users can submit the form with other ways aswell than just clicking the submit button (enter).
var number = $('input[name=number]');
is wrong. It's
var number = $('input[name="number"]');