Sending Email from Flash / Actionscript 2.0 - php

Complete Flash / AS Noob here. Friend wanted a change in Email address and I'm assisting. I notice at the bottom it posts to a formmail.php file but I was wondering if there was an easier way or perhaps someone could help me understand what exactly it POSTS and how AS handles POST methods so I can rewrite a script. As formmail.php is some script from "Andrew Riley (webmaster#boaddrink.com)"
function playTier() {
switch(this.tierContent.tier_txt.text) {
case "Sinking Ship":
bullseye_mc.arrow_ani._x = 205; break;
case "Piggy Bank":
bullseye_mc.arrow_ani._x = 180; break;
case "Loose Change":
bullseye_mc.arrow_ani._x = 155; break;
default:
trace("error for arrow posX")
}
bullseye_mc.arrow_ani.play();
sendEmail();
}
tierContent._alpha = 100;
var recipient = "user#website.com";
var subject = "AP Form";
var nameField:String;
var emailField:String;
var phoneField:String;
var commentsField:String;
//alert format
var alertFormat = new TextFormat();
alertFormat.color = 0xFF0000;
var fields:Array = new Array("name_txt", "email_txt", "phone_txt", "comments_txt");
function alertField():Boolean {
var checkFailure:Number = 0;
for (i=0; i<fields.length; i++) {
if (this[fields[i]].length<1) {
checkFailure++;
trace(checkFailure+"-checkFailure");
this[fields[i]].text = "Required!";
this[fields[i]].setTextFormat(alertFormat);
}
}
if (checkFailure>0) {
return false;
} else {
return true;
}
}
function successWindow() {
this.createTextField("my_txt",1,90,212,300,0);
this.my_txt.background = true;
this.my_txt.backgroundColor = 0x00CC00;
my_txt.multiline = true;
my_txt.autoSize = true;
my_txt.wordWrap = true;
var my_fmt:TextFormat = new TextFormat();
my_fmt.color = 0xFFFFFF;
my_fmt.size = 11;
my_fmt.font = "Verdana";
my_txt.text = "Thank You. Your information has been submitted.";
my_txt.setTextFormat(my_fmt);
}
function progressWindow() {
this.createTextField("progress_txt",1,90,212,300,0);
this.progress_txt.background = true;
this.progress_txt.backgroundColor = 0xFD530B;
progress_txt.multiline = true;
progress_txt.autoSize = true;
progress_txt.wordWrap = true;
var progress_fmt:TextFormat = new TextFormat();
progress_fmt.color = 0xFFFFFF;
progress_fmt.size = 11;
progress_fmt.font = "Verdana";
progress_txt.text = "Transmitting your information.";
progress_txt.setTextFormat(progress_fmt);
}
function sendEmail() {
switch (alertField()) {
case true :
progressWindow()
trace("break!");
var result_lv:LoadVars = new LoadVars();
result_lv.onLoad = function(success:Boolean) {
if (success) {
trace("Form sent!");
successWindow();
} else {
trace("Error in sending");
}
};
var send_lv:LoadVars = new LoadVars();
send_lv.recipient = "user#website.com";
send_lv.subject = "AP Form";
send_lv.sort = "order:name,company,email,phone,question1,question2,question3,question4,question5,question6,question7,question8"
send_lv.name = this._parent.q9.name_txt.text;
send_lv.company = this._parent.q9.company_txt.text;
send_lv.email = this._parent.q9.email_txt.text;
send_lv.phone = this._parent.q9.phone_txt.text;
send_lv.question1 = this._parent._parent.qArray[0];
send_lv.question2 = this._parent._parent.qArray[1];
send_lv.question3 = this._parent._parent.qArray[2];
send_lv.question4 = this._parent._parent.qArray[3];
send_lv.question5 = this._parent._parent.qArray[4];
send_lv.question6 = this._parent._parent.qArray[5];
send_lv.question7 = this._parent._parent.qArray[6];
send_lv.question8 = this._parent._parent.qArray[7];
send_lv.sendAndLoad("formmail.php",result_lv,"POST");
if(lvBytesLoaded < lvBytesTotal) {
progressWindow()
}
break;
case false :
trace("Error missing fields- nothing sent");
break;
default :
trace("Something bad happen");
break;
}
};

