JQuery Ajax response not working | Php - php

I have a code like this
<script type="text/javascript">
function email(){
var myTextField = document.getElementById('email_hidden').value;
//alert(myTextField);
$.ajax({
type: "POST",
url: "sendmail.php",
data: "email_user="+myTextField,
success: function(response){
alert(response);
}
});
}
</script>
My sendmail.php code is like this.
<?php
$to = $_REQUEST['email_user'];
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= "From: Haan Test<haan#gmail.com>\r\n";
$message_body = "Your Details";
$subject = "Check mail";
mail($to, $subject, $message_body, $headers);
echo "success";
?>
and my html looks like this.
<div id="email_hide"><a href="#" onclick="email()" >Send Email</a></div>
I am getting the response in my firebug console as success
but i could not alert the response. I can receive the mail also for the above jquery ajax functionality(sendmail.php)
In other words, how to alert the response after ajax call..
I have tried onComplete also. plz help me with this.
My Scenerio is like this:
User page(index1.html) >> Paypal Sandbox (for transaction) >> User page(index2.html)
Here in index2.html, i fetch last transaction details from paypal sandbox with a send mail
at the top right corner, so when user clicks the send mail(anchor tag) the mail should be sent via ajax jquery call.
Thanks
Haan

If ur datatype is json ,then try this
<script type="text/javascript">
function email(){
var myTextField = document.getElementById('email_hidden').value;
//alert(myTextField);
$.ajax({
type: "POST",
url: "sendmail.php",
data: "email_user="+myTextField,
dataType: "json",
success: function(response){
alert(response);
}
});
}
</script>

Try using the shorthand jquery method for post:
<script type="text/javascript">
function email(){
var myTextField = document.getElementById('email_hidden').value;
//alert(myTextField);
$.post("sendmail.php", {"email_user": myTextField}, function(data) {
alert(data);
});
}
</script>

Try add
$.ajax({
type: "POST",
url: "sendmail.php",
data: "email_user="+myTextField,
success: function(response){
alert("Success\n" + response);
},
error: function(errMsg) {
alert("Error\n" + errMsg);
}
});
and see which one gets called.

Related

JQuery function not posting to php

I am not a big Jquery guy but am using a plugin which is an image uploader. It has a button to remove images with correlates with the following code.
function remove_unwanted_file(id,file)
{
if(confirm("If you are sure that you really want to remove the file "+file+" then click on OK otherwise, Cancel it."))
{
var dataString = "file_to_remove=" +file;
$.ajax({
type: "POST",
url: "remove_unwanted_files.php",
data: dataString,
cache: false,
beforeSend: function()
{
$("#vpb_remove_button"+id).html('<img src="images/loadings.gif" align="absmiddle" />');
},
success: function(response)
{
$('div#fileID'+id).fadeOut('slow');
}
});
}
return false;
}
However, none of the code within the PHP file is ever executed. The alert does pop up and asks you if you want to delete the file with the correct file name. The PHP code is what actually deletes the file however the file does not delete from the file system. I have tried putting other code in the PHP file like sending me an email and none of it executes.
Can anyone see anything wrong with this JQuery code?
THIS IS THE PHP CODE
<?php
$to = 'dev#kylevan.com';
$subject = 'the subject';
$message = 'file reached';
$headers = 'From: noreply#mobilehomelist.com' . "\r\n" .
'Reply-To: noreply#mobilehomelist.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
include('ASApiClientServer.php');
include('ASApiClient.php');
$uniquekey=$_SESSION['uniquekey'];
$postFields = array(
'referralCode'=>$uniquekey,
'image'=>strip_tags($_POST["file_to_remove"]),
),
);
$ApiClient = new ASApiClient();
try{
$ApiClient->requestResponse('removePicture', $postFields);
//handle the call
}
catch(Exception $e){
print_r($ApiClient->getRawResponse());
}
if(isset($_POST["file_to_remove"]) && !empty($_POST["file_to_remove"]))
{
$uploaded_files_location = 'uploaded_files/'.strip_tags($_POST["file_to_remove"]);
#chmod($uploaded_files_location,0777);
#unlink($uploaded_files_location);
//Here you can also delete the file from your database if you wish assuming you also saved the file to your database during upload
}
?>
The email stuff at the beginning is in there just trying to get it to do something. THe path to the file is correct.
First I would make sure the AJAX--to--PHP system is working. You can do that test with two small changes:
1) At the very top of your PHP file, just make it echo out a simple string and die. For example:
<?php
die("I got to here");
2) In your AJAX success function, put an alert() to capture/display the output from the PHP file. For example:
success: function(response)
{
alert("AJAX Recd from PHP: " + response);
//$('div#fileID'+id).fadeOut('slow');
}
Doing these two simple changes will immediately show you where the error is. If the error is in your PHP file, then post another question and ask about that (posting the PHP code, of course).
The next test, I would suggest, is (a very slight modification to the first test) to make the PHP file echo back out the data received via AJAX:
<?php
$f = isset($_POST['file_to_remove']) ? $_POST['file_to_remove'] : '';
die('PHP recd from AJAX: ' . $f);
First make sure your url is correct...
And that remove_unwanted_files.php is the correct path, and not something like example/directory/remove_unwanted_files.php
Then...if it is infact a post request....try this..
$.ajax({
type: "POST",
url: "remove_unwanted_files.php",
data: {file_to_remove:file},
cache: false,
beforeSend: function()
{
$("#vpb_remove_button"+id).html('<img src="images/loadings.gif" align="absmiddle" />');
},
success: function(response)
{
$('div#fileID'+id).fadeOut('slow');
}
});
If its not a Post...
Try this...
var dataString = "file_to_remove=" +file;
$.ajax({
type: "GET",
url: "remove_unwanted_files.php",
data: dataString,
cache: false,
beforeSend: function()
{
$("#vpb_remove_button"+id).html('<img src="images/loadings.gif" align="absmiddle" />');
},
success: function(response)
{
$('div#fileID'+id).fadeOut('slow');
}
});

