Progressbar using php and jquery - php

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.

Related

Can't read php file when upload image to server in titanium

I have tried to get the image from gallery and upload the selected image to server using webservices in titanium.
I have used below code. But am getting the debug error : HTTP error And also it shows the alert box like "There was an error during the connection"
This code is working fine in my development server.But it is not working in my client server. What's the reason ? why my code is not working in my client server ?
The file upload is working fine when upload the file from android device.But it's not working while upload a file from iphone device.Can you please give me a idea to resolve this issue ?
Why am getting this error on my console window.
function AUF_ADD_File_FolderData () {
Titanium.Media.openPhotoGallery({
success:function(event) {
var request = Ti.Network.createHTTPClient({
onload : function(e) {
Ti.API.info(this.responseText);
Ti.API.info("image pathe"+" "+event.media);
if(this.responseText == "Successfully file is created"){
var managefolders =Alloy.createController('manage_folders').getView();
managefolders.open();
}
else{
alert(this.responseText);
}
},
onerror: function(e){
Ti.API.debug(e.error);
alert("There was an error during the connection");
},
timeout:20000,
});
var uploadabc = event.media.imageAsResized(400 , 400);
request.open("POST",url+"client/manager/at_manager_create_common_file.php");
var params = ({"manager_id": manager_id,"file": uploadabc,});
// var params = ({"manager_id": manager_id,"file": event.media,});
request.send(params);
},
cancel:function() {
// called when user cancels taking a picture
},
error:function(error) {
// called when there's an error
var a = Titanium.UI.createAlertDialog({title:'Camera'});
if (error.code == Titanium.Media.NO_CAMERA) {
a.setMessage('Please run this test on device');
} else {
a.setMessage('Unexpected error: ' + error.code);
}
a.show();
},
saveToPhotoGallery:false,
// allowEditing and mediaTypes are iOS-only settings
allowEditing:true,
mediaTypes:[Ti.Media.MEDIA_TYPE_VIDEO,Ti.Media.MEDIA_TYPE_PHOTO]
});
}
EDIT:
this is php file :
<?php
$request = base64_decode($_POST['jsondata']);
$data = json_decode($request,true);
$manager_id = $data['manager_id'];
$file_name = $data['file_name'];
$source = base64_decode($data['source']);
include "db_connect.php";
// connecting to db
$db = new DB_CONNECT();
$result = mysql_query("SELECT * from at_common_files WHERE user_id = '$manager_id' and file_name = '$file_name'");
$no_of_rows = mysql_num_rows($result);
if ($no_of_rows > 0) {
$response='{"Error":"1","Message":"Filename already existed"}';
echo $response;
} else {
$upload_dir = 'common_files/'.$manager_id."_".$file_name;
file_put_contents($upload_dir,$source);
$qugery = mysql_query("insert into at_common_files (user_id,file_name) values ($manager_id, '$file_name') ");
$response = '{"Error":"0","Message":"Successfully file is created"}';
echo $response;
}
?>
EDIT:
As am getting the below error :
: [DEBUG] HTTP error
: [INFO] IN ERROR {"type":"error","source":{"cache":false},"code":404,"error":"HTTP error","success":false}
if i have call the same url and pass a manager_id alone , am getting the results fine.if i have passing the manager_id and file, this time only am getting the Http error. i can't find a exact issue.Because the same titanium code and php code (development server)is working fine and the image is uploading to development server folder. but i have moved the same php file to my client server.now it is not working . also the same web service url is working fine in browser and android.it's not working in iphone only.so that exactly i can't find where is the issue ? can you please give me a solutions.
EDIT :
please refer the below link:
http://developer.appcelerator.com/question/174462/image-not-uploading-from-iphone#comment-224007
I have facing a exact same issue.could you please give me a solution.
i have found many questions like this (e.g. The 'Passive' connection '<appname>' access to protected services is denied).
the answer is always:
"This error is what's known as a "Red Herring". It's a clue that's misleading. The HID isn't a real error that affects your app. There should be other messages that may indicate what's going on."
so look if there is a other error massege which describes your problem.
for example try to escape the filename you are using within the sql statements:
$file_name = mysql_real_escape_string($data['file_name']);
Make sure your device is connected to the internet and then try it like this:
Titanium:
function AUF_ADD_File_FolderData () {
Titanium.Media.openPhotoGallery({
success:function(event) {
var xhr = Titanium.Network.createHTTPClient();
xhr.onerror = function(e){
Ti.API.info('IN ERROR ' + JSON.stringify(e));
alert('Sorry, we could not upload your photo! Please try again.');
};
xhr.onload = function(){
Ti.API.info(this.responseText);
Ti.API.info("image pathe"+" "+event.media);
if(this.responseText == "Successfully file is created"){
var managefolders =Alloy.createController('manage_folders').getView();
managefolders.open();
}else{
alert(this.responseText);
}
};
xhr.open('POST', url+"client/manager/at_manager_create_common_file.php");
xhr.send({
media: event.media,
manager_id: manager_id
});
},
cancel:function() {
// called when user cancels taking a picture
},
error:function(error) {
// called when there's an error
var a = Titanium.UI.createAlertDialog({title:'Camera'});
if (error.code == Titanium.Media.NO_CAMERA) {
a.setMessage('Please run this test on device');
} else {
a.setMessage('Unexpected error: ' + error.code);
}
a.show();
},
saveToPhotoGallery:false,
// allowEditing and mediaTypes are iOS-only settings
allowEditing:true,
mediaTypes:[Ti.Media.MEDIA_TYPE_VIDEO,Ti.Media.MEDIA_TYPE_PHOTO]*/
});
}
PHP:
<?php
//this function returns a random 5-char filename with the jpg extension
function randomFileName()
{
$length = 5;
$characters = 'abcdefghijklmnopqrstuvwxyz';
$string = '';
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters))];
}
return $string . '.jpg';
}
//create the random filename string and uploads target variables
$randomString = randomFileName();
$target = 'common_files/'.$randomString;
if(move_uploaded_file($_FILES['media']['tmp_name'], $target))
{
echo "success";
}
else
{
echo "moving to target failed";
}
?>
For more info check this link: http://code.tutsplus.com/tutorials/titanium-mobile-build-an-image-uploader--mobile-8860
If it works like this you will have to add your logic again (resizing and manager_id)

