Email custom data through JQuery / Ajax in Wordpress - php

I am trying to send some custom post data from a page that displays specific posts in a jquery pop-up email.
At the moment, I have a completed HTML form , and JQuery modal box setup.
Here is this js code for this:
jQuery(document).ready(function($){
var email = $( "#email" ),
message = $( "#message" ),
allFields = $( [] ).add( email ).add( message ),
tips = $( ".validateTips" );
$( ".email-course" )
.button()
.click(function() {
$( "#dialog-form" ).dialog( "open" );
});
$( "#dialog-form" ).dialog({
autoOpen: false,
modal: true,
width: 550,
height:260,
resizable: false,
show: 'fade',
title: 'Email course',
buttons: {
"Send": function() {
//Need help here
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
}
});
});
And the HTML form:
<div id="dialog-form" title="Email this course">
<form>
<fieldset>
<label for="email">To:</label>
<input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />
<label for="email">From:</label>
<input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />
<label for="message">Message (optional)</label>
<input type="text" name="message" id="message" value="" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form>
</div>
and the button:
<div class="right"><button class="email-course">Email this course</button></div>
My question is how to read the data from the form and also I will have to pull some post data with ids from the page that loads them all and send it by Wordpress's wp_email I assume? I will have to merge the "message (optional)" with that specific post ID's data as well. Any other information I need please let me know. Thanks in advance.

Background:
jQuery has a .serialize() method that:
Encode a set of form elements as a string for submission.
With the use of this method you can serialize all the fields values without having to collect them individually.
For example, you can do:
$('form').serialize()
and you will get a string with all the collected form fields & values, then you can pass this string to the server in a data: {} object inside a $.ajax request.
.serialize() documentation at jqAPI
Filling the Send callback:
"Send": function() {
//Need help here
$.ajax({
data : $('#dialog-form form').serialize(),
error : function (jqXHR, textStatus:string, errorThrown:string) {
if (errorThrown) {
// Show message.
}
},
success : function (response_from_server:ResponseFromServer, statusText:string, xhr) {
// Do post-processing here.
},
type : 'POST',
url : ajaxurl
});
},
Here:
ajaxurl: A javascrip global variable set by WordPress to be used in AJAX queries pointing to '/wp-admin/admin-ajax.php'
$('#dialog-form form').serialize() : This method is the one that will serialize all the Successfull HTML controls present in the form and will append them as data in the AJAX query.
Here only is missing the nonce checking to validate the AJAX request, I didn't put it there to make the code simple.
Then on the WordPress PHP backend you have to capture that serialize that data in order to process it as you like.
Hope it helps.

Related

How to alert success message in modal form?

I'm new to ajax/jquery. I want to use sweetalert on my website, i set it up as in tutorial, but when i open modal form and click send button, it goes to another page, page send.php.
Here my form:
<form id="contactForm1" action="send.php" method="post">
<div class="field-block">
<label for="text">Message1</label>
<textarea id="message1" class="field" required name="message1" rows="4" placeholder=""></textarea>
</div>
<div class="field-block">
<label for="text">Message2</label>
<textarea id="message2" class="field" required name="message2" rows="4" placeholder=""></textarea>
</div>
<div class="field-block">
<label for="text">Message3</label>
<textarea id="message3" class="field" required name="message3" rows="4" placeholder=""></textarea>
</div>
<button id="button" class="button" type="submit">Отправить</button>
<div class="result">
<span id="answer"></span>
<span id="loader"><img src="images/loader.gif" alt=""></span>
</div>
</form>
inside this form sweetalert doesn't work, but outside of form it's working.
Here sweetalert jquery and ajax request:
<script>
$("#contactForm1").on('submit',function(event) {
event.preventDefault(); // to prevent default page reloading
var dataString = $(this).serialize(); // to get the form data
$.ajax({
type: "POST",
url: "send.php",
data: dataString,
success: function(data){
$('#contactForm1')[0].reset(); // to reset form data
}
}).done(function(data){
setTimeout(function () {
Swal.fire(
'Thank you!',
'Your request has been accepted!',
)
}, 2000);
});
});
</script>
what could be the problem? Please help
The problem is you're not sending request with AJAX.
Solution:
First remove action="send.php" from your form
then add this to your script.
<script>
$('.button').click(function(){
swal({
title:"Red Stapler",
text: "Are You Sure?",
buttons: {
cancel: true,
confirm: "Submit"
}
}).then((value) => {
<!-- When the user click submit send Ajax request -->
$.ajax({
url: "send.php",
method: "POST",
data:{
message1: $(#message1).val(),
message2: $(#message2).val(),
message3: $(#message3).val()
},
success: function(data)
{
// some actions
}
});
});
});
</script>
You can send it without ajax request also try this change
$('.button').click(function(){
to
function submitForm(){
your function will look like this:
function submitForm(){
swal({
title:"Red Stapler",
text: "Are You Sure?",
buttons: {
cancel: true,
confirm: "Submit"
}
});
}
Now in the form add
onsubmit="return submitForm()"
swal({ title: "Done", text: "Record updated successfully!", type: "success" }, function () {location.reload();});
Simply use this line code, it will automatically hide alert and reload the page when click "OK".

jQuery form plugin , how to submit only visible fields

Using the jQuery form plugin, I just want to submit the visible fields (not the hidden ones ) of the form.
HTML:
<div class="result"></div>
<form id="myForm" action="comment.php" method="post">
Name: <input type="text" name="name" />
Comment: <textarea name="comment"></textarea>
<div style="display:none;">
<input type="text" value="" name="name_1" />
</div>
<input type="submit" value="Submit Comment" />
</form>
I cannot find a way to submit only the visible fields using any of the methods below:
ajaxForm:
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
ajaxSubmit:
$('#myForm').ajaxSubmit({
target: '.result',
success: function(response) {
alert("Thank you for your comment!");
}
});
There is another method formSerialize but found no way to use it with the 2 methods mentioned above (usable with $.ajax however).
How to submit only the visible fields using any of the two methods ?
$("#myForm").on("submit", function() {
var visibleData = $('#myForm input:visible,textarea:visible,select:visible').fieldSerialize();
$.post(this.action, visibleData, function(result) {
alert('Thank you for your comment!');
});
// this is needed to prevent a non-ajax submit
return false;
});

jQueryUI Dialog with ajax-injected html selector

All code below is a stand-alone working example (greatly simplified) of what I am trying to do. If anyone copy/pastes the below code blocks into 3 separate files, the code is fully self-contained-- just remember to reference/include test5.js and the jquery libraries in script tags at top of document.
SUMMARY: HTML div injected via Ajax not opening in the jQuery UI dialog widget.
Objective: On document load, jquery-ajax injects an html form (ultimately, it will retrieve appropriate form values from DB which is the reason for ajax). A div with id="clickme" is injected with the html. Clicking the div should open the dialog.
Problem: The jQueryUI .dialog does not appear. I put an alert box inside the click event, and that fires. But the dialog remains elusive.
Therefore, problem appears to be the fact that the HTML is injected. What am I missing?
HTML: index.php
<div id="putit_here">
</div>
JAVASCRIPT/JQUERY: test5.js
$(function() {
var pih = $('#putit_here');
$.ajax({
type: "POST",
url: "ajax/ax_test5.php",
data: 'contact_id=1',
success:function(data){
pih.html(data);
var etc1 = $( "#editThisContact_1" );
/* *****************************************************************
Moving Dialog up >here< was correct answer.
********************************************************************
etc1.dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
alert('DialogClose fired');
}
}); //end .Dialog
****************************************************************** */
}
}); //End ajax
/* **** This is where I had it previously ***** */
etc1.dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
alert('DialogClose fired');
}
}); //end .Dialog
$(document).on('click', '#clickme', function(event) {
alert('HereIAm...');
$( "#editThisContact_1" ).dialog( "open" );
}); //End #clickme.click
}); //End document.ready
AJAX - ax_test5.php
$rrow = array();
$rrow['contact_id'] = 1;
$rrow['first_name'] = 'Peter';
$rrow['last_name'] = 'Rabbit';
$rrow['email1'] = 'peter.rabbit#thewarren.nimh.com';
$rrow['cell_phone'] = '+1.250.555.1212';
$r = '
<div id="editThisContact_'.$rrow['contact_id'].'" style="display:none">
<p class="instructions">Edit contact information for <span class="editname"></span>.</p>
<form name="editForm" onsubmit="return false;">
<fieldset>
<span style="position:relative;left:-95px;">First Name:</span><span style="position:relative;left:10px;">Last Name:</span><br />
<input type="text" id="fn_'.$rrow['contact_id'].'" value="'.$rrow['first_name'].'" name="fn_'.$rrow['contact_id'].'">
<input type="text" id="ln_'.$rrow['contact_id'].'" value="'.$rrow['last_name'].'" name="ln_'.$rrow['contact_id'].'"><br /><br />
<span style="position:relative;left:-120px;">Email:</span><span style="position:relative;left:30px;">Cell Phone:</span><br />
<input type="text" id="em_'.$rrow['contact_id'].'" value="'.$rrow['email1'].'" name="em_'.$rrow['contact_id'].'">
<input type="text" id="cp_'.$rrow['contact_id'].'" value="'.$rrow['cell_phone'].'" name="cp_'.$rrow['contact_id'].'">
</fieldset>
</form>
</div>
';
echo $r;
EDIT:
Updated question to move dialog definition inside AJAX success callback. Did not completely solve problem, though. The dialog now appears if I change the autoOpen flag to true, but that is not how the script must work. The dialog still does not open upon clicking the (injected) #clickme div.
EDIT 2:
My bad. At first I thought it didn't work, but then found that my live test and posted SO question varied in one line: how the .dialog("open") was being called. In live code, it was still using the var: etc1.dialog("open") -- but in post above the selector was fully referenced: $('#editThisContact_1').dialog("open"). The posted syntax was correct. Thanks gents, and also itachi who got me to check chrome console.
You are trying to initialize a dialog on an element before the element exists. You need to initialize the dialog on "#editThisContact_1" after your ajax call comes back successfully.
Like this:
....
success:function(data){
pih.html(data);
//now your DIV is actually there so init the dialog
var etc1 = $( "#editThisContact_1" );
etc1.dialog({
autoOpen: false,
height: 400,
width: 600,
modal: true,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
alert('DialogClose fired');
}
}); //end .Dialog
}

JQuery use in a (PHP) form

I have been building a page where an administrator of the page can come look at some abstracts that have been submitted. I have used jquery to insert a modal-form where they can categorize the abstract to fit within one of five choices(four sessions, and one n/a). However, I am stuck on the function in the script.
What I want it to do is to go to the .php page where I'll have the appropriate code written to UPDATE the record in the database, then send the administrator back to the main page, to continue categorizing abstracts if they wish.
I have the form:
<div id="dialog-form" title="Categorize this abstract">
<p class="validateTips">Please select one session for this abstract.</p>
<form method="post" action="savecat.php">
<fieldset>
<label><input type="radio" name="abstractcategory" value="session1" />Session 1</label>
<label><input type="radio" name="abstractcategory" value="session2" />Session 2</label>
<label><input type="radio" name="abstractcategory" value="session3" />Session 3</label>
<label><input type="radio" name="abstractcategory" value="session4" />Session 4</label>
<label><input type="radio" name="abstractcategory" value="NULL" />Irrelevant</label>
</fieldset>
</form>
</div>
In the script I have the categorize button:
$( "#categorize" )
.button()
.click(function() {
$( "#dialog-form" ).dialog( "open" );
});
And this is where I'm not sure what to do, in the dialog-form function:
$( "#dialog-form" ).dialog({
autoOpen: false,
height: 300,
width: 350,
modal: true,
buttons: {
"Categorize this abstract": function() {
What should I put here? I don't know. I want it to re-direct(?) to the savecat.php that is the action of the form.
Then there's the rest, to cancel, close, etc.
$( this ).dialog( "close" );
}
},
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
}
});
Can anyone point me in the right direction? I have a feeling it's a simple thing that I just am unaware of.
I guess you just want to submit the form?
$(this).find('form').submit();

Passing variables to a PHP file through jQuery

Really not familiar with jQuery. Is there anyway I can pass form data to a PHP file using jQuery?
FORM:
<div id="dialog-form" title="Fill in your details!">
<form>
<fieldset>
<label for="name">Name</label>
<input type="text" name="name" id="name"/>
<label for="email">Email</label>
<input type="text" name="email" id="email" value=""/>
<label for="phone">Phone</label>
<input type="phone" name="phone" id="phone" value=""/>
</fieldset>
</form>
It's a pop-up dialog with jQuery and gets submitted with:
$("#dialog-form").dialog({
autoOpen: false,
height: 450,
width: 350,
modal: true,
buttons: {
"Sumbit": function() {
//VALIDATES FORM INFO, IF CORRECT
if (Valid) {
$.ajax({
url: 'process-form.php',
success: function (response) {
//response is value returned from php
$("#dialog-success").dialog({
modal: true,
buttons: {
Ok: function() {
$(this).dialog("close");
}
}
});
}
});
$(this).dialog("close");
}
}
}
});
What I want to do is to send the form data that the user enters into process-form.php, where it will be processed and sent as an email (which I can do). Just not to sure on the jQuery side of things. Is it even possible?
You can use the .serialize() function
$('yourform').serialize();
Docs for .serialize() here
You would use it like this :
$.ajax({
url: 'process-form.php',
data: $('form').serialize(), // **** added this line ****
success: function (response) { //response is value returned from php
$("#dialog-success").dialog({
modal: true,
buttons: {
Ok: function () {
$(this).dialog("close");
}
}
});
}
});
Yes, you can use the jQuery .post() method, which is detailed here
$.post( "process-form.php", $( "#dialog-form" ).serialize( ) );
Given your current code the easiest way is to serialize the form into the data property:
[...]
url: 'process-form.php',
data: $('#dialog-form').serialize()
You're on the right lines with $.ajax, but you need to actually pass the data with the submission, which you haven't done so far. You're best off setting the 'type' as well.
$( "#dialog-form" ).dialog({
autoOpen: false,
height: 450,
width: 350,
modal: true,
buttons: {
"Sumbit": function() {
//VALIDATES FORM INFO, IF CORRECT
if (Valid ) {
$.ajax({
url: 'process-form.php',
type: "post",
data: {
name: $('[name=name]').val(),
email: $('[name=email]').val(),
phone: $('[name=phone]').val(),
},
success: function (response) { //response is value returned from php
$( "#dialog-success" ).dialog({
modal: true,
buttons: {
Ok: function() {
$( this ).dialog( "close" );
}
}
});
}
});
$( this ).dialog( "close" );
}
These variables should now be available in your PHP script as $_POST['name'], $_POST['email'] and $_POST['phone']
Whats the point for form if you're sending with ajax?
On the problem now, get the inputs by:
var fields = [];
$("#dialog-form form fieldset > input").each(function() {
fields.push( $(this)[0].value );
});
...
$.ajax({
url: 'process-form.php',
data:fields
...

Categories