Send data from jQuery to PHP for mailing - php

I’ve a javascript file I’ve been using as an template for a site I’m working on and in that script there is a simple form validation where it – if no error occur – sends data to an PHP page called contact.php.
But I’m unsure on how I “grab” the data send from the JavaScript in my PHP site? The contact.php works – that is, if I, in my form, direct it directly to contact.php it sends the mail without problem. In that file I send the variables like this: $name = $_POST['formName']; and so on and in the end send it to the mail function.
The code in my JavaScript file where it sends the data and display a “successful” message on the same page is:
$.post("contact.php",
{ formFrom: FromValue, formName: NameValue, formMessage: messageValue },
function(data){
$("#loadingImage").fadeOut("fast", function() {
$("#loadingImage").before('<p>The message has been sucessfully send. Thank you!</p>');
});
}
);
The NameValue, messageValue, FromValue is set in the form validation like this var messageValue = $("#formMessage").val();.
Any help would be very much appreciated.
Sincere
- Mestika

Just use the jQuery AJAX call (this syntax is from jQuery 1.5.X):
$.ajax({
type: 'POST'
url: urlString,
data: {formFrom: FromValue, formName: NameValue, formMessage: messageValue}
}).success(function(data, status, xhr) {
var obj = eval('(' + data + ')');
//response as object
});
To send JSON back to the JavaScript, use this function in your PHP:
http://php.net/manual/en/function.json-encode.php
One other thing: as a rule of thumb, it's poor practice to use variable names like "FromValue." Initial capitalization is supposed to be used for class names, not variables (JavaScript developers borrowed this practice from Java).

Related

Sending data via ajax using php

So, here is ajax setup that I have for my wordpress site.
Page_1.php:
<?php echo '<div class="button" data-post_date="'.$rh_post_date.'" data-post_author_id="' .$rh_author_id. '" data-post_id="' .$id. '">' ;?>
custom_js.js:
jQuery('.button').click(function(e) {
e.preventDefault();
var indiv_id = jQuery(this).data("post_id");
var indiv_post_author = jQuery(this).data("post_author_id");
var indiv_date = jQuery(this).data("post_date");
jQuery.ajax({
type: "GET",
url: upload_image.ajax_url,
dataType: 'html',
data: ({ action: 'rhmp_indi_form', post_id: indiv_id , post_author_id: post_author, post_date_id: indiv_date}),
success: function(data){
jQuery('#rh_pop').html(data);
},
error: function(data)
{
alert("Error!");
return false;
}
});
});
Page_2.php:
<div id="rh_pop">
<?php
$page_2_post_id = $_REQUEST['post_id'];
$page_2_post_author_id = $_REQUEST['post_author_id'];
$page_2_post_date_id = $_REQUEST['post_date_id'];
?>
</div>
As you can see, when the button in the page_1.php is clicked, the data become variables in custom_js.js. These variables are then sent to the page_2.
Now, I know that this is not secure at all and can be hacked easily.
So, how do I send data such as data-post_date or post_author_id to another page via ajax using php?
First of Ajax is a technique that is used in javascript to send a httprequest to the php server. The server handles that request and sends back its result. Its the same as requesting a page normally but then its without reloading the page.
Creating variables in javascript with php for use with ajax doesn't mean that php is the one doing anything ajax related. Hope this clears up a missunderstand.
More info on this: https://en.wikipedia.org/wiki/Ajax_%28programming%29
Sending data to the server is never safe. You can make help features like you need to fill in this field with a name and go on. Or maybe even use a disable the submit button if there aren't 3 or more numbers in a field but this is all to help the user and to make it unlikely that the server will get requests that will never be valid anyway.
This is the reason why server side validation is always needed and client side validation is more of a user friendly thing and making sure the server doesn't get requests that can be detected from the client side already.

How to pass values from ajax to php in wordpress?

