jQuery/AJAX send autogenerated Email without form and stay on page - php

I know this is a widely covered subject, but I kept searching the Web and couldn't find a solution for my specific problem.
What I am trying to do with jQuery/AJAX (as mentioned in the title):
I DON'T want any sort of Form that the user can fill out.
I just want a button (some HTML-Element) that when clicked sends an automatically generated mail to a predefined addess.
Neither the content nor the subject or anything else needs to be "filled in" by the viewer/user.
There will only be one variable (a script will insert the right value) that should be put somewhere in the content of the Email.
On clicking the button, the mail should be sent, the button should be replaced by a "Thanks whatever..."-message and that's IT!
No redirecting to another page or whatnot.
What I found that might be useful so far:
$.ajax({
type: "...",
url: "...",
cache: ...,
contentType: "...",
data: "{ 'body':'" + myMsg + "'," +
"'to': '" + myAddr + "'," +
"'from': 'AUTOMAILER'," +
"'subject': " + mySubject + mySpecVar + "'" +
"}",
dataType: "...",
complete: function (transport) { if (transport.status == 200) $("#myButtonContainer").html("Success"); else alert("Please try again later"); }
});
Let's say my HTML is:
<p id="notify">Notify!</p>
And my JS-part would start something like this:
<script>
$(document).ready(function(){
$("#notify").click(function(){
// THE JQUERY/AJAX STUFF HERE?
});
});
</script>
I assume I need at least some sort of a .php-File as well? Apparently I still don't get it...
I still very much lack experience and would be very grateful for a solution, or even for a nudge in the right direction!
If this problem has already been solved for someone on this site, I apologize. I didn't find it.
EDIT : This should all happen on the client-side (as far as possible). Meaning that the Email content is ultimately generated on the client-side. Sorry, forgot to mention.

You forgot to mention something important. That "script" that generates the email content is it client or server side?
All you need is the clickable element:
<button type="button" onclick="doStuff()">Send</button>
The ajax method:
<script>
function doStuff()
{
//var data =... ANY DATA YOU MIGHT NEED
$.ajax({
type: "POST",
url: "sample.php",
data: data,
dataType: "text"
});
}
//ADD here some jquery to change the button text
</script>
And then you can easily find a php script to send email. You can hardcode the email address if it never changes

Your $.ajax approach is fine, but you need a server action (set in the "url") that will finally send the mail. The browser can't do it alone.

Email sending is done server side ie php. post to an email.php file which then sends the email. Make sure to use json functions in php too if you need to do a callback.

Related

Ajax form gets sometimes urlencoded