If you could post the exact change that your friend wants to make, it would be helpful in answering your question. It sounds like you just need to change the email address, though.
A short answer to your question:
There is some confusion built into this code - there are variables defined and populated that you would expect to be what is sent to the server. BUT, these variables are not referred to later on, when the information is being packaged up in the send_lv object to be sent up to the server.
If you need to change the email address that the email is going to, change send_lv.recipient = "user#website.com"; to send_lv.recipient = "newEmail#domain.com", or whatever.
You could modify to code to make use of the recipient var that is defined near the top of the code, like so:
send_lv.recipient = recipient;
If you do this, then you need to change var recipient = "user#website.com"; to var recipient = "newEmail#domain.com";.
A longer answer to your question:
It's been a pretty long time since I've worked with AS2, but what the code you posted is doing, in general, is gathering the elements of an email and then sending those elements to a PHP script. The PHP script will use the elements it receives to construct and then send an email. In this case, the email will go to user#website.com, with a subject line of AP Form. My guess is that the remaining elements - name, company, email, phone, and the list of questions (or question answers, more likely) will be used to construct the body of the email.
The send_lv object represents the information that will be sent to the server. It is also the means of sending the information to the server (send_lv.sendAndLoad()). The sendAndLoad method sends information to the server and requests a response, which in this case triggers the successWindow function. In between the time that the information is sent and the time a result is received from the server, a progress window is displayed.
You can read up a bit on this method on the LiveDocs documentation. It's pretty informative, and explains the difference between the sendAndLoad, send, and load methods.
Hope that helps.

perhaps someone could help me understand what exactly it POSTS
It posts all variables of the send_lv object (name, company, email, etc.) concatenated as urlencoded string.
If you need a variable in the backend script, just define it on the send_lv object and access it as post variable in the php script.
send_lv.dummy = "my new var"; //frontend
$dummy = filter_input('dummy', INPUT_POST); // in php script

Related

Progressbar using php and jquery