Am trying to send mail by passing the values form my JS page to PHP page in Wordpress, I made until the AJAX section
jQuery.ajax({
type: "POST",
url:"contact.php",
data: "frm_adrs=" + frm_adrs + "&to_adrs=" + to_adrs + "&sub=" + sub + "&number=" + number +"&zip=" + zip + "&message=" + message,
success: function(data) {
//...
}
In Php page
if (isset($_GET["frm_adrs"]))
{
$frm_adrs = $_GET["frm_adrs"];
$to_adrs = $_GET["to_adrs"];
Now the problem is the AJAX is not able to find the "contact.php" .. I am not developing any plugin, hence instead of ajaxurl I need to add a static url to send an email..
Thanks in advance
Firstly, you have specified a relative directory to the file "contact.php" in your jQuery code. This means you must be executing the code from a URL stating the same directory as the anticipated location of contact.php. For instance, executing your code on the following URLs would have the respective effect;
/wordpress/index.php => /wordpress/contact.php
/wordpress/contact => /wordpress/contact/contact.php
So you need to verify that your contact.php file is located within the same directory as the file generating the request.
As pointed out by Jai in a comment, you are sending data via jQuery AJAX in the POST method, but your php script is anticipating (listening for) the GET method. This will be problematic as your backend script will not interpret the data you are sending to it.
If you are sending the data as a POST request, then you should use $_POST to retrieve it, otherwise if you're sending the data as a GET request, use $_GET to retrieve it. You can use a more ambiguous method of retrieving the data by using $_REQUEST, however this is not usually the best way of doing things.
You may want to use encodeURIComponent for certain fields using non-alphanumeric characters (for instance, your message variable) this will ensure the data is transmitted correctly between your front and back end code.
Furthermore, you might want to check out the OWASP top 10 list as your script is vulnerable to CSRF attacks, and can be used as an email relay. Check it here
Lastly, it is common practice to use some form of CAPTCHA verification on data forms requiring no previous form of bot filtering / user validation. This prevents bots using your script as a relay to send out malicious or spam emails.
Try this.. sub is a keyword not use sub please use sub1
for theame :- url: "echo get_template_directory_uri()"./contact.php,
for Page-template :- url: "echo
get_template_directory_uri()"./page-template/contact.php,
$.ajax({
method: "POST",
url: "<?php echo get_template_directory_uri() ?>/contact.php",
data: {
frm_adrs : frm_adrs,
to_adrs:to_adrs,
sub1:sub1,
number:number,
zip:zip,
message:message
}
})
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
In php page
In page-template
require_once("../../../wp-load.php");
In Your theames root
require_once("../../wp-load.php");
if (isset($_REQUEST["frm_adrs"]))
{
$frm_adrs = $_REQUEST["frm_adrs"];
$to_adrs = $_REQUEST["to_adrs"];
}

Sending data to php from jquery

have a question and I hope that you can help me with it. I have two file frame.js and up.php. frame.js take data from inputs (work correctly), and sent to up.php.
Frame.js
//some code
$.ajax({
type : "POST",
url: "up.php",
data: {
login: login;
pass: pass},
success : function() {
alert('success');
close_frame ();
}
});
up.php
<?php
echo('reg start'); //message to check that it work
echo ('<script>alert('reg start');</script>'); // another varient to check
if ((isset($_POST['login']))
//some code
?>
SO jquery sent information to up.php. But is up.php launch automatically or what I need to do to make the up.php to take the data from jquery file?
The up.php will run and all the data send via the ajax will be receive in the
$_POST
So basically you do need to do anything to make the data available in the php because it's already available
But notice that you are not doing anything with the response (the 2 echos) so you will have to open the firebug/console in order to see the prints
You can access any variables you send through $_POST in up.php.
You should know that jQuery has a built in function for POST ajax requests:
$.POST(url, data)
.done(function(response){
alert(response);
});
You should process response from up.php in success function. Something like $(body).html(arguments[0])

PHP send form data more than one form/pages

I am a PHP beginner.
I want to send a form data to more than one form/pages. Is it possible?
It sends data to use.php. But I want that it also sends data to two more PHP files: lock.php and unlock.php.
How is it possible?
Make your formdata go to one script, and simply include to the other scripts and they'll have access to the $_POST variable as well.
I use this a lot myself. I have a script where everything runs through the index.php file, but functions are stored in different php files depending on what they're doing. My index.php includes all the php files I need, and inside these php files I have scripting like this:
index.php:
<?php
include('pagename.php');
include('otherpage.php');
echo $return; //output from previous pages
?>
and pagename.php:
<?php
if( $_GET['page'] != 'pagename' )
{
return ('');
}
if( isset($_POST['var']) )
{
// some code
}
You can use Ajax on a client side. I recommend Jquery because it is very easy to start with, or you can use CURL on server side, but it is much more complicated, you can find a bunch of tutorials, just google: sending post data with curl.
Now Jquery Ajax approach:
Lets say your form has an ID of myForm:
make a selector:
$(document).ready(function () {
$("myForm").submit(function (e) {
e.preventDefault(); //prevent default form submit
var url1 = 'your path to url1';
var url2 = 'your path to url2';
var url3 = 'your path to url3';
sendAjax(data,url1);
sendAjax(data,url2);
sendAjax(data,url3);
//do the regular submit
$(this).submit();
});
function sendAjax(data,url){
$.ajax({
url: url,
type:'POST',
data: data,
success: function (data) {
//here you do all the return functionality
},
cache: false
});
});
}
What have we done here:
prevented default sending of form,
made X ajax requests, and send the form normally.
We have made a function for simple ajax handeling just to make our code cleaner.
The problem with this method is that you must make form checking in javascript before you start sending.

Choosing Error Message on AJAX Call

I'm new to using AJAX (but decently experienced in jQuery and PHP) and am wondering if I can have several different error messages on one AJAX call depending on what occurs.
Here is my AJAX function. I'm basically checking the username and e-mail that are used on an HTML form on the page. I'm sending those values to be checked in the database, and if they exists, I need to display an appropriate error message. I need two different messages though. One to say 'That username already exists. Please try again.' and one for e-mail.:
var username = $('input[name="username"]').val();
var email = $('input[type="email"]').val();
var myData =
'username='+ username +
'&email='+ email;
$.ajax({
type: 'POST', // HTTP method POST or GET
url: 'signup_ajax.php', //Where to make Ajax calls
dataType:'text', // Data type, HTML, json etc.
data:myData, //post variables
success:function(response){
$('#register_form').submit();
},
error:function (xhr, ajaxOptions, thrownError){
alert('There was an error.');
}
});
I'm assuming these error messages would come on a 'successful' AJAX call because it's not that the call wouldn't connect to the database, it just wouldn't produce results. I'm figuring there is a way to send data back to the form page from the AJAX PHP page? I was thinking of setting an error message variable to a certain value on the PHP page and then trying to send it back to the Javascript page to be displayed. Is that possible to do? I know I can do these through two separate AJAX calls but I'm just trying to see if it's possible to streamline it into one function. Thanks!

Categories