Solved

PHP file not getting JSON variables?

Posted on 2014-04-07
10
698 Views
Last Modified: 2014-04-08
Hi all,

I send across some form data using ajax to send a simple hmtl email.

the code i have for my ajax is as follows;

				var jsonObject = {};
    				jsonObject['name'] = jQuery('#nameInput').val();
				jsonObject['email'] = jQuery('#emailInput').val();
				jsonObject['message'] = jQuery('#messageInput').val();
				jsonObject['product'] = jQuery('#productOwnedInput').val();
				jsonObject['company'] = jQuery('#companyInput').val();
				jsonObject['reason'] = jQuery('#reasonInput').val();
				jsonObject['contact'] = jQuery('#contactInput').val();

				var url = "<?php bloginfo('template_url'); ?>/sendform.php";

				jQuery.ajax({
        				type: "POST",
       					url: url,
        				data:  JSON.stringify(jsonObject),
        				contentType: "application/json; charset=utf-8",
        				dataType: "json",
					success: function (data) {

Open in new window


and in my php file i rtrieve the fields and substitue them into a file;

$str=file_get_contents('emailform.html');
$str=str_replace("{NAME}", $_POST['name'] ,$str);
$str=str_replace("{EMAILADDRESS}", $_POST['email'] ,$str);
$str=str_replace("{MESSAGE}", $_POST['message'] ,$str);
$str=str_replace("{PRODUCT}", $_POST['product'] ,$str);
$str=str_replace("{COMPANY}", $_POST['company'] ,$str);
$str=str_replace("{REASON}", $_POST['reason'] ,$str);
$str=str_replace("{CONTACT}", $_POST['contact'] ,$str);

$Body = $str;
 
$mail = new PHPMailer();

Open in new window


now the AJAX is submitting and the email is being sent. however all the post data is blank?
(i.e. "" is being substituted for "{CONTACT}", etc).

Am I retrieving the data incorrectly?
0
Comment
Question by:flynny
  • 2
  • 2
  • 2
  • +3
10 Comments
 
LVL 21

Expert Comment

by:Kim Walker
Comment Utility
Use var_dump to see what's being delivered in your $_POST object.
var_dump($_POST);

Open in new window

0
 
LVL 21

Expert Comment

by:Kim Walker
Comment Utility
Also, I don't think you should stringify the json object if your "datatype" is json. Unfortunately I'm not that proficient in jQuery.
0
 
LVL 108

Expert Comment

by:Ray Paseur
Comment Utility
Agree with xmediaman. Please use var_dump() to print out the contents of the request.  We need to see exactly what is getting sent to the PHP script.  Once we can see that it should be easy to figure out whether the issue is on the jQuery side or the PHP side.
0
 
LVL 30

Expert Comment

by:Marco Gasi
Comment Utility
var-dump is a great friend, but I can say a couple of things.

AFAIK, jQuery uses utf-8 charset by default with json so specify contentType is unneeded.

Secondly, I think you can pass your data using literals:

data:  {'name': jQuery('#nameInput').val(), and so on}

Third I don't understan what you mean saying
now the AJAX is submitting and the email is being sent.

I see you create a new PHPMailer object in the php file, so I suppose you're sending email using php, not Ajax. Correct me if I0m wrong, but what I guess from the code you posted is
Ajax get data from the form and pass them to a phpo script which processes them and sends the email, returning something (but what?) to javascript script (success: function (data) {: what's data?)

More than var_dump result, I would like to see the full code of the ajax call and the php script :-)
0
 
LVL 33

Expert Comment

by:Slick812
Comment Utility
greetings flynny, , you have an Error in your  jQuery.ajax({   Options object , ,
you need to remove this line -
contentType: "application/json; charset=utf-8",

in my tests, no PHP server is set up to process a   contentType:"application/json;"  without special APACHE and PHP settings, ,
you must use a standard POST or GET request to a PHP server, which is the automatic thing that  jQuery.ajax({         will do.

There is probably no good reason to send a JSON delimited CSV string to a PHP request, But you can if you want to, but you MUST parse the JSON string for an URL (substitute the punctuations wid URL hex values), , which this line does NOT do -
data:  JSON.stringify(jsonObject),

that code line also does NOT use the proper "POST" URL setup with the -
name=value&next=VALUE2
so you will need to change it to something like -

var json1 = encodeURIComponent( JSON.stringify(jsonObject));

jQuery.ajax({ type: "POST",
  url: url,
  data: "aj="+ json1,
  dataType: "json",
  success: function (data) {

BUT, if you do send up a JSON String, the PHP will NOT un parse that to the $_POST names and values , you will neeed to do the php jsondecode thing.

It seems you need to get some more information about how the AJAX process works in a PHP, as I said, my pHP servers can not do the contentType: "application/json;  request, maybe yours can?


ALSO you seem to be getting the values in the JSON object from several many Form Inputs, Jquery has an easier way with -
$("#form1").serialize()
which will get ALL inputs in form ID "form1" to a proper POST url to use in the   data:    thing

just a note, even if you place the  php var_dump($_POST);  in there, You likely have no way of ever seeing the output in the returned   success: function(data)  as that will disrupt the JSON format and error out the Jquery AJAX return.
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 33

Expert Comment

by:Slick812
Comment Utility
Just remembered, since you may not know very much about javascript, or Jquery javascript, here is something that just may work for you -
var url = "<?php bloginfo('template_url'); ?>/sendform.php";

jQuery.ajax({ type: "POST",
  url: url,
  data: $("#emailForm").serialize(), // You MUST change this id to the FORM ID with the #nameInput
  success: function (data) {

Open in new window

this should work with your PHP code as
$str=str_replace("{NAME}", $_POST['name'] ,$str);

IF the form input NAMES correspond to the post names as $_POST['name']  ,  $_POST['reason']  etc.

I have left out all of the Ajax Options for -
contentType: "application/json; charset=utf-8",
dataType: "json",

because you do not seem to understand them, or know how to use them, You likely have an empty -
success: function (data) { }
function, and don't do anything with the data anyway, if you do an Object for the data return, then you can change it to the   dataType: "json",
0
 
LVL 42

Expert Comment

by:Chris Stanyon
Comment Utility
You don't need to do anything with the jsonObject - just pass it to your PHP script 'as-is':

jQuery.ajax({
   type: "POST",
   url: url,
   data:  jsonObject,
   dataType: "json",
   success: function (data) {

Open in new window

Also note that the dataType setting is for the response FROM the server, not for passing data TO the server, so your PHP script will need to generate a valid JSON response (json_encode)
0
 

Author Comment

by:flynny
Comment Utility
Ok,

thanks for all the replies. Sorry for not  being detailed enough. basically the ajax call is calling sending the form data (its not in form tags though) to the .php file.

the .php file is then loading the template html file, subbing in the data and sending emailing the form.

the full ajax is

var jsonObject = {};
    				jsonObject['name'] = jQuery('#nameInput').val();
				jsonObject['email'] = jQuery('#emailInput').val();
				jsonObject['message'] = jQuery('#messageInput').val();
				jsonObject['product'] = jQuery('#productOwnedInput').val();
				jsonObject['company'] = jQuery('#companyInput').val();
				jsonObject['reason'] = jQuery('#reasonInput').val();
				jsonObject['contact'] = jQuery('#contactInput').val();

				var url = "<?php bloginfo('template_url'); ?>/sendform.php";

				jQuery.ajax({
        				type: "POST",
       					url: url,
        				data:  JSON.stringify(jsonObject),
        				dataType: "json",
					success: function (data) {
						alert(data);
       						if(data == "SUCCESS") {
							//alert("is success");
						}
						else if(data =="ERROR") {
							alert("An error occurred whilst submitting our form. Please contact our office to submit it manually. We apologise for the inconvenience.");
						}
    					},
					error: function (xhr, ajaxOptions, thrownError) {
        					//alert(xhr.status);
        					//alert(thrownError);
						alert("An error occurred whilst submitting our form. Please contact our office to submit it manually. We apologise for the inconvenience.");
      					}
    				});

Open in new window


the full .php is

<?php

require_once("class.phpmailer.php");

// get posted data into local variables
$From = "fromaddress"; 
$To = "emailaddress";
$Subject = "Contact Form";

$str=file_get_contents('emailform.html');
$str=str_replace("{NAME}", $_POST['name'] ,$str);
$str=str_replace("{EMAILADDRESS}", $_POST['email'] ,$str);
$str=str_replace("{MESSAGE}", $_POST['message'] ,$str);
$str=str_replace("{PRODUCT}", $_POST['product'] ,$str);
$str=str_replace("{COMPANY}", $_POST['company'] ,$str);
$str=str_replace("{REASON}", $_POST['reason'] ,$str);
$str=str_replace("{CONTACT}", $_POST['contact'] ,$str);

$Body = $str;
 
$mail = new PHPMailer();

$mail->IsSMTP();                                      // set mailer to use SMTP
$mail->Host = "host";  // specify main and backup server
$mail->SMTPAuth = true;     // turn on SMTP authentication
$mail->Username = "user";  // SMTP username
$mail->Password = "password"; // SMTP password
 
$mail->From = $From;
$mail->FromName = "Mailer";
$mail->AddAddress($To);           

$mail->Subject = $Subject;
$mail->Body    = $Body;

if(!$mail->Send()){
	print_r(json_encode('ERROR'));
}
else{
	print_r(json_encode('SUCCESS'));	
}

?>

Open in new window


I have tried print_r the POST data, but this is just causing the error on the ajax to trigger instead of the SUCCESS? the above php is returning success and the email is being sent. However, the fields are just being replaced by blank. I assume I may be missing a json_decode? but am unsure how to do this for the post data?
0
 
LVL 30

Expert Comment

by:Marco Gasi
Comment Utility
This is an amended jquery code I used to sen emails:

$(document).ready(function()
{	$('#sendEmail').on('click', function(e){
		e.preventDefault();
		var urls = $('#attachmentsList input:checkbox:checked').map(function(){
			return urldecode($(this).val());
		}).get();
		var subject = $('#subject').val();
		var message = $('#message').val();
		$.ajax({
			type: 'post',
			url: 'script_admin_send_email.php',
			data: {subject: subject, message: message, attachments: JSON.stringify(urls)},
			success: function(result) 
			{
				$('#response').html(result).fadeIn('slow').delay(2000).fadeOut('slow');
				$('#message').val('');
				$('#subject').val('');
				$(':checked').each(function(){
					$(this).attr('checked', false);
				 });
			}
		});
	});
});

Open in new window



In your php file I would change only the final response:

if(!$mail->Send()){
	echo 'ERROR';
}
else{
	echo 'SUCCESS';	
}

Open in new window


I think your problem is with jsonObject: use string literal as I do in my script and it should work for you as it works for me :-)
0
 
LVL 42

Accepted Solution

by:
Chris Stanyon earned 500 total points
Comment Utility
As I said in my previous post, you don't need to do anything with your jsonObject - just send it:

data:  jsonObject,

Then you will be able to access the POST variables in your PHP.

As for your PHP file, you need to echo out using json_encode:

if(!$mail->Send()){
	echo json_encode('ERROR'));
}
else{
	echo json_encode('SUCCESS');	
}

Open in new window

Although, you don't really need json as you're only passing back one value, so you could just echo out the result (echo "Error"; / echo "Success";) and drop the dataType argument from your jQuery altogether.
0

Featured Post

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
Responsive Design Tools 6 33
Best database setup for image uploads 6 36
PHP Curl Setup Option 4 27
Phone Dialer 5 33
Foreword (July, 2015) Since I first wrote this article, years ago, a great many more people have begun using the internet.  They are coming online from every part of the globe, learning, reading, shopping and spending money at an ever-increasing ra…
Introduction HyperText Transfer Protocol (http://www.ietf.org/rfc/rfc2616.txt) or "HTTP" is the underpinning of internet communication.  As a teacher of web development I have heard many questions, mostly from my younger students who have come to t…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now