Speeding up a form fill submission with email response in PHP? - 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.

Related

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

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.

Page Refresh & Pop Up Success Message After Submit

I wonder whether someone may be able to help me please
Firstly, my apologies as this may be a very simple problem to the more seasoned developer, but this is my first website I'm building so please bear with me.
For my site I have a number of forms which all fit around a template I've created. Most forms require the user to click a submit button which then calls a PHP script to save the data into a MySQL database.
An example of code that I use to do this, is as follows:
<form id="addfinds" name="addfinds" method="post" action="savefinds.php">
When the form has been submitted, a line in my addfinds.php script then echoes either Find saved or There was a problem.
I'm working separately on some form validation to cleanse the data before submission, but what I'd like to be able to do is rather than the message being echoed from the PHP script, I'd like a pop up message to appear on screen in it's place, and if the submission is successful for the fields to clear and the page refresh.
I've done quite a bit of reading on this, and I'm a little unsure on how to progress this. I just wondered whether someone, perhaps with a greater experience than I could offer some guidance please or point me in the direction of a good tutorial.
function FUNCTIONNAME() {
$.ajax({
type: "POST",
url: "YOUR METHOD NAME WHICH IS CALLED",
data: "{PARAMETER VALUES TO BE PASSED}",
contentType: "application/json; charset=utf-8",
dataType: "json",
complete: function () {
},
success: function (msg) {
alert("YOUR SUCCESS MESSAGE HERE");
},
error: function (msg) {
alert("Error " + msg.d.toString());
}
});
}

jquery $.ajax request remains pending

I have made a simple chat application which uses long-polling approach using jquery,
function sendchat(){
// this code sends the message
$.ajax({
url: "send.php",
async: true,
data: { /* send inputbox1.value */ },
success: function(data) { }
});
}
function listen_for_message(){
// this code listens for message
$.ajax({
url: "listen.php",
async: true,
timeout:5000,
success: function(data) { // the message recievend so display that message and make new request for listening new messages
$('#display').html(data);
listen_for_message();
}
});
}
THIS SHOULD HAPPEN : after page loaded the infinite request for listen.php occurs and when user sends message, the code sends message to database via send.php.
PROBLEM is, using firebug i've found that send.php request which is performed after listen.php request, is remains pending. means the request for send message is remains pending.
The issue was because of session locking;
both send.php and listen.php files use session variables,
so session is locked in listen.php file and the other file (here send.php file) can't be served after the session frees from serving another file ( here listen.php).
How do I implement basic "Long Polling"?
the link above is a similar question that may help you.
it does not have to be on a database, it can be saved on a tmp file, but your problem is that you are choking the browser by performing too many requests, any one browser handles two requests at a time, which means you should really allow the browser to finish the first requests first then do the second one... and so on...
you do not need to do send.php and listen.php, because you can do it simply on one page both of them.
function check(){
$.ajax({
url : 'process.php',
data : {msg:'blabla'/* add data here to post e.g inputbox1.value or serialised data */}
type : 'post',
success: function (r){
if(r.message){
$('#result').append(r.message);
check();//can use a setTimeout here if you wish
}
}
});
}
process.php
<?php
$msg = $_POST['msg'];//is blabla in this case.
$arg['message'] = $msg;//or grab from db or file
//obviously you will have to put it on a database or on a file ... your choice
//so you can differentiate who sent what to whom.
echo json_encode($arg);
?>
obviously this are only guide lines, but you will exhaust your bandwidth with this method, however it will be alot better because you have only one small file that returns either 0 to 1 byte of information, or more if there is a message posted.
I have not tested this so don't rely on it to work straight away you need a bit of changes to make it work but just helps you understand how you should do it.
however if you are looking for long pulling ajax there are loads of scripts out there already made and fine tuned and have been test, bug fixed and many minds help built it, my advice is don't re-invent the wheel

I want to make a availability button on my registration page