I have an own made ticket system and lately I have an annoying thing going on. What's happening is that sometimes when making reply, all spaces are being replaced with the + sign. So far it is only happening recently and only at certain messages, so not all of them. I haven't been able to detect a special condition or character in the messages where it is happening.
The code is as following:
$(document).on('submit', '#newticket, #addreply', function () {
$(".loadingadd").show();
var eid = $(this).attr("id");
var xform = $(this).serialize();
$("#"+eid+" :input").prop("disabled", true);
$.ajax({
type: "POST",
url: "/a/tickets",
dataType: "json",
data: xform,
success: function(data) {
The Form:
<form class="form-inline" role="form" action="" method="post" id="addreply">
I'm using Firefox 50.1.0.
I have not been able to catch the event in Firebug in action, so there is a chance the server side is causing it, but I doubt that since it's not happening every time.
Does anyone know if a browser can decide to urlencode a POST or something? Or should I always encode in JS and decode server side? If so, how to do this with the serialize?
How to encode value with jquery serialize?
I saw this, but I don't have that currently and yet I only sometimes have the + signs. And doesn't that replace removes valid + uses?
Basically I'm now just using the serialize to send the form, and using $_POST['message'] to get the contents, not using any decoding or encoding.
Or should I specify an enctype? If I read http://www.w3schools.com/tags/att_form_enctype.asp the + sign is only not replaced when using multipart/form-data?
Anyone knows whats going on here and what I should use for forms, ajax encoding and server side (php) decoding? Whats best practice?

Sending data via ajax using php

So, here is ajax setup that I have for my wordpress site.
Page_1.php:
<?php echo '<div class="button" data-post_date="'.$rh_post_date.'" data-post_author_id="' .$rh_author_id. '" data-post_id="' .$id. '">' ;?>
custom_js.js:
jQuery('.button').click(function(e) {
e.preventDefault();
var indiv_id = jQuery(this).data("post_id");
var indiv_post_author = jQuery(this).data("post_author_id");
var indiv_date = jQuery(this).data("post_date");
jQuery.ajax({
type: "GET",
url: upload_image.ajax_url,
dataType: 'html',
data: ({ action: 'rhmp_indi_form', post_id: indiv_id , post_author_id: post_author, post_date_id: indiv_date}),
success: function(data){
jQuery('#rh_pop').html(data);
},
error: function(data)
{
alert("Error!");
return false;
}
});
});
Page_2.php:
<div id="rh_pop">
<?php
$page_2_post_id = $_REQUEST['post_id'];
$page_2_post_author_id = $_REQUEST['post_author_id'];
$page_2_post_date_id = $_REQUEST['post_date_id'];
?>
</div>
As you can see, when the button in the page_1.php is clicked, the data become variables in custom_js.js. These variables are then sent to the page_2.
Now, I know that this is not secure at all and can be hacked easily.
So, how do I send data such as data-post_date or post_author_id to another page via ajax using php?
First of Ajax is a technique that is used in javascript to send a httprequest to the php server. The server handles that request and sends back its result. Its the same as requesting a page normally but then its without reloading the page.
Creating variables in javascript with php for use with ajax doesn't mean that php is the one doing anything ajax related. Hope this clears up a missunderstand.
More info on this: https://en.wikipedia.org/wiki/Ajax_%28programming%29
Sending data to the server is never safe. You can make help features like you need to fill in this field with a name and go on. Or maybe even use a disable the submit button if there aren't 3 or more numbers in a field but this is all to help the user and to make it unlikely that the server will get requests that will never be valid anyway.
This is the reason why server side validation is always needed and client side validation is more of a user friendly thing and making sure the server doesn't get requests that can be detected from the client side already.

Speeding up a form fill submission with email response in PHP?

I'm incredibly new to PHP, so I'll try and be as clear as possible. Through a bit of trial and error, I created a simple form on a website I manage where people can provide a few bits of information (about four lines total). In turn, I will receive an email using ()mail with the information, which I intend to use for remarketing purposes.
The problem? It takes a good 20-30 seconds for the person who filled out their info to be taken to the Thank You page. I still end up receiving the email, but people are definitely not going to wait around for the Thank You page to load before closing the window. This is obviously not good if I'm planning on tracking conversions.
Any suggestions? A friend suggested I set up a MySQL database to collect the info, but that's way beyond my level of expertise. Are there alternatives that can help?
Many thanks.
If the form submits to PHP you could use an AJAX script of which runs the PHP page. You can setup BeforeSend to show a div that simply says "Loading please wait..." and the user is more likely to wait. I'm not saying this is the best solution but its one.
AJAX Script:
<script>
$(document).ready(function() {
$('#submitBtn').click(function() {
var variable1=$("#variable1").val();
var variable2=$("#variable2").val();
var dataStr = 'variable1='+variable1+'&variable2='+variable2;
if($.trim(variable1).length>0 && $.trim(variable2).length>0) {
$.ajax({
type: "POST",
url: "process.php",
data: dataStr,
beforeSend: function(){ $("#submitBtn").val('Loading Please wait...');},
success: function(data){
if (data!="success") {
$("#submitBtn").val('Submit')
} else {
window.location.href = "http://example.com/thankyou";
}
}
});
} return false;
});
});
</script>
I've provided you with an AJAX example above. In the PHP script you simply need to get it to echo "success" if the email is sent. If the script ends and nothing is sent back or something else is echo'd then it will set the submit button back to "Submit".
I recommend you create a div below the submit button of which is empty by default or not visible but if the AJAX fails it is shown.

Upload file using jQuery and Ajax

I have a form that I am sending to the server using jQuery $.post method. I am sending several fields with something like:
var myName = "Pedro";
var myDescription = "Description of Pedro";
$.post("~/insert_user", { name: myName, description: myDescription }, function(data){
alert("Successfully inserted " + data.name + " in DB");
}, "json");
This works great, as I take the values in insert_user.php and treat and insert the in the data base.
What if I need to add a field to my form to let the user upload an image?
How would I do that in my $.post call and how would I get it in the PHP?
I am using Symfony2.0, by the way, just in case it changes something. But the important part is how to add a file typed field to the ajax call.
Thanks in advance.
Pedro
You will find it would be a lot easier to use a pre built jquery plugin. My favourite is uploadify http://uploadify.com.
Its simple and easy to use and it will save you a lot of time trying to figure out a method of your own <>
$.post is the same as the code block bellow. In order for you to do what you need to you need to change it to use this atleast and then things will become simpler. So start by changing the $.post to this
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
Then add a parameter in the ajax block contentType : "multipart/form-data" or try mimeType (cant remember so clearly) and in the data : $("#form").serialize(), that should work.
please tell me if it didn't work
--NEW EDIT LOL-- Excuse my blind coding, you may need to test this
I did a bit more research and came across this. You need to build this array and add it to the data in your ajax block
var files = new FormData($('#fileinputid'));
jQuery.each($('#fileinputid')[0].files, function(i, file) {
files.append(i, file);
});
If what i read was accurate you should be able to pass that array with the rest of the ajax data. Although i am not completely sure how to add it to the serialized data.
Please test this and let me know. if it doesn't work ill do a full javascript script test for you and then post it here
This tutorial might help: Nettuts+: Uploading Files With AJAX
Make iframe and put form in it, submit the form and voila. Or you can use one of these AJAX File upload scripts
I finally used this:
http://malsup.com/jquery/form/#faq
It just works great for what I need.
Thank you guys for your help.

Getting a value from a variable , send to php to process and add that value to mysql database?

i am new to php and mysql.
How can i extract a VALUE from a JAVASCRIPT VARIABLE(i set) then send it to a PHP page that can read it and process it , the PHP will then insert the value into a table in MySQL database.
var A = "somevalue"
I have been researching but none of it give me a simple and direct answer . I saw some people uses JSON(which i am unfamiliar with) to do this.
Hopes someone can give me an example of the javascript/jquery , php code to this. Thanks!
You've asked for... a lot. But, this tutorial looks like it could help you.
(FYI -- I swapped out the original tutorial for one on ibm.com. It's better but far more wordy. The original tutorial can be found here)
I'm not pretty sure if it works but just try this. Your jQuery script shoul be like this:
$(function(){
var hello = "HELLO";
$.post(
"posthere.php",
{varhello: hello},
function(response){ alert(response); }
)
});
and "posthere.php" is like this:
$varhello = $_POST['varhello'];
echo $varhello . ' is posted!';
you should then get an alert box saying "HELLO is posted!"
What you need is Ajax. This is an example jQuery to use:
function sendData(data) {
$.ajax({
type: 'POST',
data: data,
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
This will send post data to that url, in which you can use PHP to handle post data. Just like in forms.
If you have a form:
<form id="theformid">
<input type="text">
</form>
Then you can use jQuery to send the form submit data to that sendData function which then forwards it to the other page to handle. The return false stops the real form from submitting:
$("#theformid").submit(function(){
sendData($(this).serializeArray());
return false;
});
If you though want to send just a variable, you need to do it like this:
function sendData(data) {
$.ajax({
type: 'POST',
data: {somekey: data},
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
Then when you are reading $_POST variable in PHP, you can read that data from $_POST['somekey'].
Inside the success callback function you can do something with the data that the page returns. The whole data that the page returns is in the data variable for you to use. You can use this for example to check whether the ajax call was valid or not or if you need to something specific with that return data then you can do that aswell.

Categories