Ajax mailer script not working, what to edit?

I'm not receiving any emails, what could be the problem ?
ui.js
sendEmail = function(username, callback) {
var msg = getMessage(username);
$.ajax({
type: 'POST',
url: 'ui.php',
data: '***What should I type here ?***',
success: callback
});
ui.php
<?php
$to = "XXXXXX#gmail.com";
$subject = "you got mail";
$message = $_POST['getMessage'];
$send = #mail($to, $subject, $message);
if(!$send){
die();
}
?>
Data should be a hash with the data. So in your case:
sendEmail = function(username, callback) {
var msg = getMessage(username);
$.ajax({
type: 'POST',
url: 'ui.php',
data: { getMessage : 'Actual message' },
success: callback
});
Also make sure you're defining the callback function what you're using in success-callack. You can leave that away if you're not interested in response.
Also there's a shortcut to post ajax request with POST.

Send Email with PHP/AJAX From HTML Form

I want to send the information the user has filled out from an HTML form to my email address. From my understanding, this cannot be done by using only client-side coding due to the nature of how emails work, and suggested to use PHP (combined with AJAX) to handle the server-side code. I followed the guide here but I am not receiving any emails at my email address. I am testing locally on my machine (using XAMPP) before I deploy my code on my client's web space (goDaddy). I want to note that I have never used PHP before.
Javascript:
var data = "This is my email";
$.ajax({
type: "POST",
url: "email.php",
data: data,
dataType: "text"
});
PHP (email.php):
<?php
$to = "myself#hotmail.com";
$subject = "This is my email";
$message = $_REQUEST;
$send = mail($to, $subject, $message);
if(!$send){
die();
}
?>
XAMPP doesn't have an e-mail sending thing by itself as default. You may check the links below;
php mail setup in xampp
How do I enable XAMPP to locally use the php's mail() function so I can test my mail() scripts locally without having to upload to my server?
You should replace $_REQUEST with $_REQUEST["data"] or something like this, because $_REQUEST is an array.
all time the page is being refreshed. Below is my code:
HTML 5:
<form method="post" data-ajax="false">
<input type="text" name="email" placeholder="jack#example.com, jil#example.com">
<input type="submit" name="submit" value="Invite" class="submitBtn">
</form>
JS:
$('form').bind('submit',function(){
$.ajax({
type : 'POST',
url : 'data/invite.php',
data : $(this).serialize(),
cache : false,
dataType: 'text',
success : function (serverResponse) { alert('mail sent successfully.'); },
error : function (jqXHR, textStatus, errorThrown) {alert('error sending mail');}
});
})
PHP:
<?php
$to = $_POST['mail'];
$name = 'Indusnet Technologies';
$subject = 'Think Recycle';
$text = 'Welcome to our site';
$message =' You received a mail from '.$name;
$message .='Text of the message : '.$text;
if(mail($to, $subject,$message)){
echo 'mail successful send';
}
else{
echo 'there’s some errors to send the mail, verify your server options';
}
?>
var data = "This is my email";
$.ajax({
type: "POST",
url: "email.php",
data: data,
dataType: "text"
});
This Code shoud be like this
var data = "This is my email";
$.ajax({
type: "POST",
url: "email.php",
data: {"data": data},
dataType: "text"
});
and get in code either through $_POST['data'] or $_REQUEST['data']
You probably should return false to the form. Try this:
$('form').submit(function(){
$.ajax({
type : 'POST',
url : 'data/invite.php',
data : $(this).serialize(),
cache : false,
dataType: 'text',
success : function (serverResponse) { alert('mail sent successfully.'); },
error : function (jqXHR, textStatus, errorThrown) {alert('error sending mail');}
});
return false;
})

Problem with Jquery AJAX and more than 2 variables

I am trying to add a tell a friend section to a website I am making but I am having difficulty trying to send more than 2 variables through a URL with AJAX. This is the code I have at the moment:
jQuery("#tellafriendsubmit").click(function() {
var email = jQuery('#tellafriendemail').val();
var name = jQuery('#tellafriendname').val();
jQuery.ajax({
type: "POST",
url: "http://www.example.co.uk/tell-a-friend-processor-page/?postname=<?php echo $post_name; ?>&name=name&email="+email,
success: function(msg){
alert('Your tell a friend recommendation has been sent. Thank you for recommending us.');
}
});
});
If I remove the '&name=name' part so that I'm only sending the postname and email address, it works fine but I need to send the name as well so I can write 'Dear $name....'
How can I send the extra 3rd variable? Thanks for any help
Edit:
The part I'm using in the tellafriendprocessor page looks like this:
$email = $_POST['email'];
$post_name = $_GET['postname'];
$name = $_POST['name'];
$to = $email;
$subject = "Example - Tell a friend";
$body = "Dear $name http://www.example.co.uk/ads/$post_name";
if (mail($to, $subject, $body, $headers)) {
} else {
}
You could try sending them as part of the POST request body (using the data property) which will ensure that those values are properly encoded:
var email = jQuery('#tellafriendemail').val();
var name = jQuery('#tellafriendname').val();
jQuery.ajax({
type: 'POST',
url: 'http://www.example.co.uk/tell-a-friend-processor-page/?postname=<?php echo $post_name; ?>',
data: { name: name, email: email },
success: function(msg) {
alert('Your tell a friend recommendation has been sent. Thank you for recommending us.');
}
});
On the server side make sure you are reading them from the $_POST hash ($_POST["name"] and $_POST["email"]).
you can send your parameters to a page with AJAX by GET and POST method with this piece of code
data: { id : 'id', name : 'name' }, // multiple data sent using ajax
Here is an example
$.ajax({
type:"GET",
cache:false,
url:"welcome.php",
data: { id : 'id', name : 'name' }, // multiple data sent using ajax
success: function (html) {
$('#add').val('data sent sent');
$('#msg').html(html);
}
});
You will need to move name outside the string. And to add more key-value-pairs you just append them to the query string: &key=value
url: "http://www.example.co.uk/tell-a-friend-processor-page/?postname=<?php echo $post_name; ?>&name="+name+"&email="+email
Try to use object of params like this:
$.post("/tell-a-friend-processor-page/", { name: "John", email: "<?php echo $post_email; ?>", post_name: "<?php echo $post_name; ?>" },
function(data) {
alert("Data Loaded: " + data);
});

Passing a Value from PHP to the SimpleModal Contact Form

What is the simplest way to pass a value from the "index" page to the SimpleModal Demo Contact Form? For example, if a user is logged in and their email address is stored in the variable $email, what is the most straightforward way to have that info available in the Demo Contact Form?
Thank you.
Assuming the values you want are NOT in the form, here's a way to do it.
Update contact.js in the onShow: function:
...
}, function () {
$('#contact-container .contact-loading').fadeIn(200, function () {
var pt = PAGE_TITLE,
aid = ARTILE_ID;
$.ajax({
url: 'data/contact.php',
data: $('#contact-container form').serialize() + '&action=send&page_title=' + pt + '&article_id=' + aid,
type: 'post',
cache: false,
dataType: 'html',
success: function (data) {
$('#contact-container .contact-loading').fadeOut(200, function () {
$('#contact-container .contact-title').html('Thank you!');
msg.html(data).fadeIn(200);
});
},
error: contact.error
});
});
});
...
Then update contact.php in the function smcf_send() function
...
// Set and wordwrap message body
$pt = isset($_POST["page_title"]) ? $_POST["page_title"] : "";
$aid = isset($_POST["article_id"]) ? $_POST["article_id"] : "";
$body = "From: $name\n\n";
$body .= "Page Title: $pt\n";
$body .= "Article ID: $aid\n\n";
$body .= "Message: $message";
$body = wordwrap($body, 70);
...
Obviously you can play around with the details, but that should get you going.
-Eric

Categories