I want to make a mail send program and notify the user with a progress bar while waiting. Unfortunately it does not work as expected, the progressbar is not updated.
The Program loops through an array of mail adresses derived from a database. There first the mail address will be verified fro existence in the mailbox. If not, it will be reported. The reports are collected and at the end sent back to the browser.
The progress is reported by separate ajax posts every second by the javascript function "mitgl.progressBar" and sent by the server via the function "getProgress" at the bottom of the php.
Mail verification and mail sending works but the getProgress seems only be made once instead.
Altough the attached code is only a fragment, the rest of the code works fine.
I cannot find the problem, perhaps someone can see what i am blind for...
Javascript:
versandMail: function() {
mitgl.unselectRec();
mitgl.pInt = window.setInterval(mitgl.progressBar, 1000);
var oForm = $('form[name=vs]').get(0);
$.post(location.href, {
cmd: 'M mailVersand',
de: oForm.de.value,
fr: oForm.fr.value,
sr: oForm.sr.value,
aktiv: oForm.aktiv.value,
anfragen: oForm.anfragen.value,
vorstand: oForm.vorstand.value,
idList: (oForm.idList ? oForm.idList.value : ''),
betreff: oForm.betreff.value,
mailtext: $('textarea[name=mailtext]', oForm).htmlarea('html'),
attachments: JSON.stringify(mitgl.oVersand.mail.attachments)
}, function(data, status, oXhr){
window.clearInterval(mitgl.pInt);
$('#progressbar').remove();
$('#mailReport').remove();
if (data.isEmpty()) {
window.alert('Auswahl hat keine Adressen ergeben');
} else if (data.substr(0, 6) === 'Fehler') {
window.alert(data);
} else {
$('#protokoll tbody').html(data);
mitgl.protoLink();
mitgl.selectTop();
}
});
},
progressBar: function() {
$.post(location.href, {
cmd: 'M getProgress'
}, function(nProgress) {
if ($('#progressbar').length > 0) {
$('#progressbar .bar').css({width: nProgress+'%'});
} else {
var pb = $('<div/>')
.attr('id', 'progressbar')
.appendTo('#cmd');
$('<div/>')
.addClass('bar')
.appendTo(pb);
}
});
},
PHP:
function mailVersand() {
// ... Prepare Mail Data ...
require_once 'phpmailer.class.php';
require_once('class.smtp.php');
require_once('class.verifyEmail.php');
$oVerify = new verifyEmail();
$oVerify->setEmailFrom($cMailFrom);
$oMail = new PHPMailer();
$oMail->SMTPDebug = 0;
$oMail->IsSMTP(); // telling the class to use SMTP
//
// ... and so on ...
$oMail->Host = ...
$aErrors = [];
$nSent = 0;
$nError = 0;
$nProcessed = 0;
$nMails = count($aMitglied);
session_start(); // <-- Session starts
$_SESSION['nProgress'] = '0'; // progress is zero
// loop through mailing list
foreach ($aMitglied as $r) {
$aEmail = explode(';', $r->email);
$email = $aEmail[0];
if ($oVerify->check($email)) {
$oMail->AddAddress($email,"$r->vorname $r->name");
// mail verificatio is ok, try to send
if ($oMail->send() === TRUE) {
$nSent++;
} else {
// no, report error
$e = new stdClass();
$e->email = $email;
$e->name = $r->name;
$e->vorname = $r->vorname;
$e->error = $oMail->ErrorInfo;
$aErrors[] = $e;
$nError++;
}*/
$oMail->ClearAddresses();
} else {
// Mail verification failed, report error
$e = new stdClass();
$e->email = $r->email;
$e->name = $r->name;
$e->vorname = $r->vorname;
$e->error = $oVerify->getAllErrors();
$aErrors[] = $e;
$nError++;
}
$nProcessed++; // <-- Next processed record
// v-- Calulate percentage of progress
$_SESSION['nProgress'] = strval(round($nProcessed *100 /$nMails));
}
// create error report
$oBericht = new stdClass();
$oBericht->sent = $nSent;
$oBericht->error = $nError;
$oBericht->fails = $aErrors;
// now procedure finished, reply final report
// ....
$s = $this->listVersand();
echo ($s); // send reply
session_write_close(); // session ends
exit;
}
function getProgress() {
session_start();
//$n = isset($_SESSION['nProgress']) ? "$_SESSION[nProgress]" : "5";
$n="20";
echo ($n);
exit();
}
I found the problem. Sessions can store values between successive calls to a webpage. What I was intended to do is passing a value between active PHP processes.
One way to do this is using APC calls. However this is not available anymore in php versions newer than 5.3, so I have chosen a way to store the progress information in a database.
It's not very effective, it uses a lot of recources. If someone knows a better way to share variables between active php processes it would be nice to tell it here.

extjs4 and php issue - 500 Internal server error when creating entries

