I have some code in PHP 5. The code is simple - get data from a form in the site using ajax, and send it to mail.
But the code doesn't get the parameters from the POST call.
I have tried it in Postman and the code still doesn't read the parameters.
Image of Postman:
The code in short:
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];
What's the problem?
EDIT:
I've changed the code from $_POST to $_GET - now it working in Postman, but in ajax the error still here,
The ajax (with Jquery):
$.ajax({
type: "POST",
url: "http://doodlevideo.co.il/php/form-process.php",
data: {name: name_val, email: email_val, msg_subject: msg_subject_val, msg_subject_option: msg_subject_option_val, message: message_val},
success : function(text){
if (text == "send"){
formSuccess();
} else {
formError();
submitMSG(false,text);
}
}
});
Related
Why is it that if I am using Postman, I dont need to include if ($_POST) { '' } else { $_POST = json_decode(file_get_contents('php://input'), true);}
It works differently as If I were to send it from AJAX, but why?
Why doesn't Postman requres json_decode(file_get_contents('php://input'), true);
Ajax code
$.ajax({
url: "http://localhost/WEP/RESTAPI/php.php?api",
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
success: function(data) {
window.alert("Friend added! "+$name.val()+' '+$email.val());
},
error: function() {
alert("Error");
}
});
PHP
elseif ($srequest == 'POST'){
if ($_POST) {
'';
} else {
$_POST = json_decode(file_get_contents('php://input'), true);
}
$id = $_POST['id'];
$name = $_POST['name'];
$email = $_POST['email'];
//...mysqli connect,query
Your Ajax has been written to send a POST request with a JSON encoded body.
When you use Postman, you must have configured it to use a multipart or www-url-encoded body.
PHP will automatically decode request bodies using those formats.
Postman does something else then an AJAX post. One will post your classic html form with application/x-www-form-urlencoded, the other is posting straight json with a different contenttype.
bottomline: The php $_POST variable does not containt everyting you send with a POST http request!
also see here, this is an excellent explanation: PHP "php://input" vs $_POST
Everything works fine except email address. When i post email address to server and just echo it, recieve nothing. Only problem in # symbol, rest are ok.
angular:
$http({
method: 'POST',
url: 'http://______.org/_____.php',
data: {
signInSubmitBTN: '', email: 'joe#g.com'
}
}).success(function (data) {
alert(data); //alert empty when joe#g.com but joeg.com is ok
});
PHP
if (isset($_POST['signInSubmitBTN'])) {
$email = $_POST["email"];
echo $email;
}
NOTE - already configure app
app.config(function ($httpProvider, $httpParamSerializerJQLikeProvider) {
$httpProvider.defaults.transformRequest.unshift($httpParamSerializerJQLikeProvider.$get());
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
})
You need to encode using base64:
signInSubmitBTN: '', email: window.btoa('joe#g.com')
And don't forget to decode on the server side using atob()
Use this code in back end to get POST data back in PHP.
if(isset($_POST)){
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
echo $request->email;
}
I'm doing a code that send a data to a php file and send it back again and print it as a response however when i send the data it is sent as an empty data i did not know what is the problem this is the code that i tried:
var resource = $('#resource').val().replace(/[\n\r](?!\w)/gi, "").split("\n");
function doRequest(index) {
// alert(resource[0]); The data here is ok and it is not empty whenever the data is sent the response is empty !
$.ajax({
url:'curl_check.php?email='+resource[0],
async:true,
success: function(data){
alert(data);
if (resource.length != 1) {
removeResourceLine();
doRequest(index+1);
}
}
});
}
doRequest(0);
since you're not sending the data using the data property of the ajax call object like so:
$.ajax({
...
data : { email : resource[0] }
...
});
you are sending it as part of the URL, so it should be picked up as a GET variable. in php, this looks like:
$email = isset($_GET['email']) ? $_GET['email'] : false;
that said, i'd suggest using the ajax data property and specifying the type property and setting it to GET or POST. you could also use $.ajaxSetup
Ok I am not sure what is wrong with what you are doing but I am going to give you code I use to send data to php and get a response. I am going to do it with json because it is awesome. I hope it helps:
var resource = $('#resource').val().replace(/[\n\r](?!\w)/gi,"").split("\n");
function doRequest(index) {
$.post("curl_check.php", {
email: resource[0]
}, function(data, result, xhr){
if(result == 'success') {
console.log(data.success);
} else {
console.log('post failed');
}
}, "json");
}
The php code:
$json = array();
$email = $_POST['email']; //Please escape any input you receive
//Do what you have to do
$json['success'] = 'YAY IT WORKED';
die(json_encode($json));
I'm really lost on how to return a value previously submitted to a PHP file with AJAX jquery. I am just starting to learn jquery so I am still struggling with concepts a bit.
Here is my code for jquery:
$('#button2').click(function(e) {
$.post("status.php",
{name: $('#name').val(),
email: $('#email').val()},
function(data){
$('#message').html(data);
});
return false;
});
$('#button3').click(function(e){
$.get({
url: "status.php",
data: 'information=',
success: function(data) {
$('#content').data(data); },
datatype: "text"
});
return false;
});
I have the user submit their name and email to the php file, that goes through correctly and displays the output message. But I then want to have another button that displays their submission, so name: xxxxx email: xxxxx inside the #content div
Here is the PHP file
<?php
extract($_GET);
extract($_POST);
$data = array();
if(isset($name) && isset($email))
{
$data[$email] = $name;
echo "User information submitted.";
}
if(isset($information))
{
foreach($data as $key => $value)
{
$name .= $key.",";
$email .= $value.",";
}
echo $name."|".$email."\n";
}
?>
Our teacher has supplied us with the PHP file and we are to code the jquery and ajax. I am very lost however. Any help on how I can use $information to retrieve the users submission?
Your not requesting your $name and $email variables in your PHP file. Add this to the top:
$name = $_REQUEST['name'];
$email = $_REQUEST['email'];
On a side note your $('#button3') is using $.post and you are using type:"GET". You will need to make a choice on what you want to use.
Note that for button3 handler, you should not use $.post, use $.get instead.
Then you can remove type: ''GET'
I suspect that this might be a server issue, but since I do not have access to our server, I was hoping maybe someone else had a fix or could explain to me exactly what is causing the problem.
The problem ....
Using JQuery AJAX I am unable to simultaneously POST data to a php file and receive json encoded data from the php file. If the json dataType is included I am unable to POST data from the form to the php file. If I do not specify the json dataType (i.e. comment it out) then I can POST data to the php file but cannot receive the json encoded data.
I've tried this with my own js/php code and for source code that I downloaded, in order to compare results in case it was just a mistake in my coding. Both are 'submit forms' and both exhibit the problems outlined above. In case its relevant, I include the downloaded source code below. My js/php code uses similar ajax requests.
javaScript:
<script type="text/javascript">
$(document).ready(function(){
$("#myForm").submit(function(){
dataString = $("#myForm").serialize();
$.ajax({
type: "POST",
url: "postForm_ajax.php",
data: $("#myForm").serialize(),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(msg){
$("#formResponse").removeClass('error');
$("#formResponse").addClass(msg.status);
$("#formResponse").addClass(msg.status);
},
error: function(){
$("#formResponse").removeClass('success');
$("#formResponse").addClass('error');
$("#formResponse").html("There was an error submitting the form. Please try again.");
}
});
//make sure the form doens't post
return false;
});
});
</script>
the PHP:
<?php
//function to validate the email address
//returns false if email is invalid
function checkEmail($email){
if(!preg_match("/^[_\.0-9a-zA-Z-]+#([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $email)) {
//if(eregi("^[a-zA-Z0-9_]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$]", $email)){
return FALSE;
}
list($Username, $Domain) = explode("#",$email);
if(#getmxrr($Domain, $MXHost)){
return TRUE;
} else {
if(#fsockopen($Domain, 25, $errno, $errstr, 30)){
return TRUE;
} else {
return FALSE;
}
}
}
//response array with status code and message
$response_array = array();
//validate the post form
//$name = $_POST['name'];
//check the name field
if(empty($_POST['name'])){
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Name is blank';
//check the email field
} elseif(!checkEmail($_POST['email'])) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Email is blank or invalid';
//check the message field
} elseif(empty($_POST['message'])) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'Message is blank';
//form validated. send email
} else {
//send the email
$body = $_POST['name'] . " sent you a message\n";
$body .= "Details:\n\n" . $_POST['message'];
mail($_POST['email'], "SUBJECT LINE", $body);
//set the response
$response_array['status'] = 'success';
$response_array['message'] = 'Email sent!';
}
echo json_encode($response_array);
?>
EDIT....One Solution
Ok...so I found a hack that works. I don't specify the dataType:'json', i.e. comment that line and the contenType line out. Then I'm able to POST the data. Still have the php file echo the json_encode($response_array). Then put the following code in the success function
var obj = jQuery.parseJSON(msg);
$("#formResponse").addClass(obj.status);
$("#formResponse").html(obj.message);
This is not as nice as being able to specify the dataType:'json' in the ajax call. If anyone has a better solution or can explain why this problem is occurring, let me know.
Thanks
According to me you are doing nothing wrong... except you are specifying to many things...
For eg:
dataType: "json",
is sufficient for ajax call to work.... there is no need for
contentType: "application/json; charset=utf-8",
in your code, if you add this line it returns the empty array in return for some reason (not very sure about the actual reason)....
But moment I specify just
dataType: "json",
it works like a charm where in return I get the object, which I need not parse.
edit:
What I tried is as followring... just change the input name to fname from name and it worked very well
<form id="myForm" name="myForm" method="POST"
action="postform_ajax.php">
name: <input type="text" name="fname" /> <br /> email: <input
type="text" name="email" /> <br /> message: <input type="message"
name="message" /> <br /> <input type="submit" />
<div id="formResponse"></div>
</form>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#myForm").submit(function() {
dataString = $("#myForm").serialize();
$.ajax({
type : "POST",
url : "postForm_ajax.php",
data : $("#myForm").serialize(),
dataType : "json",
success : function(msg) {
$("#formResponse").removeClass('error');
$("#formResponse").addClass(msg.status);
$("#formResponse").html(msg.status);
},
error : function() {
console.log('err', msg);
$("#formResponse").removeClass('success');
$("#formResponse").addClass('error');
$("#formResponse").html("There was an error submitting the form. Please try again.");
}
});
//make sure the form doens't post
return false;
});
});
</script>