Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to retrieve information from text fields on button click and send the data to mail#example.com:
$(document).ready(function() {
$("#submit").click(function() {
var email = $("#email").val();
var name = $("#Name").val();
var subject = $("#Subject").val();
var text = $("#textarea").val();
var telephone = $("#tel").val();
var varData = "email : " + email + "name : " + name + "subject : " + subject + "text : " + text + "telephone : " + telephone;
console.log(varData);
$.ajax({
type: "POST",
url: 'sendPHP.php',
data: varData,
success: function() {
alert("message sent");
}
});
});
});
sendPHP.php:
<?php
$to = 'mail#example.com';
$name = $_POST['email'];
and so on ..
..
..
mail(mail#example.com, name, (here goes email, name, subject, textarea, tel) as message in new lines);
and somewhere i have to write from what emial im sending to example#gmail.com and what is it's password i guess
?>
While it is still somewhat unclear what your exact concern is, I have a few thoughts on your process.
1 - You are sending data to a php file as a string which is not recommended and is probably giving you problems right there. I have really seen 2 approaches to sending data to the server via post: A) store your data in a form and use jQuery's $().serialize() function, or B) store your data in a JSON object and send it that way.
Option B is my preferred method because JSON simplifies everything. It has the advantage that your data is already stored as key/value pairs, and PHP makes it super easy to work with JSON using the json_decode function. Let's make a few changes to the existing code you have:
$(document).ready(function() {
$("#submit").click(function() {
var email = $("#email").val();
var name = $("#Name").val();
var subject = $("#Subject").val();
var text = $("#textarea").val();
var telephone = $("#tel").val();
var varData = {
"email" : email ,
"name" : name,
"subject" : subject,
"text" : text ,
"telephone" : telephone
} //This is your data in JSON form
console.log(varData);
$.ajax({
type: "POST",
url: 'sendPHP.php',
data: JSON.stringifiy(varData), //Notice that I added JSON.stringify
success: function() {
alert("message sent");
}
});
});
});
Now I'll show you how to handle this in PHP - it's actually very simple.
Step 1 - turn this JSON object into an associative array so that it's easy to work with:
$input = json_decode(file_get_contents('php://input'), true);
Now we have a variable called $input that is an associative array with all of your mail data - let's set up the variables you need.
$email = $input['email']; //Notice string in brackets is JSON key
$name = $input['name'];
$subject = $input['subject'];
$text = $input['text'];
$telephone = $input['telephone'];
Ok, cool - all of your data you gathered from the front end is now ready for use on the back end. So it looks like you're using the built-in mail() function that PHP offers. I would highly recommend using a library for this as they are typically much more reliable and verbose. My favorite is called PHPMailer - here's a link to their github page https://github.com/PHPMailer/PHPMailer.
If you'd like to use that library, the process is simple.
First, include the autoloader file in your script
<?php
require('PHPMailer-master/PHPMailerAutoload.php');
Next, and they have this documented in numerous examples, you create a new instance of PHPMailer and set some basic variables - this is straight from their documentation and I promise you'll have less headache than if you try the PHP mail() approach https://github.com/PHPMailer/PHPMailer/blob/master/examples/gmail.phps.
Best of luck and let me know if I was unclear on anything.
Related
I'm using the jquery get() function to send data. The data was array with information that can have special characters like / , ? and " . When this happens i can't access to url because the characters spoil the link.
How can i solve that? I did this:
function exemple()
{
$('.add').click(function(e)
{
var kitFamilia = $('#select-family').val();
var kitReference = $('#referenceinput').val();
var kitDescription = $('#descriptioninput').val();
var kitModel = $('#model-input').val();
var supplier = $('#select-supplier').val();
var details = [];
//alert(data);
details.push({stamp: stamp,family: kitFamilia, reference: kitReference, description: kitDescription, model: kitModel, supplier: supplier});
details = JSON.stringify(details, null, 2);
//alert(details);
$.get("/management-kit/create-kit/"+details, function(data)
{
location.reload();
});
e.preventDefault();
});
}
You should encode the data with encodeURIComponent
$.get("/management-kit/create-kit/"+encodeURIComponent(details), ..
Keep in mind that you are sending the JSON encoded as part of the path and not as a parameter. (and you might also want to remove the 2 space formating of the JSON as it will make the url quite longer)
This question already has answers here:
"Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP
(29 answers)
Closed 6 years ago.
I am working on my college project, In that i have a webpage which is supposed to display City and temperature, I am trying to use AJAX to update temperature at some intervals.
Here's the code
for ajax request Java Script, I saw this code in this answer https://stackoverflow.com/a/18243161/4341530
function postAjaxRequest(qry){
alert("Ajax response on " +qry);
$.ajax({
type: "POST",
url: "ajax_resp.php",
data: {q: qry},
dataType:'JSON',
success: function(response){
dispatchCallBack(qry,response);
}});}
the alert("Ajax response on " +qry); is working fine so I know this code is running. But when I put this kind of "alert()" just before dispatchCallBack(qry,response); its not working, so I infer here that the request is not successful.
Here's ajax_resp.php
<?php
if(isset($_POST['q'])&&!empty($_POST['q'])
{
if($_POST['q']=="c_temp")
{
$api_key = "Here's my api key, working alright";
$city_id = "here's city id, also working correct";
$url = "http://api.openweathermap.org/data/2.5/forecast/city?id=".$city_id."&APPID=".$api_key;
$json = file_get_contents($url);
$json_o = json_decode($json);
$city_name = $json_o->city->name;
$temp_c = $json_o->list[0]->main->temp-273;
echo json_encode(array("city"=>$city_name,"temp"=>$temp));
//I have checked JSON response seperately its correct. I was able to get city name and temperature variable properly initialised.
}
}?>
so I can't figure out what's wrong. I am newbie :p May be some silly mistake, would be greatfull if pointed out.
Please look at the code below and correct them
[1] use single quotes or double quotes to get data from $_POST variable having the string index
[2] $qry is not defined earlier. After reading the question the most probable value of the $qry can be $_POST['q']. So replace $qry with $_POST['q'] or assign $qry = $_POST['q']
if(isset($_POST['q'])&&!empty($_POST['q'])
{
if($_POST['q']=="c_temp") <== $_POST['q'] instead of $qry
{
$api_key = "Here's my api key, working alright";
$city_id = "here's city id, also working correct";
$url = "http://api.openweathermap.org/data/2.5/forecast/city?id=".$city_id."&APPID=".$api_key;
$json = file_get_contents($url);
$json_o = json_decode($json);
$city_name = $json_o->city->name;
$temp_c = $json_o->list[0]->main->temp-273;
echo json_encode(array("city"=>$city_name,"temp"=>$temp));
//I have checked JSON response seperately its correct. I was able to get city name and temperature variable properly initialised.
}
}?>
i have a problem, help please
i have 2 sites and i want send data each other
first site :
var site_adres = $(location).attr('href');
var myArray = site_adres.split('/');
var site_adi_al = myArray[2];
$.getJSON('xxx.com/site/admin.php?site_adres='+ site_adi_al +'',
{},
function (data) {
$.each( data, function ( i, val ) {
var id=val['id'];
var site_adi=val['site_adi'];
$(".site_adi").append('<li>'+id+' >> <a href="'+site_adi+'"
target="_blank">'+site_adi+'</a></li>');
});
second site:
$site_adi = $_GET["site_adi"];
/* query */
$query = mysql_query("SELECT * FROM site WHERE site_adi = '$site_adi'");
if ( mysql_affected_rows() ){
$row = mysql_fetch_object($query);
$json = array(
"id" => $row->id,
"site_adi" => $row->site_adi
);
}else{
$json["hata"] = "Nothing !";
}
header("access-control-allow-origin: *");
echo json_encode($json);
result zero, what is wrong, help please
You have two basic problems (aside from the security issues explained in the comments on the question).
You are sending site_adres but reading $_GET["site_adi"]. You can't use different names for the same thing without explicitly writing code to link them somehow.
You are looping over data with $.each( data, function ( i, val ) { as if it was an array of objects, but your PHP is only sending a single object (which isn't in an array). You should be accessing the properties of data directly and not using each or val.
You should set up CORS on your webservers to allow them to fetch data from each other, since you're using php, i'm gonna assume you're using apache:
Header set Access-Control-Allow-Origin "*"
replace the * with the ip adress of your other website and vice versa.
I have a textarea where a user can enter 1 or more emails on there, each email separated by comma.
My js code:
var emails = $("#emails").val().split(",");
if (emails.length == 0)
{
window.alert("Enter an email address.");
$("#emails").focus();
return;
}
var valid = validateEmails(emails);
var goodEmails = valid[0];
var badEmails = valid[1];
var json = JSON.stringify(goodEmails);
$.ajax
({
url: "/mfa/service/initiate_user",
type: "POST",
data: {"emails" : json},
The data I see:
["yao#a.com","yao#b.com]
What I was hoping for:
yao#a.com, yao#b.com
The way I would handle it in the backend is basically stripping out the "[ ]" from it then stripping out the quotes from each email.
What is the proper way to send the emails to backend without those silly brackets and quotes?
To get the form yao#a.com, yao#b.com you can use the Array.join(delim) function.
Ex:
var emails = ["yao#a.com", "yao#b.com"];
var email_string = emails.join(", ");
// email_string:
// yao#a.com, yao#b.com
However, I'd say you'd want to keep the emails as an array and do the follow:
var valid = validateEmails(emails);
var goodEmails = valid[0];
var badEmails = valid[1];
$.ajax
({
url: "/mfa/service/initiate_user",
type: "POST",
data: {"emails" : goodEmails},
...
This will allow you to parse the JSON object coming back. Instead of having a string in emails you'll have an array. Not sure of your back-end but this may be an easier approach if you are already able to parse the JSON.
try to add header to ajax configuration:
headers: {'Content-type' : "application/json; charset=utf-8"}
i'm newbie in javascript so, in this example exists the geometrycontrols.js (for global controls) and markercontrol.js (for marker controls)
my problem is identify the arrays where "data" is saved...
at the reference i see a savedata function but i have no idea how work with this function...
on the other side, in test.html if i've the outup on the Glog startup and output "data", and let me thinking that comes from array...
My objective is save the coordinates and other all atributes to mysql database, and when i discover where are "data" is the easy part.
if someone worked with this example (or not) can help me i'm grateful
ps: i'm really a newbie on javascript :P
edit1:
I was out for a time, and now I focus in geometrycontrols.js specially in: GeometryControls.prototype.saveData = function(opts){
var me = this;
if(opts.allData === true){
//me.saveAllData();
} else {
//construct a json data record
var geomInfo = opts.geomInfo, index = opts.geomInfo.index;
var record = geomInfo.storage[index];
var recordJSON = {};
recordJSON.type = record.type;
recordJSON.coordinates = [];
//determine geometry type, and copy geometry appropriately
if(record.type === "point"){
recordJSON.coordinates.push({lat:record.geometry.getLatLng().lat(),lng:record.geometry.getLatLng().lng()});
alert(recordJSON.coordinates);
} else {
alert("is not point");
var vertex;
for(var i=0;i<record.geometry.getVertexCount();i++){
vertex = record.geometry.getVertex(i);
recordJSON.coordinates.push({lat:vertex.lat(),lng:vertex.lng()});
}
}
//add title and description
recordJSON.title = record.title[0];
recordJSON.description = record.description[0];
//TODO add styles
recordJSON.style = ""; //TODO} //TODO Make separate prototype function?function postData(data){
//TODO
me.debug(data);
//alert(recordJSON.coordinates);
//alert(data);
};postData(me.serialize(recordJSON));}; `
When I alert(recordJSON.coordinates), the outupt is [object Object] and i've no idea why, in theory this array contains the coordinates...
Here is some code I have used to send the data to MySQL. It uses a little bit of jQuery to do the ajax magic (the line starting with the dollarsign is jQuery).
function postData(data){
me.debug(data);
var dataString = JSON.stringify(data);
me.debug(dataString);
$.post('storage.php', { data: dataString });
};
postData(recordJSON);
As you can see I've modified the way the 'recordJSON' object gets sent to the postData function a bit too: I've removed the serialise function.
Next, create a PHP file (called 'storage.php' in my case) and put this in it:
<?php
$received = json_decode($_POST['data'], true);
echo "just received " . $received['name'];
?>
You now have an array in PHP that you can do with as you please.
In the examplecode above I've modified the jQuery post function a bit, so if it doesn't work, look there.
The data is stored in JSON format in this file: http://gmaps-utility-library-dev.googlecode.com/svn/trunk/geometrycontrols/examples/data/testdata.js -- it's pretty much self-documenting, just follow the example to set your coordinates.
Note that if you need to find the latitude and longitude for a given address this is a good site: http://itouchmap.com/latlong.html