I've been stuck with this problem for a day now. I think I'm overlooking something simple but I can't see it.
I am developing a web application where the user fills up forms and the forms get saved in the database. However, I'm having a problem inserting values to a form. The database does not update and I get a 500 Internal Server Error at the console.
Here is the controller that I call when the user saves the form that was filled up
var personStore = Ext.getStore('personBaseDetails');
var caStore = Ext.getStore('creditApplication');
var form = button.up('form').getForm();
var id = personStore.first().get('ID');
//use this to update
if(caStore.count() < 1){
var creditApplication = Ext.ModelManager.create({
}, 'app.model.creditApplicationModel');
caStore.add(creditApplication);
}
var record = caStore.first();
form.updateRecord(record);
caStore.getProxy().extraParams = {
selectedUserID: id
};
caStore.sync({
success: function(batch) {
console.log(batch.operations[0].request.scope.reader.jsonData['message']);
},
failure: function(batch) {
console.log("Failed syncing ca");
}
});
I have checked with various console.log statements that all of the variables here have the proper values.
Here is the php file that gives the 500 Internal Server Error problem:
<?php
require_once('../../db_connection.php');
require_once '../../lib/response.php';
require_once '../../lib/request.php';
class creditApplication{
var $ID_PERSON;
var $APPLICATION_TYPE;
var $APPLICATION_SUB_TYPE;
var $APPLICATION_NUMBER;
var $CUSTOMER_NUMBER;
var $DATE;
var $STATUS;
var $ID_UNIT;
}
$request = new Request(array());
if(isset($request->params)){
var $selectedCustomer = '';
if(isset($_GET['selectedUserID'])){
$selectedCustomer = $_GET['selectedUserID'];
$array_r=$request->params;
$inputData = new creditApplication();
$inputData->ID_PERSON=$selectedCustomer;
$inputData->APPLICATION_TYPE=($array_r->APPLICATION_TYPE);
$inputData->APPLICATION_SUB_TYPE=($array_r->APPLICATION_SUB_TYPE);
$inputData->APPLICATION_NUMBER='sample application number';
$inputData->CUSTOMER_NUMBER='sample customer number';
$inputData->DATE='2014-4-4';
$inputData->STATUS=42;
$inputData->ID_UNIT='sampleUnit';
$query="INSERT INTO CREDIT_APPLICATION (ID_PERSON, APPLICATION_TYPE, APPLICATION_SUB_TYPE, APPLICATION_NUMBER,
CUSTOMER_NUMBER, DATE, STATUS, ID_UNIT)
VALUES ($inputData->ID_PERSON,
'$inputData->APPLICATION_TYPE',
'$inputData->APPLICATION_SUB_TYPE',
'$inputData->APPLICATION_NUMBER',
'$inputData->CUSTOMER_NUMBER',
'$inputData->DATE',
$inputData->STATUS,
'$inputData->ID_UNIT')";
$result = mysql_query($query);
//object response
$res = new Response();
$res->success = true;
$res->message = "Created user";
print_r($res->to_json());
}
else{
$res = new Response();
$res->success = false;
$res->message = "Error - no userID";
$res->data = array();
print_r($res->to_json());
}
}
else{
$res = new Response();
$res->success = false;
$res->message = "Error - no request";
$res->data = array();
print_r($res->to_json());
}
?>
All the database rows are varchars except for ID_PERSON and STATUS which are ints (hence the single quotes in the insert) and the DATE which is of date format.
Now, I've tried hard coding the values, commenting out the if else conditions, and calling the php file through localhost:8888/..../createCreditApplication.php and it actually works. The problem happens when I bring back the if-else blocks and get the values passed to the php file.
I appreciate any help.

Inserting Variables From Jquery Always Fails

