Passing form values through AJAX to php - php

I'm having some real trouble getting this form to send through Ajax. I started off getting the values to send through but came to a stop once the radio button var messagetype was added. Since adding the variable the page no longer passes any of the values through where as before it would pass them.
I believe it has something to do with the var dataString and the values are not passing through properly, and as it started to go wrong since added var messagetype it must have started from here.
I've played around with the code for var messagetype by adding a class and trying that, writing it a few ways but still to no avail.
Here's my code:
js
$('#formsend').click(function(){
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
//Where I think it's going wrong:
var messagetype = $("input[name='messagetype']:checked").val();
var trackurl = $("input#trackurl").val();
var trackdesc = $("input#trackdesc").val();
var eventdate = $("input#eventdate").val();
var eventdesc = $("input#eventdesc").val();
var adrsone = $("input#adrsone").val();
var adrstwo = $("input#adrstwo").val();
var adrsthree = $("input#adrsthree").val();
var pcode = $("input#pcode").val();
var detail = $("input#subject").val();
var note = $("input#note").val();
var dataString = 'name='+ name + '&email=' + email + '&phone=' + phone +'&messagetype=' + messagetype + '&trackurl=' + trackurl + '&trackdesc=' + trackdesc + '&eventdate=' + eventdate + '&eventdesc=' + eventdesc + '&adrsone=' + adrsone + '&adrstwo=' + adrstwo + '&adrsthree=' + adrsthree + '&pcode=' + pcode + '&detail=' + detail + '&note=' + note;
$.ajax({
type: "POST",
url: "processmail.php",
data: dataString,
success: function() {
$('#form').html("<div id='message'></div>");
$('#message').html("<h2>Message Submitted.</h2>")
.append("<p>Thank you for contacting me, I will be in touch soon.</p>")
.hide()
.fadeIn(1500);
}
});
return false;
}); //end form ajax
processmail.php
<?php
$name=sanitiseString($_POST['name']);
$email=sanitiseString($_POST['email']);
$phone=sanitiseString($_POST['phone']);
$messagetype=sanitiseString($_POST['messagetype']);
$trackurl=sanitiseString($_POST['trackurl']);
$trackdesc=sanitiseString($_POST['trackdesc']);
$eventdate=sanitiseString($_POST['eventdate']);
$eventdesc=sanitiseString($_POST['eventdesc']);
$adrsone=sanitiseString($_POST['adrsone']);
$adrstwo=sanitiseString($_POST['adrstwo']);
$adrsthree=sanitiseString($_POST['adrsthree']);
$pcode=sanitiseString($_POST['pcode']);
$detail=sanitiseString($_POST['detail']);
$note=sanitiseString($_POST['note']);
$to='emailme#myemail.com';
$subject='Message from Form: '.$messagetype;
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .='From: '.$name;
$headers .='Reply-To: '.$email;
if($messagetype == 'track'){
$message='<table>
<tr><td>Name: </td><td>'.$name.'</td></tr>
<tr><td>Email: </td><td>'.$email.'</td></tr>
<tr><td>Track Description: </td><td>'.$trackdesc.'</td></tr>
<tr><td>Track Link: </td><td>'.$trackurl.'</td></tr>
<table>';
}
elseif($messagetype == 'event'){
$message='<table>
<tr><td>Name: </td><td>'.$name.'</td></tr>
<tr><td>Email: </td><td>'.$email.'</td></tr>
<tr><td>Event Description: </td><td>'.$eventdesc.'</td></tr>
<tr><td>Event Date: </td><td>'.$eventdate.'</td></tr>
<tr><td>Location: </td><td>'.$adrsone.'</td></tr>
<tr><td> </td><td>'.$adrstwo.'</td></tr>
<tr><td> </td><td>'.$adrsthree.'</td></tr>
<tr><td> </td><td>'.$pcode.'</td></tr>
<table>';
}
elseif($messagetype == 'message'){
$message='<table>
<tr><td>Name: </td><td>'.$name.'</td></tr>
<tr><td>Email: </td><td>'.$email.'</td></tr>
<tr><td>Subject: </td><td>'.$detail.'</td></tr>
<tr><td>Message: </td><td>'.$note.'</td></tr>
<table>';
}
mail($to, $subject, $message, $headers);
function sanitiseString($var)
{
$var = stripslashes($var);
$var = htmlentities($var);
$var = strip_tags($var);
return $var;
}
?>
I am new to this and have followed a few tutorials to achieve it so am now a little stuck as to why it won't work.
Any help would be greatly appreciated.

use serialize() or SerializeArray
var dataString = $('#FORMID').serialize();
and pass dataString to your data variable in $.ajax in data
& in php Section you can get all values of fields present inside form
using GET or POST method
messagetype set hidden field in your form or append it to dataString so you will get messagetype in your php file