Many websites have an "check availability" button. And I want to have this to. But this seems to be only available when using Ajax and Jquery. Is there any way for me to do this using only PHP and Javascript. Because i'm a starting programmer, which does not have the skills to work with Ajax or Jquery.
What I want, I have a username field. I typ in a username, and I want to check if the name is available. If the person clicks on the check availability button, I want a pop-up that says "This username is available" or "This username has already been taken".
If any knows how to do this in just PHP and Javscript, I would be very obliged to know.
Using ajax (and jquery) is easier than it seems. on your client-side you have a request like this:
$.ajax({
url: 'usernameChecker.php',
dataType: 'GET',
data: 'username=' + $("#yourUserNameFieldID").val(),
success: function(result)
{
alert(result);
}
});
Of course you need to include jquery to implement this. jQuery makes it easy to make ajax-calls.
On your serverside you can use something like this:
<?php
if(isset($_GET["username"]))
{
// check username
if(username_is_free)
// of course this needs to be a bit different, but you'll get the idea
{
echo "Username is free!";
}
else echo "Username is taken!";
}
?>
$(document).ready(function(){
// available-button is the ID of the check availability button
//checkAvailability.php is the file which gets the username param and checks if its available
// user is the id of the input text field where the user enter the username
// available-message is the id of a div which displays the availability message. Use this instead of alert
$('#available-button').click(function() {
$.ajax({
type : 'POST',
url : 'checkAvailability.php',
data: {
username : $('#user').val()
},
success : function(data){
$('#available-message').text(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("Some Error occured. Try again")
}
});
return false;
});
});
Use jQuery ajax, that is the best & easy way to do it.
Using Ajax send a request to a php page which will take username as parameter (get or post method, you can specify in ajax call) and then on server side search for uniqueness of username in database & return appropriate response.
Is there any way for me to do this using only PHP and Javascript.
Because i'm a starting programmer, which does not have the skills to
work with Ajax or Jquery.
I think you'll find making an AJAX request in jQuery a lot more simple than writing one in pure javascript.
As jQuery is an extension on Javascript, you can use minimal jQuery to make the request to the server, and then deal with the response using pure javascript.
Look into using jQuery AJAX:
http://api.jquery.com/jQuery.ajax/
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
Here you would change the success part to something like:
success: function(data){
if (data == 1){
$(".message").html("Available");
}
else {
$(".message").html("Already Taken");
}
}
I would recommend using jQuery for this task.
jQuery (or another Javascript library) will make the task simple to complete compared trying to do it without using one of them.
jQuery docs are good and for there are plenty of online tutorials matching what you want to do.
You will benefit from putting in the time to learn about the jQuery library.

jQuery/Ajax SQL live update via PHP help

I have a table that outputs all my contacts via a while loop from my database.
my syntax is like this:
SELECT * FROM contacts WHERE id = $_SESSION['user_id'] ORDER BY name ASC LIMIT 5
that pulls out all my data and only gives me 5 results.
Now my goal is to have a little button that opens up a model box with jquery (this I can manage on my own) with a form asking the user to input a number then that number will be sent via post or get to $PHP_SELF and update a local variable with the number the user inputed, then that variable will be used to update the database to increase or decrease the LIMIT value.
I have looked all over the web (with google) to look for submitting a form using AJAX but all the examples i've found don't work for me.
When the user submits the number and the sql query is executed and updated for the outputed table to dynamically update according to the new LIMIT value all without ever refreshing the page to the user.
my jquery code is:
(document).ready(function(){
$("form#form").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var val = $('input[name=new_value]').attr('value');
$.ajax({
type: "post",
url: "process.php",
data: "val="+ val,
cache: false,
success: function(){
$('form#form').hide(function(){$('.success').fadeIn();});
}
});
return false;
});
});
$(document).ready(function(){ $("form#form").submit(function() {
// we want to store the values from the form input box, then send via ajax below
var val = $('input[name=new_value]').attr('value');
$.ajax({ type: "post", url: "process.php", data: "val="+ val, cache: false, success:
function(){
$('form#form').hide(function(){$('.success').fadeIn();});
} }); return false; }); });
then my php code is:
$new_val = $_POST['new_val'];
$_val = "UPDATE `settings` SET `display_limit` = {$new_val} WHERE `user_id` = {$_SESSION['user_id']}";
mysql_query($_val) or die(mysql_error());
and my form is simple:
any suggestions? I haven't come to how to have my outputed table dynamically update yet so if anyone can point me in the right direction or provide some help that would be awesome.
thanks
EDIT:
Here is an updated jquery script I was working on, I'm able to submit the form successfully! but my only problem is that I can't see the changes until the page is refreshed with defeats the purpose of the AJAX usage... sigh
how can I now have my #results div updated and refreshed with the form submission content?
$(document).ready(function() {
var options = {
url: 'process.php',
type: 'post',
//dataType: 'json',
target: '#last_five_sellers',
success: success
};
// bind to the form's submit event
$('#form').submit(function() {
// inside event callbacks 'this' is the DOM element so we first
// wrap it in a jQuery object and then invoke ajaxSubmit
$(this).ajaxSubmit(options);
// !!! Important !!!
// always return false to prevent standard browser submit and page navigation
return false;
});
function success(responseText, $form) {
$("form#form").hide();
$(".success").fadeIn();
}
});
In your php code where you do the update, You could echo your contacts in html-format. That would then return to your success function in jquery.
success: function(){
$('form#form').hide(function(){$('.success').fadeIn();});
}
The function have a parameter data, which is the html-format you echoed in php.
Example
success: function(data){
$('form#form').hide(function(){$('.success').fadeIn();});
$(data).appendTo('#result');
}
You need to understand the flow of a request. Once the php script runs, that is it, it is done. If you plan on submitting back to that same page, it'll be a new request and a new execution of that script. Now, you could add a special case to that script to return the necessary data to your jQuery code, but that's messy IMO. I would rather have a separate script to handle that functionality. This can be looked at as a web service.
So, when a you go to that page in a browser, it will intially display 5 contacts (or w/e the default you have in the LIMIT clause). When you click the icon to display more contacts, you employ jQuery to submit a GET request to that 'web service' page (it really should be GET, since you're retrieving data, not submitting new data). This would then be a list of contacts that you use to update the display on the page, using jQuery/JavaScript.
As noted by Codler, the output from that 'web service' can be HTML which you simply use to replace the existing HTML which displays the contacts. (This would be the preferred way. You almost always want do as much on the server as you reasonably can.)
It looks like your jQuery code is duplicated — there's no need to bind the form's submit event twice. Additionally, the first jQuery block is missing the opening dollar-sign ("$"). And as far as I know, .hide() does not support passing a callback through the first parameter. In the jQuery API documentation, it's written as .hide( duration, [ callback ] ).
I would write:
$(function(){
$("form#form").submit(function(){
// we want to store the values from the form input box, then send via ajax below
$.ajax({
type: "post",
url: "process.php",
data: "val=" + $("input[name=new_value]").val(),
cache: false,
success: function(){
$("form#form").hide();
$('.success').fadeIn();
}
});
return false;
});
});
Now, if you want to update your results table dynamically, the simplest way is just to replace the entire thing with the updated HTML. So for instance, if you modified your PHP script (process.php) so that, after updating display_limit, it outputted the new results table, you could then write something like (assuming your results table is table#results):
$(function(){
$("form#form").submit(function(){
// we want to store the values from the form input box, then send via ajax below
$.ajax({
type: "post",
url: "process.php",
data: "val=" + $("input[name=new_value]").val(),
cache: false,
success: function(data){
$("form#form").hide();
$(".success").fadeIn();
$("#results").replaceWith(data);
}
});
return false;
});
});
You just have to make sure your script only outputs HTML.
Contrary to what George answers above, HTML will definitely work for this purpose, but I think the ideal method is to send purely the data alone (minus structure/presentation) in either JSON or XML format, and then use JavaScript to build the HTML; you can save a lot of bandwidth this way, and ultimately build a much more responsive application.
EDIT
Here's a mini JSON-based example.
JavaScript:
$(function(){
$("#form").submit(function(){
var val = $("input[name=new_value]").val();
$.getJSON("process.php?val=" + val, function(data){
$("#results").empty();
$(data.rows).each(function(){
$("#results").append('<tr><td>' + this.column_a + '</td><td>' + this.columbn_b + '</td></tr>');
});
});
return false;
});
});
PHP (process.php):
[assuming you already have a result/rows called $result]
$json = array('rows' => array());
while ($row = mysql_fetch_assoc($result)) {
$json['rows'][] = $row;
}
echo json_encode($json);
Now, granted, I haven't tested this code at all, but it should give you the gist of it.

Categories