Send email using php, http response erorr - html

I am having problem send email using php and jquery if some one can take a look and help me i would be thankful to him.
This is my HTML
<form id="contact" name="contact" method="post">
<h2>
<span>
Read This FREE Report
</span>
Discover How You Could Become a Successful Forex Trader In As Little As 72 Hours From Now (or Less)!
</h2>
<input type="text" id="name" placeholder="Name" name="name" required />
<input type="email" id="email" placeholder="Email" name="email" required />
<button type="submit">
Free Instant Access
</button>
</form>
Jquery
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$('form').submit(function (event) {
// Stop the browser from submitting the form.
event.preventDefault();
// Serialize the form data.
var formData = $('form').serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: 'contact_form.php',
data: formData
})
.done(function (response) {
$(formMessages).text("Your form has been send..");
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
})
.fail(function (data) {
$(formMessages).text("Oops! An error occured and your message could not be sent");
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
Php
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
// Check that data was sent to the mailer.
if ( empty($name)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! Dogodio se problem za vašim zahtjevom. Molimo pokušajte opet.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "email#hotmail.com";
// Set the email subject.
$subject = "Web contact from $name";
// Build the email content.
$email_content = "Person: $name\n";
$email_content = "Email: $email\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Došlo je do pogreške, nismo uspjeli poslati vašu poruku.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "Dogodio se problem za vašim zahtjevom. Molimo pokušajte opet.";
}
?>
And this is error i get:
Fatal error: Call to undefined function http_response_code() in /home2/speanut/public_html/freeforexreport.com/contact_form.php on line 35

Seems like your PHP Version is below 5.4. The http_response_code() function was introduced in PHP 5.4.
I would advice you to update for PHP 5.4 or higher. If you can not do that, you can use following compatibility code:
// For 4.3.0 <= PHP <= 5.4.0
if (!function_exists('http_response_code'))
{
function http_response_code($newcode = NULL)
{
static $code = 200;
if($newcode !== NULL)
{
header('X-PHP-Response-Code: '.$newcode, true, $newcode);
if(!headers_sent())
$code = $newcode;
}
return $code;
}
}
For more reference look at the following question.

Related

How to get data from html form?

What is the most modern way to get data from an html form and email it to yourself?
One way could be to have a JQuery .sumbit() event handler on your submit button which would gather all the info from the form and send them to a backed controller which would actually send the email.
JQuery example:
$('form').submit(function(event) {
// get the form data
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'phone' : $('input[name=phone]').val()
};
// process the form
$.ajax({
type : 'POST',
url : 'process.php',
data : formData,
dataType : 'json',
encode: true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
});
event.preventDefault();
});
The server side could look something like:
<?php
// process.php
$errors = array();
$data = array();
// Validation
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
if (empty($_POST['phone']))
$errors['phone'] = 'phone is required.';
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
// Send email here
$data['success'] = true;
$data['message'] = 'Success!'
}
?>
In this way you would decouple client side logic (gather form data) and backend logic (send the email).

how to friend invite send to mail?

(Update)Hi all i want to invite friend sent to mail using Nodejs. Mainly server side user and pass which can be use? and mail also can't sent then i tried many ways but unable to get the solution if any one knows the solution please help me.....
myplunker
HTML:-
<div id="container">
<center>
<input id="to" type="text" placeholder="Enter E-mail ID" /><br><br>
<input id="subject" type="text" placeholder="Write Subject" /><br><br>
<textarea id="content" cols="40" rows="5" placeholder="Message"></textarea><br><br>
<button id="send_email">Send Email</button>
</center>
<span id="message"></span>
</div>
Server:-
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
use_authentication: true,
auth: {
user: "sample#gmail.com",
pass: "password"
}
});
app.get('/',function(req,res){
res.sendfile('index.html');
});
app.get('/send',function(req,res){
var mailOptions={
to : req.query.to,
subject : req.query.subject,
text : req.query.text
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end("error");
}else{
console.log("Message sent: " + response.message);
res.end("sent");
}
});
});
The Following steps may help you:
Add var nodemailer=require("nodemailer") to the top of your server
script
Add var express=require("express"); var app=express() to the top of your server script
To Test that the email is being sent move what is in your app.get("/send") script outside the function and comment everything else (For Now) should Look similar to this:
var nodemailer=require("nodemailer");
var express=requre("express");
var app=express();
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
use_authentication: true,
auth: {
user: "email#domain.com",
pass: "PASS"
}
});
var mailOptions={
to : "email#domain.com",
subject :"SUBJECT",
text : "MESSAGE"
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
}else{
console.log("Message sent: " + response.message);
}
});
/*
app.get('/',function(req,res){
res.sendfile('index.html');
});
app.get('/send',function(req,res){
var mailOptions={
to : req.query.to,
subject : req.query.subject,
text : req.query.text
}
console.log(mailOptions);
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
res.end("error");
}else{
console.log("Message sent: " + response.message);
res.end("sent");
}
});
});*/
Make sure you have this turned on for the email you are trying to send an email with: https://www.google.com/settings/security/lesssecureapps
Make Sure your version of nodemailer is correct, It should be 0.71v for the setup you have: How to downgrade this node.js module to specific version and prevent automatic upgrade later?
Run the server script with a terminal: node fileName.js (If none of the tips help could you please copy the error stack?)
If everything works uncomment everything and delete the mailOptions and smtpTransport that are outside the app.get. Everything should work now...
Good Luck, And I'll be happy to help if you have any more problems.

