I have following form processing php script.
<?php
$G['hotel_email']="xxxx#xxxx.com";
$G['hotel_name']="xxx xxx";
$G['language']="en";
$T['lbl_form_sent_successfully']="H";
# Recipients: comma separated
$G['form_contact_mail_recipients'] = $G['hotel_email'];
$G['form_contact_mail_subject'] = $G['hotel_name'] . ' - Contact Weddings [' . $G['language'] . ']';
# CHECK IF FORM SENT. AJAX. RESPONSE IN JAVASCRIPT TO INTERACT IN THE FORM.
if (!empty($_POST)) {
$js = '';
# ALTERNATIVE CAPTCHA, IT MUST NOT BE FILLED
if (!empty($_POST['title'])) { exit; }
# FORM MAIL TO SENT
unset($_POST['title']);
unset($_POST['submit']);
$message = date("l, F j, Y, g:i a")." [GMT] \n\nFORM DETAILS\n\n\n";
foreach ($_POST as $field => $value) {
$message .= ucfirst(str_replace('_',' ',$field)).': '.$value."\n\n";
}
$message .= "\n\n\n";
mail($G['form_contact_mail_recipients'], $G['form_contact_mail_subject'], $message, "From: ".$_POST['email']."\r\n");
echo "success";
}
?>
The form is being submitted using following JavaScript
$(function() {
// Initialize form validation on the registration form.
// It has the name attribute "registration"
$("#ba-form-contact form").validate({
// Specify validation rules
rules: {
// The key name on the left side is the name attribute
// of an input field. Validation rules are defined
// on the right side
First_Name: "required",
Surname: "required",
email: {
required: true,
// Specify that email should be validated
// by the built-in "email" rule
email: true
}
},
submitHandler: function() {
jQuery.ajax({
type: 'POST',
url: '<?=$_SERVER['REQUEST_URI']?>',
data: jQuery("#ba-form-contact form").serialize(),
dataType: 'html'
});
return false;
}
});
});
</script>
The last echo statement does't work and I don't get any error msg.I do get email with all the info alright.I think nothing work after the mail function, I tried like var_dump, but nothing. What could be the error here?
As per your ajax request, you are not using success method here in ajax request, you need to add success method as:
jQuery.ajax({
url: YourURL,
type: "POST",
data: jQuery("#ba-form-contact form").serialize(),
dataType: "html",
success: function(response) {
alert(response); //this will return the response
},
beforeSend: function()
{
// loading if you need before ajax success
}
});
return false;
Here success: function(response) { will return the success message.
You do not know that it is the echo that does not work.
What you do know is that the script executes, and the jQuery function does not issue output. And that's where half the problem is.
jQuery.ajax({
type: 'POST',
url: '<?=$_SERVER['REQUEST_URI']?>',
data: jQuery("#ba-form-contact form").serialize(),
dataType: 'html'
});
The above does not do anything with the output, so logically nothing happens.
Try this:
jQuery.post({
'<?=$_SERVER['REQUEST_URI']?>',
jQuery("#ba-form-contact form").serialize()
}).done(function(retval) {
// Debug (better use console.log actually)
alert(JSON.stringify(retval));
// Do what you want with retval.message (check retval.status also)
alert(retval.message);
});
and in the PHP, which must output nothing else, end with:
header('Content-Type: application/json');
die(json_encode(array(
'status' => 'success',
'message' => 'The mail was sent',
)));
(I have changed from HTML to JSON output since this allows to send more structured data, with negligible additional complexity).
Related
I've created a form using a bit of jquery, ajax and php.
The ajax, validation and php processing works well.
I came up with the following code to hide my form after submitting, but I don't know if this is the good way to do that. I would like your advise.
Below the js script with the ajax call
<script type="text/javascript">
$(document).ready(function(){
$("#submitContact").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'form/process.php',
data: $("#contact_form").serialize(),
success: function(response) {
$("#formstatus").hide().html(response).slideToggle(600);
}
});
});
});
</script>
The above code will call the php to validate and populates the div#formstatus to notify the user if the form is sent or not.
Within my process.php, I will hide the form if there are no errors found using echo js script.
// If no errors found echo succes message
if (!($formerrors)) :
//Hide the form
echo '<script type="text/javascript">
$(document).ready(function(){
$("#contact_form").hide();
});
</script>';
// display success message
echo '<div>
Your message has been sent. <br />
Thank you for contacting us!
</div>';
Etc....
To sum up:
Should I use this method to hide my form? (Because it does work)
Note. I'm new to jquery and ajax :)
I think it would be better to return a JSON object which contains the information relevant to the request.
For example:
if (!($formerrors)){
echo json_encode(array(
'success'=> true,
'message'=> 'Your message has been sent. <br> Thank you for contacting us!'
));
}
else{
echo json_encode(array(
'success'=> false,
'message'=> 'Error processing form',
'errors'=> array(
'phone'> 'A phone number is required'
)
));
}
This will be easy to work with on the client side (jQuery will automatically parse the json)
<script type="text/javascript">
$(document).ready(function(){
$("#submitContact").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'form/process.php',
data: $("#contact_form").serialize(),
success: function(response) {
if(response.success){
$("#formstatus").hide().text(response.message).slideToggle(600);
}
else{
jQuery.each(response.errors,function(){ ... });
}
}
});
});
});
I think you'll find you have more manageable code if you separate display concerns from functional concerns. For php I agree with Walkerneo.
Javascript AJAX Success Handler
success: function(response) {
var response = $.parseJSON(response);
if(response.status === 'true') {
$("#formstatus").hide().html(response.message).slideToggle(600);
$("#contact_form").hide();
} else {
$("#formstatus").hide().html(response.message).slideToggle(600);
}
}
PHP
if(!$formerrors) {
exit(json_encode(array('status' => 'true', 'message' => 'Your message has been sent. \n Thank you for contacting us!')));
} else {
$message = '<p class="error">' . implode('</p><p>', $formerrors) . '</p>';
exit(json_encode(array('status' => 'false', 'message' => $message)));
}
I recommend avoiding this method. You should instead return information about the status and message to display to the user. For example, here's how you can do it without reloading the page.
demo (non-blank data will be accepted)
We prevent the default event, so that the page doesn't reload. Because of the below HTML changes, we also can make or code more general.
$('form').submit(function(e){
e.preventDefault();
var $this = $(this);
$.ajax({
cache: false,
type: 'POST',
url: 'URLHERE',
data: $(this).serialize(),
dataType: 'jsonp',
success: function(response) {
We display the error or success message here. Depending on the status field, we make the text green or red, and decide whether to hide the form or not.
$("#formstatus").hide().text(response.msg).show(600);
if (response.status === "success") {
$this.hide();
$("#formstatus").css({color: "green"});
}
else {
$("#formstatus").css({color: "red"});
}
}
});
return false;
});
Our PHP simply returns a JSON object.
function callback($data){
$json = json_encode($data);
return $json;
}
if ($valid === true) {
echo callback(
array(
"msg" => "Your message has been sent.\nThank you for contacting us!",
"status" => "success"
)
);
}
else {
echo callback(
array(
"msg" => "Please fill in all fields.",
"status" => "error"
)
);
}
The HTML is also changed to use a submit button, which allows us to target the form instead of the button. The code may now be transported more easily.
<div id="formstatus"></div>
<form>
<input placeholder="First Name" name="name">
<input placeholder="Email" name="email">
<input placeholder="Comment" name="comment">
<input type="submit">
</form>
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');
}
});
I am setting up a registration form.
This form has 7 fields that are being tested for validation.
2 of them have a special validation; I have an Ajax call to a PHP class where I send an email_string to this class, testing, if such an email already exists in my database (evading duplicates).
params = {};
params['source'] = 'checkEMail';
params['email'] = email
$.ajax({
type: 'POST',
url : 'some_class.php',
data : params,
success: function(msg)
{
if(msg > 0) /* email exists */
is_error = true;
}
});
And in my PHP Class I got something like this:
$final = mysql_fetch_assoc(foo);
echo ($final) ? 1 : 0;
I was testing the data and in fact - I get '1' if the email exists and '0' if it does not.
Funny thing is, that this snippet works fine AS LONG AS there are other errors in this form - like an empty username.
The "is_error" is a boolean that is set to false at the beginning of the script and if one validation fails, it gets true.
Then, finally, I got this:
if(is_error)
{
error.show();
error.empty().append('some html foo');
}
else
{
$('form').submit();
error.empty().hide();
}
So how can it be that I the form will be send although is_error is set to true?
Only reason I could think of is that the form is being send before the "is_error" is being testet - but the send of the form is at the very bottom of the script.
Oh and I am calling it this way:
<script type="text/javascript">
$("#reg_submit").click(function(event) {
event.preventDefault();
checkReg();
});
</script>
instead of having the if(is_error){ part at the end of the script, I would suggest you to do it in the ajax request completion to avoid race conditions:
$.ajax({
type: 'POST',
url: 'some_class.php',
data: params,
success: function(msg) {
if (msg > 0) /* email exists */
is_error = true;
},
complete: function() {
if (is_error) {
error.show();
error.empty().append('some html foo');
} else {
$('form').submit();
error.empty().hide();
}
}
});
Maybe it is caused by different output types that you are trying to match...
First, change your PHP output to
echo json_encode($final ? true : false);
Then, to work with JSON, I would add this line to ajax calling method, to be sure...
$.ajax({
type: 'POST',
dataType:'json',
...
success: function(msg)
{
if(msg!==true){
is_error = true;
}
}
});
I'm using in the same page a validation engine with date picker.
Datepicker: http://jqueryui.com/demos/datepicker/
Validationengine: http://www.position-relative.net/creation/formValidator/demos/demoValidators.html
I've added a jQuery.noConflict(); to make it work (at the beginning of the code).
Now, I need to make my insert through a PHP file, but without refreshing the page, and by displaying an error message in the same bubble of validationEngine (for example when the email is already registered in the BDD).
should I import jQuery to make my insert in the same page
without causing conflicts, or can I use one on the query already used
for the same purpose?
How do I display a server response through the validationEngine?
My code is the following one.
$(".btn_newsletter").live('click', function() {
$.ajax(
{
url: "php/functions/signin.php"+nomfichier,
success: function(data) {
if (data.check==0) {alert('Error : Sorry '); return false;}
if (data.check==1) {alert('yep!!!');
}
},
cache: false,
type: "POST",
dataType: 'json'
});
}
This is my PHP code.
$ip= $_SERVER["REMOTE_ADDR"];
$select = "select * from av_newsletter where email='".$_POST['email']."'";
$exist = $_BASE->query_array($select);
if ($exist) {
$check = "0";
}
else {
$ajout="INSERT INTO av_newsletter(id,sub_date,email,ip) VALUES (NULL,now(),'$email','$ip')";
$add=$_BASE->query($ajout);
if ($add) {
$check="1";
}
}
$return_arr["check"] = $check;
echo json_encode($return_arr);
It doesn't work; I've no alert, but also no errors.
If you are not tied in too deeply to your 'Validationengine' I would recommend using this one, is has served me well for years, it has support for making remote checks so you could do something like this:
$(document).ready(function(){
var save_options = {
success: userSaved, //callback function
url: '/users/save',
response: 'json',
method: 'post'
};
var validationObj = {
rules: {
name: "required",
email: {
email: true,
required: true,
remote: "/user/check_email/"
}
},
messages: {
name: "Please name yourself",
email: {
required: "Please enter your email address",
email: "Invalid email address",
remote: "Email already in use."
}
},
errorPlacement:function(error, element) {
error.appendTo( element.next() );
},
submitHandler: function(form) {
$(form).ajaxSubmit(save_options);
},
success:function(label) {
label.html(" ").addClass("checked");
}
};
});
And then on the PHP side at the '/users/check_email' endpoint the PHP does the following:
echo $emailExists ? json_encode(false) : json_encode(true);
Ok, before we spam the comments and get to far off topic, please execute this code which should get you started in getting it to work eventually.
$(".btn_newsletter").live('click',function() {
alert('clicked'); // click is executed
$.ajax({
url: "php/functions/signin.php"+nomfichier,
success: function(data) {
alert(data); // should alert the data
if(data.check==0){ alert('Error : Sorry '); return false; }
if(data.check==1){ alert('yep!!!'); }
},
error: function(request, status, error) {
alert('failed '+status);
},
cache: false,
type: "POST",
dataType: 'json'
});
});
it works :)
$(".btn_newsletter").live('click',function() {
var data ="email="+$('#email').val();
$.ajax({
url: "php/functions/signin.php"+"?"+data,
success: function(data) {
if(data.check=='1'){ alert('yep!!!'); }
if(data.check=='0'){ alert('Error : Sorry '); return false; }
},
cache: false,
type: "POST",
dataType: 'json'
});
});
and in my signin.php I catch the value of the input like this $email=$_REQUEST['email']
Thanks a lot! time for me to see about validation engine how to link this with :)
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);
});