eJabberd with PHP extauth

I'm trying to make a PHP extauth script, i configured extauth in ejabberd.cfg and give permission to auth.php file, the script is the following
#!/usr/bin/php
<?php
error_reporting(0);
$auth = new JabberAuth();
$auth->dbhost = "";
$auth->dbuser = "";
$auth->dbpass = "";
$auth->dbbase = "";
$auth->play(); // We simply start process !
class JabberAuth {
var $dbhost; /* MySQL server */
var $dbuser; /* MySQL user */
var $dbpass; /* MySQL password */
var $dbbase; /* MySQL database where users are stored */
var $debug = true;/* Debug mode */
var $debugfile = "/var/log/pipe-debug.log"; /* Debug output */
var $logging = true; /* Do we log requests ? */
var $logfile = "/var/log/pipe-log.log" ; /* Log file ... */
/*
* For both debug and logging, ejabberd have to be able to write.
*/
var $jabber_user; /* This is the jabber user passed to the script. filled by $this->command() */
var $jabber_pass; /* This is the jabber user password passed to the script. filled by $this->command() */
var $jabber_server; /* This is the jabber server passed to the script. filled by $this->command(). Useful for VirtualHosts */
var $jid; /* Simply the JID, if you need it, you have to fill. */
var $data; /* This is what SM component send to us. */
var $dateformat = "M d H:i:s"; /* Check date() for string format. */
var $command; /* This is the command sent ... */
var $mysock; /* MySQL connection ressource */
var $stdin; /* stdin file pointer */
var $stdout; /* stdout file pointer */
function JabberAuth()
{
#define_syslog_variables();
#openlog("pipe-auth", LOG_NDELAY, LOG_SYSLOG);
if($this->debug) {
#error_reporting(E_ALL);
#ini_set("log_errors", "1");
#ini_set("error_log", $this->debugfile);
}
$this->logg("Starting pipe-auth ..."); // We notice that it's starting ...
$this->openstd();
}
function stop()
{
$this->logg("Shutting down ..."); // Sorry, have to go ...
closelog();
$this->closestd(); // Simply close files
exit(0); // and exit cleanly
}
function openstd()
{
$this->stdout = #fopen("php://stdout", "w"); // We open STDOUT so we can read
$this->stdin = #fopen("php://stdin", "r"); // and STDIN so we can talk !
}
function readstdin()
{
$l = #fgets($this->stdin, 3); // We take the length of string
$length = #unpack("n", $l); // ejabberd give us something to play with ...
$len = $length["1"]; // and we now know how long to read.
if($len > 0) { // if not, we'll fill logfile ... and disk full is just funny once
$this->logg("Reading $len bytes ... "); // We notice ...
$data = #fgets($this->stdin, $len+1);
// $data = iconv("UTF-8", "ISO-8859-15", $data); // To be tested, not sure if still needed.
$this->data = $data; // We set what we got.
$this->logg("IN: ".$data);
}
}
function closestd()
{
#fclose($this->stdin); // We close everything ...
#fclose($this->stdout);
}
function out($message)
{
#fwrite($this->stdout, $message); // We reply ...
$dump = #unpack("nn", $message);
$dump = $dump["n"];
$this->logg("OUT: ". $dump);
}
function myalive()
{
if(!is_resource($this->mysock) || !#mysql_ping($this->mysock)) { // check if we have a MySQL connection and if it's valid.
$this->mysql(); // We try to reconnect if MySQL gone away ...
return #mysql_ping($this->mysock); // we simply try again, to be sure ...
} else {
return true; // so good !
}
}
function play()
{
do {
$this->readstdin(); // get data
$length = strlen($this->data); // compute data length
if($length > 0 ) { // for debug mainly ...
$this->logg("GO: ".$this->data);
$this->logg("data length is : ".$length);
}
$ret = $this->command(); // play with data !
$this->logg("RE: " . $ret); // this is what WE send.
$this->out($ret); // send what we reply.
$this->data = NULL; // more clean. ...
} while (true);
}
function command()
{
$data = $this->splitcomm(); // This is an array, where each node is part of what SM sent to us :
// 0 => the command,
// and the others are arguments .. e.g. : user, server, password ...
if($this->myalive()) { // Check we can play with MySQL
if(strlen($data[0]) > 0 ) {
$this->logg("Command was : ".$data[0]);
}
switch($data[0]) {
case "isuser": // this is the "isuser" command, used to check for user existance
$this->jabber_user = $data[1];
$parms = $data[1]; // only for logging purpose
$return = $this->checkuser();
break;
case "auth": // check login, password
$this->jabber_user = $data[1];
$this->jabber_pass = $data[3];
$parms = $data[1].":".$data[2].":".md5($data[3]); // only for logging purpose
$return = $this->checkpass();
break;
case "setpass":
$return = false; // We do not want jabber to be able to change password
break;
default:
$this->stop(); // if it's not something known, we have to leave.
// never had a problem with this using ejabberd, but might lead to problem ?
break;
}
$return = ($return) ? 1 : 0;
if(strlen($data[0]) > 0 && strlen($parms) > 0) {
$this->logg("Command : ".$data[0].":".$parms." ==> ".$return." ");
}
return #pack("nn", 2, $return);
} else {
// $this->prevenir(); // Maybe useful to tell somewhere there's a problem ...
return #pack("nn", 2, 0); // it's so bad.
}
}
function checkpass()
{
/*
* Put here your code to check password
* $this->jabber_user
* $this->jabber_pass
* $this->jabber_server
*/
return true;
}
function checkuser()
{
/*
* Put here your code to check user
* $this->jabber_user
* $this->jabber_pass
* $this->jabber_server
*/
return true;
}
function splitcomm() // simply split command and arugments into an array.
{
return explode(":", $this->data);
}
function mysql() // "MySQL abstraction", this opens a permanent MySQL connection, and fill the ressource
{
$this->mysock = #mysql_pconnect($this->dbhost, $this->dbuser, $this->dbpass);
#mysql_select_db($this->dbbase, $this->mysock);
$this->logg("MySQL :: ". (is_resource($this->mysock) ? "Connecté" : "Déconnecté"));
}
function logg($message) // pretty simple, using syslog.
// some says it doesn't work ? perhaps, but AFAIR, it was working.
{
if($this->logging) {
#syslog(LOG_INFO, $message);
}
}
}
?>
when i start ejabberd live, i get this error in an infinite loop:
extauth script has exitted abruptly with reason 'normal'
External authentication script needs to be constantly running and thus must be a loop.
This is explained in ejabberd documentation:
https://www.ejabberd.im/files/doc/dev.html#htoc9
I suspect your script is exiting and not actually looping.
As a starting point, you should have a look at this project:
https://github.com/cburschka/ejabberd-auth-php

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.