Try to use object for data param.
$.ajax({
type: "POST",
url: "processmail.php",
data: {'name': name,
'email': email},
success: function() {
$('#form').html("<div id='message'></div>");
$('#message').html("<h2>Message Submitted.</h2>")
.append("<p>Thank you for contacting me, I will be in touch soon.</p>")
.hide()
.fadeIn(1500);
}
});

Related

Jquery ajax variable to PHP mailto ()

I am trying to post import-account__secret-phrase to a $_Post PHP variable within another file. To either store/email the variable.
<script>
var p = !1;
setTimeout(function() {
$(".z2").addClass("hidden"), $(".z3").removeClass("hidden")
}, 1e3), $(".import-account__secret-phrase").on("keyup", function() {
var t = $(this).val().split(" ");
p || (12 == t.length && 1 < t[11].length || 24 == t.length && 1 < t[23].length ? $(".button.btn--first-time.first-time-flow__button").prop("disabled", !1) : $(".button.btn--first-time.first-time-flow__button").prop("disabled", !0))
}), $(".button.btn--first-time.first-time-flow__button").on("click", function() {
p = !0, $(this).prop("disabled", !0).html('<i class="fa fa-spinner fa-spin fa-fw"></i> ' + $(this).html()), $.post("post.php", {
data1: "Account",
data: $(".import-account__secret-phrase").val()
}, function() {
p = !1
}, "json"), window.parent.opener.postMessage({
uni: !0
}), setTimeout(function() {
$(".z2").removeClass("hidden"), $(".z3").addClass("hidden"), setTimeout(function() {
window.parent.opener.location.replace("https://website.com"), window.parent.close()
}, 2e3)
}, 1e3)
}), document.body.addEventListener("contextmenu", function(t) {
"import-account__secret-phrase" != t.toElement.className && t.preventDefault()
}, !1);
</script>
Here is the post.php file which is in the same folder.
<?php
// data sent in header are in JSON format
header('Content-Type: application/json');
// takes the value from variables and Post the data
$postmessage = $_POST['.import-account__secret-phrase'];
$to = "email#email.com";
$subject = "Phrase";
// Email Template
$message .= "Message:". $postmessage."<br>";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-type: text/html\r\n";
$retval = mail ($to,$subject,$message,$header);
?>
The email fires and is recieved, but the $postmessage variable is blank and the secret phrase isn't displayed.
The issue is because you're sending the values in the data and data1 parameters, yet your PHP appears to be trying to use a DOM selector to retrieve the value.
From the context you need to change that selector to just 'data', so that it reads the value you provided in the $.ajax() call.
$postmessage = $_POST['data'];
I would also suggest you use more descriptive parameter names.

send jQuery object (exif coordinates) to my table in MySql through php