JSON issue in Codeigniter File Upload

I am having the below code in view for the file upload form:
<form method="post" action="<?=site_url('api/do_upload')?>" enctype="multipart/form-data" id="upload_photo" />
<input type="file" name="userfile" size="20" class="btn btn-primary" /><br />
<input type="submit" value="upload" class="btn btn-warning btn-xs" />
</form>
The event captures in JS:
$("#upload_photo").submit(function(evt) {
evt.preventDefault();
var url = $(this).attr('action');
var postData = $(this).serialize();
$.post(url, postData, function(o){
if(o.result == 1) {
Display.success(o.output);
}
else
{
Display.error(o.error);
}
},'json');
});
Model, where I am processing the file upload:
public function do_upload()
{
$this->_require_login();
$this->output->set_content_type('application_json');
$config['upload_path'] = 'C:\xampp2\htdocs\kedb\public\img\profile';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '10000';
$config['max_width'] = '1024';
$config['max_height'] = '768';
$config['file_name'] = $this->session->userdata('user_id');
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
if ( ! $this->upload->do_upload('userfile'))
{
$this->output->set_output(json_encode([
'result' => '0',
'output' => $this->upload->display_errors()
]));
}
else
{
$this->output->set_output(json_encode([
'result' => '1',
'output' => 'File Uploaded Successfully'
]));
return false;
//$data = array('upload_data' => $this->upload->data());
//$this->load->view('upload_success', $data);
}
}
When I click the "upload" button, it getting the below error:
{"result":"0","output":"<p>You did not select a file to upload.<\/p>"}
If I remove id="upload_photo" in <form> tag, it is working. It gives error only when I add id attribute in <form>.
I might have missed something or did anything wrong. Could someone please me out?
I resolved the same issue by adding "text/plain" to the json type in the config/mimes.php file. So now this line looks like this (it's 117-th line in the file in the CI version I use):
'json' => array('application/json', 'text/json', 'text/plain'),
.serialize() returns a string of all the form values. You cannot upload files by using .serialize().
If you want to upload via AJAX, then you'll need to create a FormData object. You'll also need to use $.ajax, so you can tweak a few of the settings.
var url = $(this).attr('action');
var postData = new FormData(this);
$.ajax({
url: url,
data: postData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(o){
if(o.result == 1) {
Display.success(o.output);
}
else{
Display.error(o.error);
}
}
});
I haven't been using codeigniter long but I would think this might be because of the way your are implementing the form. Use form_open();
https://ellislab.com/codeigniter/user-guide/helpers/form_helper.html
To add the attributes, do this
<?echo form_open('api/do_upload',array('id'=>'upload_photo'));?>
The Second error I can see is in your AJAX.
$(this).serialize();
You want to pass an object into postdata like so
data:{file:$(this).children('input[type="file"]').val()},
Also! When sending files with AJAX you need to use formData();
formData=new formData();
$file=$(this).children('input[type="file"]');
formData.append('file',$file.files[0],$file.files[0].name);
In case I've got anything wrong:
http://blog.teamtreehouse.com/uploading-files-ajax

How do I use MVC Validation to display a warning message without making the field required?

I have a asp.net MVC website where the user enters a social security number (SSN). The client wants to display a warning message if the SSN is already used, but doesn't want to force them to change the SSN (there are conditions under which multiple records can have the same SSN).
The MVC code I inherited has a validation to check if the SSN has already been used. The code works great. If the user enters a SSN that is already used, a message appears saying "SSN already exists" and prevents the form from being submitted. How can I change this so that the message is displayed, but so it doesn't prevent the form from being submitted?
ModelApplication.cs
[StringLength(9, MinimumLength = 9, ErrorMessage = "Please Enter 9 Digit SSN No")]
[Remote("IsSSNExist", "Admin", HttpMethod = "GET")]
public string ApplicantSSN { get; set; }
AdminController.cs
[HttpGet]
public JsonResult IsSSNExist(string ApplicantSSN)
{
if (Session["viewapp"] == null)
{
if (obj_BllApp.IsSSNExist(ApplicantSSN))
return Json("SSN already exists.", JsonRequestBehavior.AllowGet);
else
return Json(true, JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
Application.cshtml
<label>
SSN
</label>
#Html.TextBoxFor(m => m.ApplicantSSN, new { #class = "input-small", #maxlength = "9", #onkeypress = "return ValidateNumberKeyPress(this, event);" })<br />
#Html.HiddenFor(m => m.ApplicantSSNID, new { id = "hdnApplicantSSN" })
span id="spAppSSn" class="SSNmsg">#Html.ValidationMessageFor(m => m.ApplicantSSN)</span>
UPDATE
I also tried using the response header like another poster suggested, but I couldn't get it to work.
This code didn't return anything and broke other javascript I had:
$(function () {
$("#txtApplicantSSN").change(function (xhr) {
alert("Hello");
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getResponseHeader("SSN-DUPLICATED").toLowerCase();
alert(headers);
alert("Goodbye");
});
});
Using the same concept, I tried another way of getting the request header, but I never got a value. It looked like the validation that set the header value was being called after the javascript.
$(function () {
$("#txtApplicantSSN").change(function () {
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getResponseHeader('SSN-DUPLICATED');
$("#remoteMessage").text(headers);
});
});
I tried something similar using session variables, but again the session variable seem to be getting set after the javascript code.
$(function () {
$("#txtApplicantSSN").change(function () {
var someSessionVariable = '#Request.RequestContext.HttpContext.Session["SSNExists"]';
alert(someSessionVariable);
$("#remoteMessage").text(someSessionVariable);
});
});
My current thought is to try to disable the validation when the submit button is clicked, but I haven't found a way to do it. I tried this
HtmlHelper.ClientValidationEnabled = false;
in the controller but it never hits the server side code. I get the validation error before it hits the controller.
Update #2
I disabled the validation when the submit button is clicked using the cancel class:
<input id="Submit1" type="submit" class="btn btn-primary cancel" value="Save" onclick="javascript: return ValidatonCoApplication();" />
This fixes the problem for this field, but disables validation for all other fields. Can someone suggest another way to do what I want without turning off validation?
In summary, this is asp.net MVC with Razor. After the user enters a SSN in a text box, I need a message to appear on the screen saying whether or not the SSN is valid. Currently I have a validation attribute in the model, but this is not only showing the message, it is declaring the model invalid and therefore not letting the user proceed to the next page. I want the validation message to appear, but do not want the model invalid. I'd appreciate any help you could give me. Thank you.
Since you only want to display a message based on the value of ApplicantSSN (not invalidate the model), remove the [Remote] attribute, and instead handle the .change() event of the textbox to call a conroller method and return an appropriate message.
Controller
public JsonResult IsSSNExist(string ApplicantSSN)
{
bool isValid = // your logic
if (isValid)
{
return Json(null, JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
View
#Html.TextBoxFor(m => m.ApplicantSSN) // remove the onkeypress attribute
// add a placeholder for the message
<span class="field-validation-error"><span id="ssn-message">The SSN already exists.</span></span>
css
#ssn-message {
display: none;
}
Script
var url = '#Url.Action("IsSSNExist")';
var ssnMessage = $('#ssn-message');
$('#ApplicantSSN').change(function() {
$.getJSON(url, { ApplicantSSN: $(this).val() }, function(response) {
if(response) {
ssnMessage.show();
} else {
ssnMessage.hide();
}
});
});
Note: If the user enters an invalid value and tabs out of the control, the message will be displayed. You may want additional logic to hide the message if the user then starts typing in the textbox again in whichcase you would alo need to handle the keyup event
You can put validation in response header and then show it using jQuery as follows
[HttpGet]
public JsonResult IsSSNExist(string ApplicantSSN)
{
if (Session["viewapp"] == null)
{
if (obj_BllApp.IsSSNExist(ApplicantSSN)){
Response.AddHeader("SSN-DUPLICATED", "SSN already exists. ");
return Json(true, JsonRequestBehavior.AllowGet);
}
else
return Json(true, JsonRequestBehavior.AllowGet);
}
else
{
return Json(true, JsonRequestBehavior.AllowGet);
}
}
And add a span to display the remote message, and some jQuery in your view like following
<label>
SSN
</label>
#Html.TextBoxFor(m => m.ApplicantSSN,
new { #class = "input-small", #maxlength = "9", #onkeypress = "return ValidateNumberKeyPress(this, event);" })
<br />
#Html.HiddenFor(m => m.ApplicantSSNID, new { id = "hdnApplicantSSN" })
<span id="spAppSSn" class="SSNmsg">
#Html.ValidationMessageFor(m =>m.ApplicantSSN)</span>
<span id="remoteMessage" class="SSNmsg">
#Html.ValidationMessageFor(m =>m.ApplicantSSN)</span>
$(function () {
$('#ApplicantSSNID').rules()
.remote.complete = function (xhr) {
var responseMessage=xhr.getResponseHeader('SSN-DUPLICATED');
if (xhr.status == 200 && xhr.responseText === 'true') {
jQuery('#remoteMessage')[0].innerHTML =
(responseMessage||'');
}
};
});
Note: please don't use Session in MVC. It's not a good practice.
You cannot really do what you want in the way you want. Validation will pass or fail! What you'll have to do is remove the [Remote] validation attribute and do the check in the action you are submitting the form to. If the SSN exists then you'll have to pass this message out once you have completed the processing of the form.
Or use javascript and Ajax to check the SSN when the SSN textbox loses focus, then you can display the warning before the user submits the form

update database using AJAX

I'm trying to update my database using AJAX, but somehow it doesn't work. I have already done the part of getting the data from the database into the input fields.
I have an input field "name":
<form method="post" ACTION="update.php">
<input maxlength="250" NAME="name" id="name" value="SomeName" SIZE="50">
<INPUT TYPE="submit" NAME="submit" id="submit" VALUE="submit">
<span id="error" style="display:none"> Please Enter Valid Data! Did you fill in all the fields?</span>
<span id="success" style="display:none"> the name has been updated successfully!</span>
</form>
And using this code:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$("#submit").click(function() {
var name = encodeURIComponent($.trim($("#name").val()));
var dataString = "name =" + name;
if(name == "")
{
$("#success").fadeOut(2).hide();
$("#error").fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "update.php",
data: dataString,
dataType:'json',
success: function(data)
{
if(!data.error)
{
$("#success").fadeIn(200).show();
$("#error").fadeOut(200).hide();
}
else
{
alert(data.error);
}
}
});
}
return false;
});
});
I'm passing the name to update.php, which is:
<?php
$con = mysql_connect('localhost', 'someUsername', 'somePassword');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("someDatabase", $con);
if(isset($_POST['name']))
{
$name = mysql_real_escape_string($_POST['name']);
$query="UPDATE SOMETABLE SET name ='$name'";
$result = mysql_query($query) or die (mysql_error);
}
else
{
echo "Something wrong with the POST";
}
mysql_close($con);
exit;
?>
I'm getting the error: "Something wrong with the POST";
Thanks in advance.
UPDATE: the problem is not "name" instead of "name =" (which I already have edited). That was just a typing error on here.
var dataString = "name" + name;
this line should be changed to this;
var dataString = "name=" + name;
You use the datatype "json" in the jquery ajax request. And you give only a String to this method.
Change your dataString value to this:
var dataString = {'name':name};
This should work fine ;)
Unless you use turn off the option "processData" you need to pass in an object as data.
See this snippet from the jQuery API:
By default, data passed in to the data option as an object
(technically, anything other than a string) will be processed and
transformed into a query string, fitting to the default content-type
"application/x-www-form-urlencoded". If you want to send a
DOMDocument, or other non-processed data, set this option to false.
http://api.jquery.com/jQuery.ajax/
Your data should be passed as an array (reference), try changing your post to the following:
$.ajax({
type: "POST",
url: "update.php",
data: {
name: name
},
dataType:'json',
success: function(data)
{
if(!data.error)
{
$("#success").fadeIn(200).show();
$("#error").fadeOut(200).hide();
}
else
{
alert(data.error);
}
}
});