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"];
}
Related
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.
I have a Javascript variable that is an object with keys and arrays (shortened version shown below). I scripted in HTML a form so that a users with access (after they login) can delete, add, or alter any of the Keys for their genealogy. What I need to know is how to take this new, altered variable and save it to the server as say, userNameGenealogy.js so that another page can use it. I have done some searching, but do not know if what I need is only PHP oriented, or if I will need to look into AJAX or JSON as well.
var genealogy = {};
genealogy["Johnson"] = {
"Ron": new Array(
{"nickname":"Ronny","dob":"06/20/88"},
{"nickname":"Ronald","dob":"03/15/54"}),
"Scott": new Array(
{"nickname":"Scotty","dob":"01/21/42"})
};
This is just a short snippet, but I'd prefer not to have to change the format of the Javascript, as the rest of the site is coded to work with it as is. Any help / point in the right direction would be greatly appreciated.
You need to use ajax for that. For example with ajax() and pass data parameter to it. Then you need to handle that in PHP script in which you have to read $_POST (in case below) parse it as you like it, save to file and echo response.
JavaScript code:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
Below is my javascript function that makes an ajax call via post. It sends a file location and the contents of a file to a php page that saves the file. The idea is so users can manage config file templates for a small application via the browser instead of manually logging into remote servers, making edits, and submitting the edits back to src control to be pulled into each application (it's all automated on the page that this ajax call posts the data to).
My problem is with fileloc. I CANNOT get my ajax call to post the fileloc and keep the dir structure intact. I've tried escape(), encodeURI(), encodeURIComponent(), and JQuery's versions of these functions. No matter what, my fileloc comes through on the saveConfigTemplates.php page as: "D:TestPHPconfigurationautomationtemplatesservernamefilename.cfg". I've tried php's decode and it doesn't make a difference... it's like the post loses all encoding and treats the single slashes as escape chars. Driving me nuts, any suggestions are appreciated.
function saveFile(){
var fileContents = $("#fileContent").val();
alert(fileContents);
var fileloc = "D:\TestPHP\configuration\automation\templates\servername\filename.cfg";
var fileconts = "fileloc="+encodeURIComponent(fileloc)+"&fileconts="+fileContents;
$.ajax({
type: "POST",
url: "saveConfigTemplates.php",
data: fileconts,
success: function(data) {
alert(data);
}
});
}
escape the backslashes:
var fileloc = "D:\\TestPHP\\configuration\\automation\\templates\\servername\\filename.cfg";
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).
Could someone point me in the right direction here?
Basically, I've got this jQuery code snippet:
$('.bggallery_images').click(function () {
var newBG = "url('" + $(this).attr('src');
var fullpath = $(this).attr('src');
var filename = fullpath.replace('img/Bakgrunner/', '');
$('#wrapper').css('background-image', newBG);
// Lagre til SQL
$.ajax({
url: "save_to_db.php",
// The url to your function to handle saving to the db
data: filename,
dataType: 'Text',
type: 'POST',
// Could also use GET if you prefer
success: function (data) {
// Just for testing purposes.
alert('Background changed to: ' + data);
}
});
});
This is being run when I click a certain button. So it's actually within a click handler.
If I understand this correctly, this snippet takes the source if the image I just clicked and strips it so I end up with only the filename. If I do an alert(filename), I get the filename only. So this is working ok.
But then, it does an ajax call to a php file called "save_to_db.php" and sends data: filename. This is correct right? Then, it does a callback which does an alert + data.
Does this seem correct so far?
Cause my php file looks like this:
<?php
require("dbconnect2.php");
$uploadstring = $_POST['filename'];
$sessionid = $_SESSION['id'];
echo ($sessionid);
mysql_query("UPDATE brukere SET brukerBakgrunn = '$uploadstring' WHERE brukerID=" .$_SESSION['id']);
mysql_close();
?>
When I click the image, the jQuery snippet fires and I get the results of this php file as output for the alert box. I think that the variables somehow are empty.
Because notice the echo($sessionid); which is a variable I've created just to test what the session ID is. And it returns nothing. What could be the issue here?
Edit: I just tried to echo out the $uploadstring variable as well and it also returns nothing. It's like the jQuery snippet doesn't even pass the variable on to the php file?
You're trying to send just the filename, but you're retrieving a named form field in your PHP code. So you need to send a named form field:
Change your ajax call like this:
$.ajax({
url: "save_to_db.php",
// The url to your function to handle saving to the db
data: {filename: filename}, // <= Change #1 (give jQuery a simple object)
dataType: 'text', // <= Change #2 ('text', not 'Text')
type: 'POST',
// Could also use GET if you prefer
success: function (data) {
// Just for testing purposes.
alert('Background changed to: ' + data);
}
});
Your PHP script will now receive a POST varible called filename whose value comes from your filename Javascript variable. (You can also use $.post to do this, but it's just a wrapper for ajax anyway...)
Passing a simple object into the ajax call is the easiest way to send fields to the server. jQuery will take the object and create the URL-encoded form data (doing all of the escaping for you) by using the object's keys and field names. So for instance, if you give it this object:
data: {a: 1, b: "testing one two three", c: 3}
...it sends this URL-encoded data:
a=1&b=testing+one+two+three&c=3
(Note how it encodes it for us.) More in the ajax docs (but beware, at present what the docs say about array handling is wrong; see this bug report for details).