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();).
Related
I have a form with multiple types of ajax calls.
- general form update that saves all input fields
- per-field uploads
- per-upload deletion
The per-field and per-upload ajax calls are targeted by the class name of the button that is clicked. So there are only 3 scripts in the page.
Each of the scripts work. When the page loads fresh, I can complete any of the form update, field upload, or upload deletion actions.
However, after I have completed an initial action, subsequent actions don't work.
Example:
If I click the "save" button to update the form, this causes the per-field upload and per-upload deletion buttons not to work.
If I click the "per-field" upload, the upload works, but then I'm not able to delete anything.
If I click a "per-upload" delete button, I can no longer upload anything.
But in each case, I am still able to click "save" to update the form.
Here's a visual of how the page is set up:
When a file or image is uploaded to a field, it appears in a container div within the field's markup. The uploaded asset comes with a 'delete' button allowing the user to remove the upload.
Here's the basic HTML of the page
<form id = "form" action = "/process.php" method = "post">
<div class="field">
<label class="field-label">
<span class="field-label-text">Upload 1</span>
<input type="file" data-name="answer1" name="files_answer1[]" />
</label>
<!-- destination for ajax response messages -->
<div id="ajax-message-answer1" class="ajax-field-message"></div>
<!-- upload button -->
<button type="button" class="ajax-button" data-field="answer1" data-type="files">Upload</button>
<!-- container div for uploads -->
<div class="assets" id="assets-answer1">
<div class="asset file">
Name of file
<label class="asset-action">
<!-- deletion button to remove asset -->
<button type="button" data-asset="asset1" data-parent="answer1" class="ajax-delete" value="asset1" onclick="return confirm('You are about to delete this item. Press OK to proceed.')">Delete</button>
</label>
</div><!-- .asset.file -->
</div><!-- .assets -->
</div><!-- .field -->
.... more fields of the same kind ...
<button type = "submit" id = "save">Save</button>
</form>
JS
There are several other scripts in the page, such as jQuery, jQuery UI, Bootstrap, and some custom ones for generating slugs, etc. But I'm thinking these aren't to blame since the problem began only when I started running more than one Ajax request in the page. Here's the JS:
Form Update script
<script type="text/javascript">
$(document).ready(function() {
// process form
$('#form').submit(function(eform) {
// stop regular form submission
eform.preventDefault();
// set variables
var form = $('#form');
// serialize form data
var fdform = form.serializeArray();
// make request
$.ajax({
url: '/account/ajax.php',
type: 'post',
data: $.param(fdform),
dataType: 'json',
success: function(data) {
// get URL for redirect if supplied
if (data.redirect) {
window.location.href = data.redirect;
} else {
// replace with updated template from response
$('#form').html(data.html);
// place template js in specified div
$('#ajax-js').html(data.js);
}
},
error: function(report) {
console.log(report.responseText);
}
});
}); // .click
}); // .ready
</script>
Per-Field Upload script
<script>
$(document).ready(function() {
$(".ajax-button").click(function() {
var fdUpload = new FormData();
// get field info from the clicked button
var field = $(this).data('field');
var uploadType = $(this).data('type');
var input = $('#' + field)[0];
var container_id = '#assets-' + field;
var button_id = '#button-' + field;
// add each file to uploads array
$.each(input.files, function(i, upl) {
// add each file to target element in fdUpload
fdUpload.append(uploadType + '[]', upl);
});
// make request
$.ajax({
url: '/account/ajax.php',
type: 'post',
data: fdUpload,
dataType: 'json', // returns success(data) as object
contentType: false,
processData: false,
success: function(data) {
// put received html in container
$(container_id).html(data.html);
// put received js in #ajax-js
$('#ajax-js').append(data.js);
// clear file input after upload completes
input.value = '';
if (!/safari/i.test(navigator.userAgent)) {
input.type = '';
input.type = 'file';
}
},
error: function(report) {
console.log(report.responseText);
}
});
});
});
</script>
Per-Upload Deletion script
<script>
$(document).ready(function() {
$(".ajax-delete").click(function() {
var fdDelete = new FormData();
// get asset info from clicked button
var asset = $(this).data('asset');
var parent = $(this).data('parent'); // answer
var container_id = '#assets-' + parent;
var button_id = '#delete-' + asset;
var message_id = '#ajax-message-' + asset;
// make request
$.ajax({
url: '/account/ajax.php',
type: 'post',
data: fdDelete,
dataType: 'json',
contentType: false,
processData: false,
success: function(data) {
// put received html in container
$(container_id).html(data.html);
// put received js in #ajax-js
$('#ajax-js').html(data.js);
// retrieve and display response status
$(message_id).html(data.status);
$(message_id).addClass('show');
},
error: function(report) {
console.log(report.responseText);
}
});
});
});
</script>
Summary
Again, each ajax request works when activated after a fresh page load. But after the form has been updated or after an upload or deletion, the upload and deletion no longer fire.
The 'error' callback doesn't display anything in console when this failure occurs.
Do you see a conflict somewhere in the scripts? Maybe the scripts need function names defined? Or is it a problem that the returned response object is called 'data' in each script?
I haven't been working with Ajax very long, so I'd really appreciate your help. I've been banging my head on this all day.
You're using $(".ajax-...").click(...) but in ajax success handler you're updating HTML code for container, thus loosing any attached click handlers for elements in this container.
If you switch to using $("#form").on('click', '.ajax-...', ...) then you'll catch click events even after directly replacing HTML.
jQuery.on() documentation
I need to pass some variables to my mail.php script to use them for email composing, but as soon as I enter e-mail my script brokes down.
Seems like it converts the email automatically to URL and after that it will crash my JS or where am I wrong?
Below is code snippet (what causes problems):
$(document).on('click', '.kinnitus', function(){
var kood = '<?php echo $params->get('Kood');?>';
var info = '<?php echo $params->get('info');?>';
if(confirm("Saada kinnitus meilid?"))
{
$.ajax({
url:"mail.php",
method:"POST",
data:{kood:kood, info:info, mail_from: 'mail#domain.com'},
success:function(data)
{
$('#alert_message').html('<div class="alert alert-success">Kinnitus meilid saadetud</div>');
$('#user_data').DataTable().destroy();
fetch_data();
}
});
setInterval(function(){
$('#alert_message').html('');
}, 5000);
}
});
and thats what happens after i add
, mail_from: 'mail#domain.com'
without email it works like a charm.
So, # symbol was cause of this wierd situation.. so..
i used litle "workaround".
$mail_to_pass = rawurlencode($mail_from);
and decoded it on my mail.php.
so my mail was on passing mail%40domain.com
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 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;
});
I am trying to pass two variables (below) to a php/MySQL "update $table SET...." without refreshing the page.
I want the div on click to pass the following variables
$read=0;
$user=$userNumber;
the div Basically shows a message has been read so should then change color.
What is the best way to do this please?
here's some code to post to a page using jquery and handle the json response. You'll have to create a PHP page that will receive the post request and return whatever you want it to do.
$(document).ready(function () {
$.post("/yourpath/page.php", { read: "value1", user: $userNumber}, function (data) {
if (data.success) {
//do something with the returned json
} else {
//do something if return is not successful
} //if
}, "json"); //post
});
create a php/jsp/.net page that takes two arguments
mywebsite.com/ajax.php?user=XXX&secondParam=ZZZZ
attache onClick event to DIV
$.get("ajax.php?user=XXX&secondParam=ZZZZ". function(data){
// here you can process your response and change DIV color if the request succeed
});
I'm not sure I understand.
See $.load();
Make a new php file with the update code, then just return a json saying if it worked or not. You can make it with the $.getJSON jQuery function.
To select an element from the DOM based on it's ID in jQuery, just do this:
$("#TheIdOfYourElement")
or in your case
$("#messageMenuUnread")
now, to listen for when it's been clicked,
$("#messageMenuUnread").click(function(){
//DO SOMETHING
}
Now, for the AJAX fun. You can read the documentation at http://api.jquery.com/category/ajax/ for more technical details, but this is what it boils down to
$("#TheIdOfYourImage").click(function(){
$.ajax({
type: "POST", // If you want to send information to the PHP file your calling, do you want it to be POST or GET. Just get rid of this if your not sending data to the file
url: "some.php", // The location of the PHP file your calling
data: "name=John&location=Boston", // The information your passing in the variable1=value1&variable2=value2 pattern
success: function(result){ alert(result) } // When you get the information, what to do with it. In this case, an alert
});
}
As for the color changing, you can change the CSS using the.css() method
$("#TheIdOfAnotherElement").css("background-color","red")
use jQuery.ajax()
your code would look like
<!DOCTYPE html>
<head>
</head>
<body>
<!-- your button -->
<div id="messageMenuUnread"></div>
<!-- place to display result -->
<div id="frame1" style="display:block;"></div>
<!-- load jquery -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
//attach a function to messageMenuUnread div
$('#messageMenuUnread').click (messageMenuUnread);
//the messageMenuUnread function
function messageMenuUnread() {
$.ajax({
type: "POST",
//change the URL to what you need
url: "some.php",
data: { read: "0", user: "$userNumber" }
}).done(function( msg ) {
//output the response to frame1
$("#frame1").html("Done!<br/>" + msg);
});
}
}
</script>
</body>