I have a web form, simple HTML / PHP that works by itself but when it is passed onto the template page via the below AJAX call -- the post data is missing on submission. This HAS got to be a param I'm missing below.
$(document).ready(function() {
$('#toggle3').click(function(){
var tog = $('.toggle');
$.ajax({
type: 'POST',
url: '/mysimplewebform.php',
success: function (fields){
tog.html(fields);
tog.slideToggle(1000);
}
});
});
});
The request is sent. And upon submission I receive email, everything but the selected post data via form is sent. Below is the PHP.
<?php
$backwheel = $_POST['backwheel'];
$frontwheel = $_POST['frontwheel'];
$form_message = "backwheel:".$backwheel." frontwheel:".$frontwheel." \nMessage: ". " You just recieved a new custom order via your Customizer!"."\nFullCustomURL: ".$_SERVER['HTTP_REFERER'];
mail("email#gmail.com", "Your Website Something", $form_message, "From: Capn Ron (New Order!)" );
if (isset($_POST['submit']))
{
echo "<script>
alert('Thanks for your Order!');
window.location.href='http://www.website.com';
</script>";
}
?>
You're not missing a param. From your code, #toggle3 appears to be button since the click event is bound to it. So, if you try to serialize it, it will certainly return nothing. You have to serialize the surrounding form which is easily achieved by using jQuery's closest() function; i.e.:
$(document).ready(function() {
$('#toggle3').click(function(){
var tog = $('.toggle');
$.ajax({
type: 'POST',
url: '/mysimplewebform.php',
data: $(this).closest('form').serialize(),
success: function (fields){
tog.html(fields);
tog.slideToggle(1000);
}
});
});
});
Related
I am trying to send a variable from JS to php through ajax but I'm not able to get in php file.
JS
var names = ['lee','carter'] ;
$.ajax({
type: "POST",
url: "http://localhost/test/ajax.php",
data: {name:names},
}).done(function() {
location.href = 'http://localhost/test/ajax.php' ;
});
PHP
print_r($_POST);
this is showing an empty array but when I do console.log(data) it shows an array in console.log
var names = ['lee','carter'] ;
$.ajax({
type: "POST",
url: "http://localhost/test/ajax.php",
data: {name:names},
}).done(function(data) {
console.log(data) ;
});
Edit: (by mega6382) I believe OP wants to open a page in browser with post params, which cannot be done by AJAX. All others who answered got mistaken by the AJAX code in the question and started providing AJAX solutions, without realizing what OP is trying to do. If you were to read OP's comments on Jeroen's answer.
The problem is with what you do when the ajax request finishes:
}).done(function() {
location.href = 'http://localhost/test/ajax.php' ;
});
Here you are re-directing to http://localhost/test/ajax.php (requesting it a second time...), using a GET request so $_POST is indeed empty.
Just do the following in your php file to receive a json formatted string
echo json_encode(['success' => true]);
Instead of ajax try sending a dynamically generated form like:
var names = ['lee','carter'] ;
var newForm = $('<form>', {
'action': "http://localhost/test/ajax.php",
'target': '_top',
'method': 'POST'
});
names.forEach(function (item, index)
{
newForm.append($('<input>', {
'name': 'name[]',
'value': item,
'type': 'hidden'
}));
});
$(document.body).append(newForm);
newForm.submit();
This will send the values over POST via a form. It will do both redirect to the new page and send post vals.
Since you're using an AJAX request, in this case POST, you could use the _REQUEST method in php for obtaining the JS variable. In your case try:
$names = $_REQUEST['name']
echo $names;
/* Or try JSON_ENCODE if echo isn't working*/
$json = json_encode($names)
echo ($json);
var names = ['lee','carter'] ;
JSON.stringify(names);
$.ajax({
type: "POST",
dataType: 'json',
url: "http://localhost/test/ajax.php",
data: {name:names}
}).done(function() {
console.log('ok');
});
This is a successful ajax call. Now in order to "check by yourself" that is working you don't have to redirect to the other page because that way you refresh and lose the data. What you have to do is:
Open developer tab in your browser
Go to network tab
Locate your ajax call (it has the name of your php class that you do
the call)
go to response tab and there you have your php output
This link is to help you understand how to debug ajax call
I'm having a problem when I'm trying to serialize data form.
Here is the code. I have a page1.php that contains the form. And when the form has been sent, through AJAX, I retrieve the form data and then send it to page2.php.
The problem appears, when it's trying to serialize the file field.
page1.php (containing the form)
$(document).ready(function(){
$("#enviar").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "processar_updateUser.php",
data: $("form").serialize(),
success: function(data){
alert(data);
}
});
return false;
});
});
page2.php (processing the form data)
<?php
$personal_name = addslashes(htmlentities($_POST['personalname']));
$name = addslashes(htmlentities($_POST['name']));
$surname = addslashes(htmlentities($_POST['surname']));
$concatnom = $name.".".$surname;
$password = addslashes(htmlentities($_POST['password']));
$adegree = addslashes(htmlentities($_POST['adegree']));
$initials = addslashes(htmlentities($_POST['initials']));
$n = substr($name,0,1);
$c = substr($surname,0,1);
$initials = $n.$c;
$email = addslashes(htmlentities($_POST['email']));// que sigui cadena+#"+cadena+.+cadena
$telephone = addslashes(htmlentities($_POST['telephone'])); //numero y nomes 9
$signature = addslashes(htmlentities($_FILES['signature']['name']));//i have used $_POST, but dind't work
?>
Try this (Replaces JQuery selectors according to your html):
var formData = new FormData();
formData.append('personalname', $("#personalname").val());
formData.append('name', $("#name").val());
formData.append('surname', $("#surname").val());
formData.append('password', $("#password").val());
formData.append('adegree', $("#adegree").val());
formData.append('initials', $("#initials").val());
formData.append('email', $("#email").val());
formData.append('telephone', $("#telephone").val());
formData.append('signature', $('#signature')[0].files[0]);
$(document).ready(function(){
$("#enviar").click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "processar_updateUser.php",
data: formData,
success: function(data){
alert(data);
}
});
return false;
});
});
This can be tedious, but it is how I managed to send images to the backend
The method $('#signature') will return a JQuery input object.
This: $('#signature')[0] returns the HTML input tag.
This: $('#signature')[0].files return a JQuery object that contains all files you have selected.
And finally, this: $('#signature')[0].files[0] will return the first file in the JQuery object...
I'm assuming you accept just one file... If not, you must append to formData every file stored in $('#signature')[0].files
Hope this help.
Regards
I had the same problem some time ago. I used this plugin jQuery Form Plugin for mixed forms - data plus files,or in other case this one blueimp but this one only for file upload.
I use them a lot and they work like a charm and are easy to integrate.
Hope this will help.
UPDATE II
$("#form").submit(function(event){
event.preventDefault();
var $form = $( this ),
url = $form.attr( 'action' );
var posting = $.post( url, {
id: $('#id').val(),
name: $('#name').val(),
wname: $('#wname').val(),
xcor: $('#xcor').val(),
ycor: $('#ycor').val(),
xwid: $('#xwid').val(),
yhei: $('#yhei').val(),
photo: $('#photo').val(),
targeturl: $('#targeturl').val()
});
posting.done(function( data ){
alert('success');
});
});
UPDATE
This does not work... the alert('nice'); is not triggered
$("#form").submit(function(e){
var postData = $(this).seralizeArray();
var formURL = $(this).attr("action");
$.ajax({
url : formURL,
type : "POST",
data : postData
});
e.preventDefault();
e.unbind();
});
$("#form").submit();
alert('nice');
My goal is to send data with a form through ajax and the page does not refresh.
I am not using a button, the submit is triggered by a javascript function which triggers the ajax
The serialized data I had follows the format of
name=name$email=email etc...
I don't know what to do with this string
This is what I have on the sending page
var frm = $('#form');
var formData = $('#form').serialize();
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
data: formData,
url: frm.attr('action'),
success: function (data) {
alert('successful update');
}
});
ev.preventDefault();
});
Does the serialized data get appended to a URL? I mean I realize upon submission the current page does not go anywhere so how would that work as far as the action page "seeing the url and pulling it" so to speak...
My action page is the cliche design of a form being submitted by a button on the same page mostly it is a declaration of the variables and then an insert line
if($_SERVER['REQUEST_METHOD']=='POST'){
$name = $_POST['name'];
$email= $_POST['email'];
$link = new mysqli("$servername", "$username", "$password", "$dbname");
$stmt = mysqli_prepare($link, "INSERT INTO table VALUES(?,?)");
$stmt->bind_param('ss',$name,$email);
$stmt->execute();
I apologize if this is clearly wrong, I haven't used serialized form data submission before
Assuming your form method frm.attr('method') is POST, the serialized data does not get put in the URL but instead in the HTTP request body.
http://en.wikipedia.org/wiki/HTTP_message_body
If the form method is GET then the data would be appended to the end of the URL like so:
http://yoursite.com/yourrequestpage?name=yourname&email=youremail
If you are using the GET method then on the PHP side, you would have to use $_GET['email'] instead of $_POST['email'].
I also see that var formData = $('#form').serialize(); is out of the form submission function body. This should be put in the body so that it is initialized when the form is submitted (when you have filled out the form), not when the page is loaded (when you haven't yet interacted with the form).
I have a nice looking slideup/slidedown jquery form on my website. It sends the data to the same file to send the email. This works fine:
$(document).ready(function(){
$('div.contact a.submit').click(function() {
var name = $('div.contact input.name').val();
var email = $('div.contact input.email').val();
var message = $('div.contact textarea.message').val();
$('div.contact').slideUp('slow', function() {
$.ajax({
type: "POST",
url: "test.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success: function(msg)
{
$('div.contact').html('<h1>Contact</h1><div class="comment">Success!</div><div class="clear"></div><p class="indent">Thank you, we will be in contact shortly.</p>');
$('div.contact').slideDown('slow');
}//end of success
});//end of ajax
});
});
});
The php at the top of test.php to send the email:
include("expander-b1.0.php");
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
sendmail("admin#site.co.uk", $message, "Contact message from $name", $email);
This is getting my simple mail function from a external file. However, I would like some way to validate the form entry (including email validation), then display the error(s) in the contact dive. I am not that experienced with jQuery or ajax but an unable to get it working with using if statements in my php and echoing the variables in the "success" part of the ajax.
$(document).ready(function(){
$('div.contact a.submit').click(function() {
var name = $('div.contact input.name').val();
var email = $('div.contact input.email').val();
var message = $('div.contact textarea.message').val();
//Email Validation
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(reg.test(email) == false) {
alert('Invalid Email Address');
return false;
}
//Name and message VALIDATION
//-------- goes here ------------//
$('div.contact').slideUp('slow', function() {
$.ajax({
type: "POST",
url: "test.php",
data: "name=" + name + "&email=" + email + "&message=" + message,
success: function(msg)
{
$('div.contact').html('<h1>Contact</h1><div class="comment">Success!</div><div class="clear"></div><p class="indent">Thank you, we will be in contact shortly.</p>');
$('div.contact').slideDown('slow');
}//end of success
});//end of ajax
});
});
});
you need to use mysql_real_escape() to filter evil code in the post and you can use regular expression to check for a valid email. if you google for it you will find a lot of documentation and tutorials about that.
you can also make it easy on yourself and buy (or find a free one) a ready to use validation class -> Codecanyon validation class
and about the success part have a look at this question -> how can i create a success back function?
http://www.position-absolute.com/articles/jquery-form-validator-because-form-validation-is-a-mess/
A JQuery-based validation script that works very well to validate and automatically insert error messages if a section of your code fails validation. Simply include files, add jquery (see source of examples for best methods) and add the "required" element to your class names. Should be a perfect solution to your problem....with no crazy math or individual selectors required.
At the moment i have this piece of javascript code:
//Display custom confirm box and delete multiple message
$(document).ready(function () {
$(".delete_button-multiple").click(function () {
//Get message id as variable
var id = $(this).attr("id");
var dataString = 'id=' + id;
var parent = $(this).parent();
//Display custom Confirm box
jConfirm('Are you sure you want to delete this message?', '', function (r) {
if (r == true) { //initiate delete message if agreed
$.ajax({
type: "POST",
url: "delete-mail_ajax.php",
data: dataString,
cache: false,
success: function () {
window.location = "mail_inbox.php";
}
});
return false;
}
});
});
});
delete-mail_ajax.php:
if($_POST['id'])
{
$id=$_POST['id'];
$id = mysql_escape_String($id);
$sql = "delete FROM mail WHERE mail_id='$id'";
mysql_query( $sql);
}
This is a working code for deleting only one mail item.
I wrote the following code to delete multiple messages from checkboxes:
//Multiple delete mail
if(!empty($_POST['message'])){
$list_mail = $_POST['message'];
foreach ($list_mail as $messageID){
$sql = "delete FROM mail WHERE mail_id='$messageID'";
mysql_query($sql);
//deletion complete, refresh the page
header("Location: mail_inbox.php");
}
}//end delete multiple
The difficulty i'm having is changing the working code above to incorporate the multiple selection, and deletion, of selected mails.
Any help on this issue would be appreciated
-Callum
Assuming you're using checkboxes, your code would look something like:
var messages = new Array();
$("input[name='mail_items[]']:checked").each(function() {
messages.push($(this).val());
});
$.ajax({
type: "POST",
url: "delete-mail_ajax.php",
data: { message: messages } //jQuery should translate this to an array that PHP should understand
cache: false,
...
});
You may need to json_decode the input to the $_POST['message'] variable, but I'd do a var_dump() on the stuff first just to make sure what PHP is doing in the background. Can't check at the moment, sorry.
I guess you have trouble submitting the form via Ajax? There is a neat plugin that does that for you: http://jquery.malsup.com/form/