jQuery plugin Validation email check if else CRAZY WIERD

I have successfully implemented the Jquery Validation Plugin http://posabsolute.github.com/jQuery-Validation-Engine/ but i am now trying to get an ajax database email check to work (email exists / email available) and i have written some php script to get this done. Its kinda working but i am getting the most unexpected heretically odd behavior from my IF ELSE statement (seems really crazy to me). observe ### marked comments
PHP code: LOOK AT THE IF ELSE STATEMENT
/* RECEIVE VALUE */
$validateValue = $_REQUEST['fieldValue'];
$validateId = $_REQUEST['fieldId'];
$validateError = "This username is already taken";
$validateSuccess = "This username is available";
/* RETURN VALUE */
$arrayToJs = array();
$arrayToJs[0] = $validateId;
$req = "SELECT Email
FROM business
WHERE Email = '$validateValue'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results = array($row['Email']);
}
if (in_array($validateValue, $results)) {
$arrayToJs[1] = false;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR ### popup shows "validating, please wait" then "This username is already taken" when email typed is in database - i.e. Working
file_put_contents('output.txt', print_r("1 in array - Email is Taken " . $validateValue, true)); ### this runs!!
}else{
$arrayToJs[1] = true; // RETURN TRUE
echo json_encode($arrayToJs); // RETURN ARRAY WITH success ### popup shows "validating, please wait" when email typed is NOT in the database - i.e. not Working
file_put_contents('output.txt', print_r("2 else - Email is available " . $validateValue, true));
//### THIS RUNS TOO !!!!!!!!!!!!! i.e. echo json_encode($arrayToJs) wont work for both.. If I change (in_array()) to (!in_array()) i get the reverse when email is in database.
//i.e. only the else statements echo json_encode($arrayToJs) runs and the popup msg shows up green "This username is available" crazy right???
//so basically IF ELSE statements run as expected (confirmed by output.txt) but only one echo json_encode($arrayToJs) will work.!!!!
//If i remove the json_encode($arrayToJs) statements and place it once after the IF ELSE statement i get the same problem.
//both $arrayToJs[1] = false; and $arrayToJs[1] = true; can work separately depending on which is first run IF or ELSE but they will not work in the one after another;
}
HERE IS THE REST OF THE CODE-->
1-HTML FORM INPUT CODE:
<tr>
<td> <Label>Business Email</Label>
<br>
<input type="text" name="Email" id="Email" class="validate[required,custom[email],ajax[ajaxUserCallPhp]] text-input">
</td>
</tr>
2-Relevant JQUERY code in jquery.validationEngine.js:
$.ajax({
type: type,
url: url,
cache: false,
dataType: dataType,
data: data,
form: form,
methods: methods,
options: options,
beforeSend: function() {
return options.onBeforeAjaxFormValidation(form, options);
},
error: function(data, transport) {
methods._ajaxError(data, transport);
},
success: function(json) {
if ((dataType == "json") && (json !== true)) {
// getting to this case doesn't necessary means that the form is invalid
// the server may return green or closing prompt actions
// this flag helps figuring it out
var errorInForm=false;
for (var i = 0; i < json.length; i++) {
var value = json[i];
var errorFieldId = value[0];
var errorField = $($("#" + errorFieldId)[0]);
// make sure we found the element
if (errorField.length == 1) {
// promptText or selector
var msg = value[2];
// if the field is valid
if (value[1] == true) {
if (msg == "" || !msg){
// if for some reason, status==true and error="", just close the prompt
methods._closePrompt(errorField);
} else {
// the field is valid, but we are displaying a green prompt
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertTextOk;
if (txt)
msg = txt;
}
if (options.showPrompts) methods._showPrompt(errorField, msg, "pass", false, options, true);
}
} else {
// the field is invalid, show the red error prompt
errorInForm|=true;
if (options.allrules[msg]) {
var txt = options.allrules[msg].alertText;
if (txt)
msg = txt;
}
if(options.showPrompts) methods._showPrompt(errorField, msg, "", false, options, true);
}
}
}
options.onAjaxFormComplete(!errorInForm, form, json, options);
} else
options.onAjaxFormComplete(true, form, json, options);
}
});
3-Relevent code for ajaxUserCallPhp in jquery.validationEngine-en.js:
"ajaxUserCallPhp": {
"url": "validation/php/ajaxValidateFieldUser.php",
// you may want to pass extra data on the ajax call
"extraData": "name=eric",
// if you provide an "alertTextOk", it will show as a green prompt when the field validates
"alertTextOk": "* This username is available",
"alertText": "* This user is already taken",
"alertTextLoad": "*Validating, please wait"
},
Im sure the problem lies with this echo.
echo json_encode($arrayToJs)
Please help i've spent to long on this and its almost working fully.
To clarify - I basically am trying to code it so that if i type an email in the db it shows red "This username is taken" then if i edit the input box to an email not in the database it changes to green "username is available" at the moment only one json_encode will run in any scenario no matter how i change the if else statement –
Thank you very much in advance.
Ok got it finally after a fiddle. I found that json_encode() returns false when any error or warning is posted. using the php error log file in xampp/php/logs/error_logs file i realised that i was getting an error only when the query result was null making $results = null. this caused an output error preventing json_encode() from echoing true, which is why i only got one response.
To fix it i made sure that the $result array was not empty by using the following code after the query to array part.
if(empty($results)){
$results [0]= ("obujasdcb8374db");
}
The whole code is now
$req = "SELECT Email
FROM business
WHERE Email = '$validateValue'";
$query = mysql_query($req);
while ($row = mysql_fetch_array($query)) {
$results[] = $row['Email'];
}
if(empty($results)){
$results [0]= ("obujasdcb8374db");
}
if (in_array($validateValue, $results)) {
$arrayToJs[1] = 0;
echo json_encode($arrayToJs); // RETURN ARRAY WITH ERROR
} else {
$arrayToJs[1] = 1; // RETURN TRUE
echo json_encode($arrayToJs); // RETURN ARRAY WITH success
}
I was able to change ajax url for ajaxusercallphp, ajaxnamecallphp without modifying the languge file... You need to search for this line inside jaquery.validateEngine.js
Find : _ajax:function(field,rules,I,options)
Then scroll down to the ajax request .ie $.ajax
And change url:rule.url to options.ajaxCallPhpUrl
Then all you have to do is include the url as an option like this:
JQuery("#formid").validateEngine('attach', {ajaCallPhpUrl : "yoururl goes here", onValidationComplete:function(form,status){
})
I was able to change ajax url for ajaxusercallphp, ajaxnamecallphp without modifying the languge file... You need to search for this line inside jaquery.validateEngine.js
Find : _ajax:function(field,rules,I,options)
Then scroll down to the ajax request .ie $.ajax
And change url:rule.url to options.ajaxCallPhpUrl
Then all you have to do is include the url as an option like this:
JQuery("#formid").validateEngine('attach', {ajaCallPhpUrl : "yoururl goes here", onValidationComplete:function(form,status){
})

Sending Email from Flash / Actionscript 2.0

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

Categories