I am attempting to construct an ajax form that integrates with the mailchimp API via a PHP script. I am passing variables successfully from AJAX using the form below:
<div id="mailchimp_form">
<p>Enter your email address below to get first dibs!</p>
<form>
<input type="email" value="" name="EMAIL" placeholder="Enter your email address to get first dibs...">
<button class="btn">Submit</button>
</form>
</div>
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#mailchimp_form .btn").click(function (){
dataString = $("#mailchimp_form form").serialize();
$.ajax({
type: "POST",
url: "includes/subscribe.php",
data: dataString,
success: function(returnval) {
alert(returnval);
}
});
});
});
</script>
I know this because when I echo $_POST["EMAIL"] I get a response. When I pass the variable to the API call that is when I have a problem. The entire script just dies, no errors from the API, no errors from php, absolutely nothing, I know it dies because nothing echoes after the api call. What's ever stranger is when I run the API call with $my_email = "test#testemail.com" and run the PHP script by itself, everything works fine. All other API calls also work fine with ajax, listSubscribe is the only one I have any issues with. IF I type in an non-email into the email field the listSUbscribe api function reports it as an error (validation on the API's part is clearly working as well), but if i do type an email, absolutely nothing happens. No users are added to the list and nothing is in my inbox, spam or trash folders.
Can anyone give me even a slight clue as to what the issue could be, im completely lost on this one. The PHP code is beow:
function test($apikey,$listId) {
$api = new MCAPI($apikey);
$my_email = $_POST["EMAIL"];
$merge_vars = array("FNAME"=>'Sichard', "LNAME"=>'Wright');
$api->listSubscribe( $listId, $my_email, $merge_vars );
echo $my_email;
echo $api->errorCode;
}
test($apikey,$listId);
My includes:
require_once 'MCAPI.class.php';
require_once 'config.inc.php'; //contains apikey
Prevent the form to be submitted :
$("#mailchimp_form .btn").click(function (e){
// your ajax...
e.preventDefault();
return false;
});
Related
I've had a look around and unfortunately the solutions I've found on the site don't appear to address my issue below.
Basically I'm doing a project where I need to effectively set up a diary - the user writes in a textarea element and this is passed via PHP to a database and stored for the user. In the lecturer's video, it appears he's doing without using a submit button (even if he's not, I think it'd be an interesting thing to learn how to do).
I'm having some issues though. Here's my PHP:
<?php
session_start();
if(array_key_exists("id", $_COOKIE)) {
$_SESSION['id'] = $_COOKIE['id'];
}
if(array_key_exists("id",$_SESSION)) {
echo "Logged in: <p><a href='secretDiaryFinal2.php?logout=1'>
Log out</a></p>";
} else {
header("Location: secretDiaryFinal2.php");
}
/* I'm putting in the database update later, for now I just wanted to check if I could
actually create the POST variable below*/
$msg = "";
if(array_key_exists('diaryEntry',$_POST)) {
$msg = $_POST['diaryEntry'];
} else {
$msg = "Some kind of PHP error";
}
?>
The relevant HTML:
<body>
<div id="testDiv">
<? echo $msg ?>
</div>
<div class="container" id="diaryArea">
<form method="post">
<textarea id="diary" value=""></textarea>
</form>
</div>
The relevant JQuery (I'm very weak on Ajax and I suspect there's a lot of issues here - also note the url I'm using is actually in the same script as the JQuery, I'm not certain if that works?) is below.
The basic idea is that every time the user types, the database should be updated (I realise this is a lot of calls to the server, I'll probably replace it with a timed command):
<script type="text/javascript">
$("#diary").keyup(function () {
var dataString = $("#diary").val();
$.ajax({
type: "POST",
url: "loggedInPageFinal.php",
data: ({diaryEntry:dataString}),
success: function(data) {
console.log(data);
}
});
return false;
});
</script>
Many thanks in advance and apologies for my poor code!
var DataString = $("#diary").val();
$.post( "loggedInPageFinal.php",{dataString:DataString }, function( data ) {
console.log(data);
});
Your ajax script actually does work.
But your php code isn't returning anything. put exit($msg); at the end of the code and see what happens.
I cannot for the life of me figure out what is going on here. I'll open a different browser to check if what I changed works, and maybe my other browser cached something, and it will work! But then I do it again and it doesn't seem to. I'm going crazy.
On my website, syllableapp.com, I created a MySQL database I could connect to. I made a PHP script that connects to it, adds a simple entry to it, and is done. It's called register_email.php, and it's available to access here. Accessing it manually via that URL will add the entry. Its code is as follows:
<?php
$db = new mysqli("localhost", "username", "password", "table");
if ($db->connect_error) {
echo "Could not connect to database.";
exit;
}
else {
$db->query("INSERT INTO emails (email) VALUES ('weird')");
echo 1;
}
?>
If I check, it gets added.
However, I want it to be added from a form. I have an HTML file at http://syllableapp.com/test/index.html that looks like this:
<html>
<head>
<title>Syllable - iPhone Speed Reader</title>
<link rel="stylesheet" href="styles/style.css">
<script type="text/javascript" src="scripts/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="scripts/scripts.js"></script>
<script type="text/javascript" src="scripts/jquery-ui-1.8.23.min.js"></script>
</head>
<body>
<div class="content">
<img src="images/app-icon.png" alt="App icon">
<h1>Syllable</h1>
<p>Speed reading app for iPhone. Devour all your Instapaper and Pocket articles, and learn to read much faster in the process.</p>
<form method="post" action="">
<input type="email" class="email" placeholder="Email me when it's live">
<input type="submit" class="submit" value="Send">
</form>
</div>
</body>
</html>
So when the user submits the form, the JavaScript file I linked to at the top intercepts the submit button press, and calls an AJAX function to submit it to the PHP form. The jQuery for that looks like:
$(document).ready(function() {
$('input[type="submit"]').click(function() {
var email = $.trim($('.email').val());
var emailRegEx = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if (email == "" || !emailRegEx.test(email)) {
event.preventDefault();
$(this).effect("shake", { times:2 }, 75);
}
else {
$.ajax({
type: "POST",
url: "http://syllableapp.com/test/register_email.php",
data: { "message": "hi" },
success: function(data) {
alert("success");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("failure");
}
});
}
});
});
Which basically just checks if it's a valid email address, then if so, calls the PHP file.
However, every time I click submit, it says failure. Why on earth is this happening? Why can I access it directly, but it won't let me use AJAX?
Just a guess, but in your AJAX block change the URL line to this:
url: "register_email.php",
Also, as a test,
(1) change your alert command in the AJAX success function to:
alert(data);
and (2) insert this line immediately following the <?php directive in the file "register_email.php":
die('Made it to here');
A few things:
1) You're form needs an action or else it's not proper HTML. You can set it to a value like "#"
2) When you click the submit button, you want the form submitted using custom ajax, and not through the standard way. Your ajax handler for the click event should be something like:
$('input[type="submit"]').click(function(event) {
event.preventDefault();
//...
});
You have event.preventDefault in your code, but the event variable isn't being passed to the function. And I think you want event.preventDefault called every time, not just in the case of input validation failure.
3) Instead of using alerts, try using console.log and monitoring your javascript console to see if you get any errors. Add those errors to your question to help us with your issue.
I am trying to simply send an email to a hardcoded email address as a function of a report bug button. However, the text I try to input to the php file that sends the email wont transmit through, and the email function in my javascript file is sending two emails at once. Not sure why either of these are happening.
Here is all my code pertaining to the email function.
Bug page (HTML)
<div data-role="page" id="bug">
<div data-role="header" data-position="fixed">
<h4>Submit a bug</h4>
</div>
<div data-role="content">
<textarea name="textarea" id="textarea"></textarea>
Send
<script language="javascript" type="text/javascript">
$("#send").click(function(){
email();
});
function clearText()
{
$('textarea#textarea').val('');
}
</script>
</div><!-- /content -->
</di> <!-- /bug -->
The above page is called when a user hits the "report bug button", which looks like this:
Report bug
Javascript file with email function:
function email(){
var name = "Joey";
var email = "example#gmail.com"
var vardata = $("textarea").val();
$.ajax({ type: "POST", url: "email.php", data: vardata, success: function() {
alert("Your bug report was sent!");
}
});
return false;
}
and my PHP file that is called:
<?php
$message = $_POST["vardata"];
mail("example#gmail.com", "Mystery person", $message);
?>
If the $message field is hardcoded in, I can get text in the emails just fine, but it can't grab it from the vardata tag. Also, it submits twice, as you can see here. Just click the report bug button and hit send.
When you send data to PHP through jQuery's ajax method, it's helpful to make it a JSON object, so you can get the values you need from the $_POST array in your PHP.
For example:
var name = "Joey";
var email = "example#gmail.com"
var vardata = $("textarea").val();
$.ajax({
type: "POST",
url: "email.php",
data: {name:name, email:email, vardata:vardata},
success: function() {
alert("Your bug report was sent!");
}
});
In this way, you can get the data in your PHP code like this:
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['vardata'];
In your PHP file you are getting the $_POST["vardata"], but in your javascript the field is called data. So use $_POST["data"] instead.
while analyzing the console panel it seems there are two ajax calls made this is because id="send" has a click event attached twice
So here is the trick to do first unbind all the click events on id="send" anchor then attach the click event which will resolve the twice email problem
$(document).ready(function(){
$("#send").unbind("click");
$("#send").click(function(){
email();
});
});
You need to send the data to the server with a name:
$.ajax({ /* ... */, data: {vardata: vardata}});
As for the double sending, you are wiring the click event twice, although I do not see where the second event is wired, but I suspect that it is autogenerated and then thrown away once.
You can see events wired by calling jQuery._data($("#send")[0], "events"); in your debug console. Two events are wired and both handler functions are identical (they call email();).
I found a tutorial here : http://tutorialzine.com/2009/08/creating-a-facebook-like-registration-form-with-jquery/ (please take a look)
It's a nice tutorial, I followed everything there and remove extra stuff I don't want , like the functions.php with generate_function option as I am not in need of birthday etc. stuff.
All I want is a NAME(usrname) , EMAIL(email) , Password(password) , when the user click on "REGISTER" button (which is the form submit button), the script I got from the tutorial will send the data over to "regprocess.php" which contains validation check codes like checking if the submitted form data is empty.
But when I click REGISTER , the data is not sent back (the error message) from the "regprocess.php" nor the success message.
When i check with my firebug , the JSON response is showing the full php code like the one below(scroll down).
Here's my code :
HTML-
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript" src="register.js"></script>
<form id="regForm" action="regprocess.php" method="post">
<label for="usrname">Name:</label>
<input id="usrname" name="usrname" type="text" value="" class="nor">
<label for="email">Email:</label>
<input id="email" name="email" type="text" value="" class="nor">
<label for="password">Password:</label>
<input id="password" name="password" type="password" value="" class="nor">
<table><tr><td style="width:290px;"><div id="error"> </div></td><td><input name="register" type="submit" value="Register" id="regbtn"><center><img id="loading" src="images/load.gif" alt="Registering..." /></center></td></tr></table>
</form>
Okay the Ajax script is in "register.js" above.
Ajax script(register.js)-
$(document).ready(function(){
$('#regForm').submit(function(e) {
register();
e.preventDefault();
});
});
function register()
{
hideshow('loading',1);
hideshow('regbtn',0);
error(0);
$.ajax({
type: "POST",
url: "regprocess.php",
data: $('#regForm').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
hideshow('loading',0);
hideshow('regbtn',1);
}
});
}
function hideshow(el,act)
{
if(act) $('#'+el).css('visibility','visible');
else $('#'+el).css('visibility','hidden');
}
function error(act,txt)
{
hideshow('error',act);
if(txt) $('#error').html(txt);
}
CSS:
Regbtn is the submit button , it's visibility is set to visible
loading is set to hidden
error is set to hidden
When a user click on Regbtn , loading visibility will become visible while Regbtn hides(visibility:hidden).
It's done in the Ajax script(register.js).
Okay now the php:
PHP(regprocess.php)-
if(empty($_POST['usrname']) || empty($_POST['email']) || empty($_POST['password']))
{
die('{status:0,"txt":"Fill in All Fields"}');
}
if(!(preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $_POST['email'])))
die('{status:0,"txt":"Please Provide a Valid Email"}');
echo '{status:1,txt:"registered.html"}';
This checks whether the username , email and password data is empty , if yes , returns a message which will be displayed in the Error(#error in html) , it also checks whether email provided is valid.
If everything else is right , user will be directed to registered.html
But i think the script can't get the error message back from the php.
I hope someone can help me. Thanks.
Have a nice day.
hmm not too much of an answer but what I do on my forms is a I submit via ajax and put the result from the php page in the parent of the form.
below is the plugin in code. it works when the form is a child of a div by default.
(function($){
$.fn.extend({
//pass the options variable to the function
ajaxForm: function(options)
{
//Set the default values, use comma to separate the settings, example:
var defaults =
{
target: 'div'
}
var options = $.extend(defaults, options);
return this.each(function()
{
var o=options
$(this).submit(function(event)
{
event.preventDefault();//stop from submiting
//set needed variables
var $form = $(this)
var $div = $form.parent(o.target)
$url = $form.attr("action");
//submit via post and put results in div
$.post( $url, $form.serialize() , function(data)
{ $div.html(data) })
})
});
}
});
})(jQuery);
note this will run for every form so change it as you would wish.
whatever you want to display just echo on the php page. also this is made for post and the php page will access anything just like any other form being with post.
also it wouldn't be hard to modify if you felt necessary to send as json instead.
You need to put php tags around the php code, like this:
<?php
if(empty($_POST['usrname']) || empty($_POST['email']) || empty($_POST['password']))
{
die('{status:0,"txt":"Fill in All Fields"}');
}
if(!(preg_match("/^[\.A-z0-9_\-\+]+[#][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $_POST['email'])))
die('{status:0,"txt":"Please Provide a Valid Email"}');
echo '{status:1,txt:"registered.html"}';
?>
I feel like this is something that I should have learned by now, and I'm sure it's something small I'm missing, but I could use clarification to make sure my approach is correct.
I'm using AJAX to post data to self which is a file that contains php and html. I can write the php fine, but after a successful ajax post, how do I only return the data that is processed via php and not the remaining html? Is it better to just post to a separate script?
If you have the PHP handling the POST request in the beginning of the file, you can just do something like this:
<?php
if (isset($_POST['somevar'])) {
/* do something */
exit(0);
}
?>
exit() will stop the loading of the page at that line.
I, for one, think it's better to be utilizing a separate script to deal with dynamic AJAX requests.
You can scrape changed parts of the resulting document and insert them into the original page. This way you can also make your page work for a user with JavaScript disabled not doing anything specially.
Example:
<html><title>Unobtrusive AJAX Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script><script type="text/javascript">
$("form.ajax[id]").live('submit', function() {
$(this).find("input[type='submit']").attr("disabled", true);
$.ajax({
type: $(this).attr('method') || 'POST',
url: $(this).attr('action') || window.location.pathname,
data: $(this).serialize(),
context: $(this),
success: function(data) {
$(this).html(
$(data).find("#" + $(this).attr("id")).html()
);
}
});
return false;
});
</script>
</head><body>
<div><form method="post" class="ajax" id="main">
<p><?php echo date('H:i:s'); ?></p>
<p><input type="submit"></p>
</form></div>
<!-- keep the div: you got to have at least one div to make it work -->
</body></html>
It always depends on what are your needs, but if using the same script is enough for you then do it.
If you want the script not to send anything more than your answer to an XML HTTP Request, after sending the data, use an exit(); in PHP, which will make the script finish at that point.
Put to the of the script:
if($_POST['id']) {
$data = array('return'=>'returnValue');
$data = json_encode($data);
exit($data); }
Javascript:
$.ajax({
url: 'frmSelf.php',
data: $("#frmSelf").serialize(),
dataType: 'json',
type : 'post',
success : function(returnData) {
console.log(returnData);
}
});