i have some problem, i made some local website using php.
I have a file called functions.php which this is the code:
public function saveAll($idmt_salesarea, $thn_bln, $no_pesanan, $tgl_pesan, $idms_langganan, $idms_kodebarang, $quantity, $harga, $jumlah, $disc_cash, $disc_kredit){
$message = "Waiting input...";
try{
$con = new db();
$conn = $con->connect();
$query = "INSERT INTO mt_pesanan(idmt_salesarea,thn_bln,no_pesanan,tgl_pesan,idms_langganan, idms_kodebarang,quantity,harga,jumlah,disc_cash,disc_kredit) VALUES ($idmt_salesarea, '$thn_bln', '$no_pesanan', '$tgl_pesan', $idms_langganan, $idms_kodebarang, '$quantity', $harga, $jumlah, '$disc_cash', '$disc_kredit')";
$result = mysqli_query($conn, $query) or die(mysqli_error($conn) . " " . mysqli_errno());
if($result == 1){
$message = "Success";
} else if($result == 0){
$message = "Failed";
}
}catch(Exception $exc){
echo $exc->getCode();
}
$con->disconnect();
return $message;
}
i Take the input parameter from file called: index.php and pass the parameter using AJAX Jquery. The parameter itself is sent and pointing to file called insert.php
here's the insert.php file:
<?php
include_once 'functions.php';
$idmt_salesarea = isset($_GET['salesarea']);
$thn_bln = isset($_GET['thn_bln']);
$no_pesanan = isset($_GET['nopes']);
$tgl_pesan = isset($_GET['tglpes']);
$idms_langganan = isset($_GET['idlangganan']);
$idms_kodebarang = isset($_GET['idbarang']);
$quantity = isset($_GET['quantity']);
$harga = isset($_GET['harga']);
$jumlah = isset($_GET['jumlah']);
$disc_cash = isset($_GET['disc_cash']);
$disc_kredit = isset($_GET['disc_kredit']);
if (($disc_cash == null) || ($disc_kredit == null)) {
$disc_cash = 0;
$disc_kredit = 0;
}
$insert = new functions();
$insert->saveAll($idmt_salesarea, $thn_bln, $no_pesanan, $tgl_pesan, $idms_langganan, $idms_kodebarang, $quantity, $harga, $jumlah, $disc_cash, $disc_kredit);
?>
but when i check the error, that is the variable that cannot get from insert.php file (using $_GET statement).
How proper way to gain the variable? because all the parameter is set.
I know this is combining object oriented style and old fashion php coding. Any ideas?
thanks in advance.
UPDATE
here's the index.php file using jquery ajax to sent the data
function sendAll(){
var tgl_pesan = $('#dpc').val();
var sales_area = $('#sales_area').val();
var nopes = $('#no_pesanan').val();
var thnbln = getTahunBulan();
var id_langganan = $('#kode_langganan').val();
var id_barang = $('#kode_barang').val();
var quantity = getQuantity();
var harga = $('#harga').val();
var jumlah = $('#jumlah').val();
var disc_cash = $('#cash').val();
var disc_kredit = $('#kredit').val();
var max = $('#max').val();
$.ajax({
type:"POST",
**url:"insert.php",**
data:{
salesarea:sales_area,
thn_bln:thnbln,
nopes:nopes,
tglpes:tgl_pesan,
idlangganan:id_langganan,
idbarang:id_barang,
quantity:quantity,
harga:harga,
jumlah:jumlah,
disc_cash:disc_cash,
disc_kredit:disc_kredit,
max:max
},
success:function(msg){
alert("Data Inserted");
},
error:function(msg){
alert("Data Failed to save" + msg);
}
});
the ajax itself is pointing to file insert.php which the insert.php is executing function from another file called functions.php
The problem is with this code:
$idmt_salesarea = isset($_GET['salesarea']);
$thn_bln = isset($_GET['thn_bln']);
$no_pesanan = isset($_GET['nopes']);
$tgl_pesan = isset($_GET['tglpes']);
$idms_langganan = isset($_GET['idlangganan']);
$idms_kodebarang = isset($_GET['idbarang']);
$quantity = isset($_GET['quantity']);
$harga = isset($_GET['harga']);
$jumlah = isset($_GET['jumlah']);
$disc_cash = isset($_GET['disc_cash']);
$disc_kredit = isset($_GET['disc_kredit']);
For each of those variables, you are assigning the result of isset(), which will evaluate to either TRUE or FALSE. If you want to bind the actual value of your $_GET input, change each line from this syntax:
$idmt_salesarea = isset($_GET['salesarea']);
To
$idmt_salesarea = isset($_GET['salesarea']) ? $_GET['salesarea'] : '';
However this code isn't really maintainable, and I would also recommend using arrays instead of passing that many arguments to your saveAll() method.
In response to your update
If you are sending an AJAX request with type: "POST", you cannot access your input data via the PHP $_GET super global, you have to use $_POST. However, what I said before is still valid, as you aren't binding values to your variables properly.
Although I do not get what you are saying completely, still based on your description the problem can be you sending the variable using ajax call. If the ajax call is async you might not get the value by the time you use it.
So you can either set async:false in the ajax call (which is not a good way) or trigger any thing that uses that variable from within the success callback handler of the ajax call.
It would be really helpful if you can share the piece of code which explains the following statement of yours.... "i Take the input parameter from file called: index.php and pass the parameter using AJAX Jquery. The parameter itself is sent and pointing to file called insert.php"

Flash Registration Form

I need help with my flash registration form. I made sure all my information is correct, but when I enter the information, it doesn't seem to enter it into the mysql database. Here is the flash code:
var lvSend:LoadVars = new LoadVars();
var lvReceive:LoadVars = new LoadVars();
register_btn.onRelease = function() {
var valid:Boolean = validateForm();
if(valid){
//gather information and put in loadvars object
lvSend.username = username.tInput.text;
lvSend.password = password.tInput.text;
lvSend.email = email.tInput.text;
//send information php script for insertion into database
lvSend.sendAndLoad("register.php", "POST");
}
};
function validateForm():Boolean{
if(username.tInput.text == "" || password.tInput.text == "" || email.tInput.text == ""){
return false;
}
return true;
}
function clearTextFields():Void{
username.tInput.text = "";
password.tInput.text = "";
email.tInput.text = "";
}
Here is the Php Code:
http://i.stack.imgur.com/cvvcO.png
Sorry that my code is in picture form. That was the best way I could make it readable by you guys.My problem is that all the information in both codes seem correct. All my text fields are called username, password, and email, same goes for the database columns. The database info isn't wrong because I used the php code with html, I just can't get it to work with flash. My php file is called register.php and my flash file is called play.swf. Thanks for your help!
try:
lvReceive.onLoad = function(success:Boolean) {
if (success) {
trace("ok");
}
else {
trace("error");
}
lvSend.sendAndLoad("register.php", lvReceive, "POST");

strange issue with FLASH/PHP

i am having strange issue with Flash and PHP. actually i have one Forgot password form in flash in which user enters his email id and when presses submit button flash passes data to PHP and retrieves(here i am stuck) data from PHP.
The issue is Flash getting UNDEFINED from PHP.
my flash code.
var email_id:RegExp = /(\w|[_.\-])+#((\w|-)+\.)+\w{2,4}+/;
var urlRequest:URLRequest = new URLRequest("forgot_password.php");
var urlVariable:URLVariables = new URLVariables();
var urlLoader:URLLoader = new URLLoader();
urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
urlLoader.addEventListener(Event.COMPLETE, urlLoader_complete);
btn_submit.addEventListener(MouseEvent.CLICK, btn_submit_click);
function btn_submit_click(e:Event)
{
if(txt_email.text == "")
{
txt_error.text = "Email can not be blank.";
}
else if(!email_id.test(txt_email.text))
{
txt_error.text = "Enter proper email address.";
}
else
{
urlVariable.mailId = txt_email.text;
urlRequest.data = urlVariable;
urlLoader.load(urlRequest);
}
}
function urlLoader_complete(e:Event)
{
trace(e.target.data.return_var); // **it receive Undefined** i am checking in flashlog.txt :(
//txt_error.text = e.target.data.return_var;
}
my PHP code
<?php
require_once('connection.php');
$query = "select * from user_account where email='".$_REQUEST['mailId']."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
echo "return_var=success";
}
else
{
echo "return_var=failed";
}
?>
there is a space before return_var but i don't know why.. i have checked my PHP file 100 times it is perfect than what is the issue??????????????????????????????????????????
EDIT:
If i am tracing
trace(e.target.data);
it traces
%20return%5Fvar=success
Note %20 before return%5var // what is that?????????????
Obviously problem isn't in PHP, anyway you should write it something like this to prevent SQL injection...
<?php
require_once 'connection.php';
$email = $_GET['mailId'];
$email = mysql_real_escape_string($email);
$query = "SELECT email FROM user_account WHERE email = '$email' LIMIT 1";
$result = mysql_query($query);
echo (mysql_num_rows($result) > 0)? 'return_var=success': 'return_var=failed';
?>
Remove this line:
urlLoader.dataFormat = URLLoaderDataFormat.VARIABLES;
and change your urlLoader_complete() function to:
function urlLoader_complete(e:Event)
{
var loader:URLLoader = URLLoader(e.target);
var vars:URLVariables = new URLVariables(loader.data);
trace(vars.return_var);
}
does that help?
First of all thank you all for your contributions.
Now the issue was not related with Flash or PHP but it was related with our server. if i am creating PHP file and directly saving on our server than that PHP file gives response with adding one space before variable name. and if i am creating PHP file and saving it in my local drive and than pasting it on my server it works perfectly!!!!!!!!!!!!!!!!!
see the response difference between two files..............
return_var=success
return_var=success // adding space before response.
may be its issue related with memory but now its working fine so cheers!!!!!!!!!
Again many Thanx.

Categories