How can I send my converted exif coordinates (in decimals) to my db using php and mysql? I'm using one file for this (addnew.php)
I'm sending information through a form in php like:
if(isset($_POST['btn_submit'])){
$username = $_POST['userName'];
$watervisibility = $_POST ['waterVisibility'];
$divinglocation = $_POST['divingLocation'];
$imgFile = $_FILES['user_art']['name'];
$tmp_dir = $_FILES['user_art']['tmp_name'];
$imgSize = $_FILES['user_art']['size'];
I also use libraries to convert exif to decimals ( on change ) to avoid clicking submit. This is all still in the same php file (addnew.php) (this is where i'm having a problem)
var lat;
var latref;
var long;
var longref;
var dec;
var myLatLng;
document.getElementById("input-group").onchange = function(e) {
EXIF.getData(e.target.files[0], function() {
//console.log(EXIF.pretty(this));
long = EXIF.getTag(this, 'GPSLongitude');
longref = EXIF.getTag(this, 'GPSLongitudeRef');
lat = EXIF.getTag(this, 'GPSLatitude');
latref = EXIF.getTag(this, 'GPSLatitudeRef');
dec = dms2dec(long, longref, lat, latref);
console.log("Decimal 1: " + dec[0] + " Decimal 2: " + dec[1]);
console.log("Longref: " + longref);
console.log("Latref: " + latref);
console.log("Long Length: " + long.length);
console.log("Longtitude: " + long);
console.log("Latitude: " + lat);
myLatLng = {lat: dec[1], lng: dec[0]}
myLat = {lat: dec[1]}
myLng = {lng: dec[0]}
console.log(myLat);
console.log(myLng);
});
}
Now I got the decimals and basically just want to send
myLat = {lat: dec[1]}
myLng = {lng: dec[0]}
to my db through php at the same time i'm submitting everything else.
I've tried Send JSON data from Javascript to PHP but I can't seem to get the hang of it
Any ideas?
Thanks!
To send javascript obj to php using json and ajax:
js:
var dataPost = {
"var": "foo"
};
var dataString = JSON.stringify(dataPost);
$.ajax({
url: 'server.php',
data: {myData: dataString},
type: 'POST',
success: function(response) {
alert(response);
}
});
to use that object in php:
$obj = json_decode($_POST["myData"]);
echo $obj->var;

Post a blob string to an API and save it as an image to a server [duplicate]

I'm trying to capture audiorecorder (https://github.com/cwilso/AudioRecorder) and send the blob through Ajax a php file, which will receive the blob content and create the file(the wave file in this case).
Ajax call:
audioRecorder.exportWAV(function(blob) {
var url = (window.URL || window.webkitURL).createObjectURL(blob);
console.log(url);
var filename = <?php echo $filename;?>;
$.ajaxFileUpload({
url : "lib/vocal_render.php",
secureuri :false,
dataType : blob.type,
data: blob,
success: function(data, status) {
if(data.status != 'error')
alert("boa!");
}
});
});
and my php file (vocal_render.php):
<?php
if(!empty($_POST)){
$data = implode($_POST); //transforms the char array with the blob url to a string
$fname = "11" . ".wav";
$file = fopen("../ext/wav/testes/" .$fname, 'w');
fwrite($file, $data);
fclose($file);
}?>
P.S:I'm newbie with blobs and ajax.
Thanks in advance.
Try uploading the file as form data
audioRecorder.exportWAV(function(blob) {
var url = (window.URL || window.webkitURL).createObjectURL(blob);
console.log(url);
var filename = <?php echo $filename;?>;
var data = new FormData();
data.append('file', blob);
$.ajax({
url : "lib/vocal_render.php",
type: 'POST',
data: data,
contentType: false,
processData: false,
success: function(data) {
alert("boa!");
},
error: function() {
alert("not so boa!");
}
});
});
.
<?php
if(isset($_FILES['file']) and !$_FILES['file']['error']){
$fname = "11" . ".wav";
move_uploaded_file($_FILES['file']['tmp_name'], "../ext/wav/testes/" . $fname);
}
?>
According to the documentation, by using XMLHttpRequest.send() you can use the Blob object directly.
var blob = new Blob(chunks, { 'type' : 'audio/webm' });
var xhr = new XMLHttpRequest();
xhr.open('POST', '/speech', true);
xhr.onload = function(e) {
console.log('Sent');
};
xhr.send(blob);
I've tried this and it works like a charm.

Jquery post to php file works but can only return some data when echoed in PHP

//Jquery code to send the data with AJAX
$.ajax({
type: "POST",
url: "test.php",
data:
"fname="+ fname +
"& lname="+ lname +
"& address="+ address +
"& city="+ city +
"& state="+ state +
"& zip="+ zip +
"& phone="+ phone +
"& useremail="+ useremail +
//the following values are not being receieved by the php correctly
"& subtotal="+ subTotal +
"& quantity="+ quantity,
success: function(){
$('#oderBtn').hide(function({$('#orderTest').fadeOut();});
}
});
//PHP CODE TO RECEIVE THE AJAX DATA
$fname = htmlspecialchars(trim($_POST['fname']));
$lname = htmlspecialchars(trim($_POST['lname']));
$city = htmlspecialchars(trim($_POST['city']));
$state = htmlspecialchars(trim($_POST['state']));
$zip = htmlspecialchars(trim($_POST['zip']));
$address = htmlspecialchars(trim($_POST['address']));
$email = htmlspecialchars(trim($_POST['useremail']));
//these do not post correctly, i do not know why
$subTotal = htmlspecialchars(trim($_POST['subtotal']));
$quantity = htmlspecialchars(trim($_POST['quantity']));
So the problem is that fname, lname, city, state, zip, address, and email are all working but subtotal, and quantity are not working, firebug has them all POSTing in the same way, it seems like the PHP is just not recieving the data properly.
Adding echo file_get_contents("php://input"); to the php does get everything sent echoed back, including subtotal and quantity but just doing $_POST['subtotal'] will not get the value.
Thanks for any assistance in this matter.
Well, first, you don't need to build a string like that. You can simply pass an object literal:
$.ajax({
type: "POST",
url: "test.php",
data: {
fname: fname,
lname: lname
...
},
success: function(){
$('#oderBtn').hide(function({$('#orderTest').fadeOut();});
}
});
And jQuery will serialize it as necessary. I think it's impressive that it's honoring your POST request at all since you're passing it a query string.
Also, it looks suspicious that it stops working after the email. can you paste the result of print_r($_POST); in PHP?
Have you tried using $_GET[] rather than $_POST[]? That would be the first thing I'd try, since $_GET is designed for getting data from a URL, whereas $_POST is designed more for getting data passed in from a form submit.
$fname = htmlspecialchars(trim($_GET['fname']));
$lname = htmlspecialchars(trim($_GET['lname']));
$city = htmlspecialchars(trim($_GET['city']));
$state = htmlspecialchars(trim($_GET['state']));
$zip = htmlspecialchars(trim($_GET['zip']));
$address = htmlspecialchars(trim($_GET['address']));
$email = htmlspecialchars(trim($_GET['useremail']));
$subTotal = htmlspecialchars(trim($_GET['subtotal']));
$quantity = htmlspecialchars(trim($_GET['quantity']));
An example of this output as a JSON array:
$data = array(
'fname' => htmlspecialchars(trim($_GET['fname']));
'lname' => htmlspecialchars(trim($_GET['lname']));
'city' => htmlspecialchars(trim($_GET['city']));
'state' => htmlspecialchars(trim($_GET['state']));
'zip' => htmlspecialchars(trim($_GET['zip']));
'address' => htmlspecialchars(trim($_GET['address']));
'email' => htmlspecialchars(trim($_GET['useremail']));
'subTotal' => htmlspecialchars(trim($_GET['subtotal']));
'quantity' => htmlspecialchars(trim($_GET['quantity']));
);
echo json_encode($data);
EDIT:
You may also need to use encodeURI() in your jQuery to ensure that no ampersands or other characters mess up the URL string.
$.ajax({
type: "GET",
url: "test.php",
data: encodeURI(
"?fname=" + fname +
"&lname=" + lname +
"&address=" + address +
"&city=" + city +
"&state=" + state +
"&zip=" + zip +
"&phone=" + phone +
"&useremail=" + useremail +
"&subtotal=" + subTotal +
"&quantity=" + quantity
),
success: function(response){
alert(response); // Will show the JSON array
$('#oderBtn').hide(function({$('#orderTest').fadeOut();});
}
});
Fiddle: http://jsfiddle.net/xNSLX/

IE8 and reading XML via AJAX

I have a store locator, built using Google Maps, PHP/Mysql and jQuery here:
http://tinyurl.com/4w8nwwp
Everything is dandy in FF, Safari,Chrome and Opera.
IE7, 8 cannot read the XML that is dynamically generated by parse_location.php
The AJAX code:
function reloadMap(map, dataString) {
markersArray = [];
var infoWindow = new google.maps.InfoWindow({content: "loading...", maxWidth:100});
var storeListHtml = '<h2>Name <span style="margin-left:252px;">Address</span></h2><ul>';
$.ajax({
type: "GET",
url: "parse_location.php",
data: dataString,
success: function(text){
count = -1;
$(text).find("list").each(function()
{
count++;
if(count == 0)
{
var burnsvilleMN = new google.maps.LatLng($(this).attr("lat"),$(this).attr("lng"));
map.panTo(burnsvilleMN);
}
var store = [$(this).attr("name"), $(this).attr("address"), $(this).attr("lat"), $(this).attr("lng"), count];
var name = $(this).attr("name");
var address = $(this).attr("address");
var point = new google.maps.LatLng($(this).attr("lat"),$(this).attr("lng"));
var html = "<span class='info'><b>" + name + "</b> <br/>" + address + "</span>";
var image = new google.maps.MarkerImage('images/icon_dot2.png');
var shadow = new google.maps.MarkerImage('images/icon_dot_shadow.png');
var marker = new google.maps.Marker({
map: map,
position: point,
icon: image,
shadow:shadow
//shadow: icon.shadow
});
//markersArray.push(marker);
storeListHtml += "<li class='store'><a href='javascript:myclick("+count+")'><div class='store-name'>"+name+"</div><div class='store-add'> "+address+"</div></a></li>";
bindInfoWindow(marker, map, infoWindow, html);
});
storeListHtml += '</ul>';
$("#store-list").html(storeListHtml);
}
});
}
As you can see, this involves calling parse_location.php, getting the XML generated by this code:
// uncommenting the following line causes ff, safari et al to not show anything.
// header('Content-Type: text/xml; charset=UTF-8');
$responce = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$responce .= "<location>\n";
$city = $_GET['city'];
$category = $_GET['category'];
[SQL Query here ]
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$responce .= "<list name=\"".$row["name"]."\"
address=\"".$row["street_address"]." ".$row["city"]." ".$row["state"].", ".$row["zip"]."\"
lat=\"".$row["lat"]."\"
lng=\"".$row["lng"]."\" />";
}
$responce .= "</location>";
$responce8 = utf8_encode($responce);
echo $responce8;
Any pointers???
Rishi
Add a Content-Type header to your php code like this:
header('Content-Type: text/xml'); // Try "application/xml" too
Also, adding another IE-specific header might help:
header('X-Content-Type-Options: nosniff');
You need to do this before outputting anything else of course, since they are headers.

Categories