Joomla post form - joomla

In Joomla, I am trying to post a form created directly in an article via php DirectPHP and save data to database. I don't know why but sometimes it saves the data and sometimes not. It looks like there was some cache or something because if I get the field value displayed it still shows me the first value of the form I filled out at first.
If I make any change to the code (e.g. add one row to echo whatever it works but then again the form displays this last record). Any ideas please (I don't want to use Chronoforms component).
The code in the article:
if($_GET['sent']=="ok")
{
$db = mysqli_connect("localhost", "xxxx", "xxxx", "xxxx") or die("Database not found");
mysqli_query($db, "INSERT INTO subscribe_form VALUES('','".$_GET['email_address']."')");
mysqli_close($db);
$form_sent = 1;
echo "Thank you, your email address was saved.";
}
if($form_sent==0)
{
echo "Enter your email address if you want to get subscribed.";
echo "<form action='index.php' method='get'>";
echo "</br></br>Your email address: <input type='text' name='email_address'/>";
echo "<input type='hidden' name='sent' value='ok'/>";
echo "<input type='hidden' name='option' value='com_content'>";
echo "<input type='hidden' name='Itemid' value='240'>";
echo "<input type='hidden' name='id' value='36'>";
echo "<input type='hidden' name='view' value='article'>";
echo "<input type='submit' name='odeslano' value='SAVE' />";
}
?>

The reason why your code sometimes saves the data and sometimes it doesn't is because if the email contains an escape character then it can (silently) break the query. You should cleanup $_GET['email_address'] before saving it to the database.

Related

Simple Perl and CGI::Ajax form validation

I'm trying to do a real simple setup.
1.Do checks on each field using CGI::Ajax.
2.Validate that all fields have been filled in with simple perl CGI
The thing is, when testing individually, both work, but when combined as seen in the code below I have two issues:
1.In the username and password fields I see CGI=HASH(0x228ed48) etc
2. When I push the submit button and there is an error (a field is empty), it prints an internal server error, I believe this is due to $ajx->build_html( $cgi, \&form($error, $username, $password)); and calling the form function in this manner.
Any ideas?
Thanks in advance.
#!/usr/bin/perl -w
use CGI;
use CGI::Session qw/ -ip-match/;
use CGI::Ajax;
$cgi = new CGI;
#$session = new CGI::Session(undef, $cgi, {Directory=> '/tmp'});
my $ajx = new CGI::Ajax( 'checkuser' => \&checkuser );
#print $ajx->build_html( $cgi, \&form);
if($cgi->param("submit")) {
process(); } else { print $ajx->build_html( $cgi, \&form); }
sub checkuser
{
my $input = shift;
my $out = $input . " is not taken";
return $out;
}
sub form {
my $error = shift;
my $username = shift;
my $password = shift;
my $html = <<HTML;
<html>
<BODY>
<form id='log' action='session.cgi' method='post' accept-charset='UTF-8'>
<input type="hidden" name="submit" value="Submit">
<fieldset>
<legend>Login</legend>
<font color="red">$error</font>
<label for='username' >UserName*:</label>
<input type='text' name='user' id='user' value="$username"
maxlength="50" onchange="checkuser( ['user'], ['resultdiv'] );">
<br><br>
<div id="resultdiv"></div>
<label for='password' >Password*:</label>
<input type='password' name='pd' id='pd' value="$password" maxlength="50" />
<input type='submit' name='Submit' value='Submit' />
</fieldset>
</form>
</body></html>
HTML
return $html;
}
sub process
{
if(validate_form()) {
print $cgi->header;
print <<HTML;
<body>Validated<br></body>
HTML
}
}
sub validate_form
{
my $username = $cgi->param("user");
my $password = $cgi->param("pd");
my $error = "";
$error .= "Please enter your username<br/>" if ( !$username );
$error .= "Please specify your password<br/>" if ( !$password );
if ( $error )
{
$ajx->build_html( $cgi, \&form($error, $username, $password));
return 0;
}
else
{
return 1;
}
}
For development, use CGI::Carp qw/fatalsToBrowser/;. This will allow you to see the actual errors your code is producing, rather than "Internal Server Error".
Update: Also, your code is failing because you are misunderstanding how a callback function works. The callback function is not called by you; it is called by the code you pass it to--in this case the module. So you can't provide parameters, the module does. This won't work:
$ajx->build_html( $cgi, \&form($error, $username, $password));
build_html wants to call the function you pass in internally, with its own parameters.
Here you are not allowing to happen. Instead you are calling form() before you call build_html(), then passing in a scalar reference to the result. This fails later, because build_html tries to use that scalar reference as a subroutine reference.
Solution: you just need to use \&form. You will need another way to fill in the fields.
Also:
Form validation is a very common task. Mature Perl modules are available and are widely used for this (for example, HTML::FormFu and Data::Formvalidator). There are also some related modules that appear to add Javascript validation (HTML::FormFu::ExtJS, JavaScript::DataFormValidator). It is probably worth checking these out before you create your own.
Most modern Perl web development is done using a web framework of some sort. The available frameworks are very powerful and worth using for all but the simplest projects. If your goal is to learn, I recommend starting with a framework as early as possible, because development using a framework is quite different from traditional CGI development, and there is a learning curve. I am quite happy with Catalyst, and there are other options as well, such as Mojolicious and Dancer.

Display textbox when image onclick

I want to display a textbox when user click on an image.
Here is my code :
print "<img src=\"../resources/pictures/pages/edit-button.png\" height=\"18px\" onClick=\"document.getElementById('#$txtboxName').style.display=\"block\">";
print "<input type=\"text\" name=\"$txtboxName\" size=\"20\" title=\"State Permission Here\" style=\"display:none\" />";
My code wont work, any help?
see this link
$('img').on('click',function(){
$('#inputField').show();
});​
Replace with getElementByName
print "<img src=\"../resources/pictures/pages/edit-button.png\" height=\"18px\" onClick=\"document.getElementByName('#$txtboxName').style.display=\"block\">";
print "<input type=\"text\" name=\"$txtboxName\" size=\"20\" title=\"State Permission Here\" style=\"display:none\" />";

codeigniter form helper wiredness

I have some of wiredness going on in some code I am writing. I have a regular form to update a user account. The fields are populated with data from the database. after changing that needs to be changed, I can't submit the form. when I click on the button, it behaves like disabled submit with javascript but I didn't. On the otherhand if I use javascript and stop it from submitting and console log to see if a click is happening, it appears the button is being clicked but just nothing. below is my code in my view for the form.
form_open('members/users/update_curr_user');
$data5 = array('name'=>'username','id'=>'username','value'=>$uservar['username']);
echo 'Username :'.form_input($data5);
$data6 = array('name'=>'email','id'=>'email','value'=>$uservar['email']);
echo 'Email Address :'.form_input($data6);
$phone1 = array('name'=>'phone','id'=>'phone','value'=>$uservar['phone']);
echo 'Your phone number formatted like so: 0802-331-5544'.form_input($phone1);
switch ($uservar['active']):
case 0:
$data7 = array(
'name'=>'status',
'id'=> 'status',
'value' =>'Deactivated'
);
echo 'Status : Active or Deactivated'.form_input($data7);
break;
case 1:
$data8 = array(
'name' =>'status',
'id' =>'status',
'value'=>'active'
);
echo 'Status :Active or Deactivated'.form_input($data8);
break;
endswitch;
$group1 = array('name'=>'group','id'=>'group','value'=>$uservar['group']);
echo 'Group :'.form_dropdown('group',$groups).'<br />';
echo '<br /><br />';
//$data9 = 'id="updateuser"';
//echo form_submit('submit','Update User',$data9);
?>
<input name="submit" id="updateuser" type="submit" value="Update User" />
<?php echo form_close();?>
Because of how unsure I was of what was going on I manually created a button still the same. Other forms on the page are working ok. If it's of any consequence, I am using phil sturgeon's template library, ion_auth and firephp.
You're not actually writing out the form tag. You need to put an echo up there. Do this:
echo form_open('members/users/update_curr_user');
Your submit button should now work.

Ajax request in YouTube API browser-based upload

I'd like to upload a YouTube video using ajax requests. The following script is used to create a form in order to upload a video to YouTube:
function createUploadForm($videoTitle, $videoDescription, $videoCategory, $videoTags, $nextUrl = null)
{
$httpClient = getAuthSubHttpClient();
$youTubeService = new Zend_Gdata_YouTube($httpClient);
$newVideoEntry = new Zend_Gdata_YouTube_VideoEntry();
$newVideoEntry->setVideoTitle($videoTitle);
$newVideoEntry->setVideoDescription($videoDescription);
//make sure first character in category is capitalized
$videoCategory = strtoupper(substr($videoCategory, 0, 1))
. substr($videoCategory, 1);
$newVideoEntry->setVideoCategory($videoCategory);
// convert videoTags from whitespace separated into comma separated
$videoTagsArray = explode(' ', trim($videoTags));
$newVideoEntry->setVideoTags(implode(', ', $videoTagsArray));
$tokenHandlerUrl = 'http://gdata.youtube.com/action/GetUploadToken';
try {
$tokenArray = $youTubeService->getFormUploadToken($newVideoEntry, $tokenHandlerUrl);
if (loggingEnabled()) {
logMessage($httpClient->getLastRequest(), 'request');
logMessage($httpClient->getLastResponse()->getBody(), 'response');
}
} catch (Zend_Gdata_App_HttpException $httpException) {
print 'ERROR ' . $httpException->getMessage()
. ' HTTP details<br /><textarea cols="100" rows="20">'
. $httpException->getRawResponseBody()
. '</textarea><br />'
. '<a href="session_details.php">'
. 'click here to view details of last request</a><br />';
return;
} catch (Zend_Gdata_App_Exception $e) {
print 'ERROR - Could not retrieve token for syndicated upload. '
. $e->getMessage()
. '<br /><a href="session_details.php">'
. 'click here to view details of last request</a><br />';
return;
}
$tokenValue = $tokenArray['token'];
$postUrl = $tokenArray['url'];
// place to redirect user after upload
if (!$nextUrl) {
$nextUrl = $_SESSION['homeUrl'];
}
print <<< END
<br /><form id="ajaxform" action="${postUrl}?nexturl=${nextUrl}"
method="post" enctype="multipart/form-data">
<input name="file" type="file"/>
<input name="token" type="hidden" value="${tokenValue}"/>
<input value="Upload Video File" type="submit" />
</form>
END;
}
At the end, a form is created using action="${postUrl}?nexturl=${nextUrl} which tells to YouTube to redirect the browser after the uploading has been completed. When the user is redirected, to nextUrl, two variables are passed with the URL (the status of the uploaded video and an ID for that video). I don't want a page reload but it seems that nextUrl is mandatory. Furthermore, I want to be able to get that ID for further use.
Is it possible to change the behavior of that automatic redirection and to pass those values in any other way?
Thanks

Codeigniter: How to redirect properly with form validation

I understand how to do it w/ a plain form w/o existing values, but let's say I have a view that I can call via http://domain.com/account/settings. let's say I have two fields, username, password and city, which are all pulled from the DB (except for password of course). So, if a user tries to submit the form and fails validation for whatever reason, where should I "redirect" them to? Right now, I have it showing the same view but the problem is, it pulls the info from the DB again. Should I be creating two different views?
The second view would essentially show the information they tried to enter along w/ the error message.
You do not need two separate views. Check out Form Helper's functions set_value(), set_select(), set_checkbox() and set_radio(). These re-populate form after its submission and validation. So in your case, you should specify the fields this way:
<input type="text"
name="username"
value="<?php echo set_value('username', $user['username']); ?>" />
<input type="text"
name="city"
value="<?php echo set_value('city', $user['city']); ?>" />
By default, the input will have $user['city'] value. But after failed validation it will be re-populated with previously entered values (including incorrect ones).
Just remember that all fields you want to re-populate need to be passed through form_validation library:
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('city', 'City', '');
On the same controller you could have something like this:
if ($this->form_validation->run('create_comment') === TRUE)
{
$this->comments_model->name = $this->input->post('name', TRUE);
$this->comments_model->email = $this->input->post('email', TRUE);
$this->comments_model->website = $this->input->post('website', TRUE);
$this->comments_model->comment = $this->input->post('comment', TRUE);
$this->comments_model->create_comment();
redirect(current_url());
}
$this->load->view('your_view');
That's all there is to it.
The idea is to have it redirect to itself or wherever you want, when the validation returns 'true' so that we kind of refresh the page, hence, update the page.
If the validation returns 'false' then you won't have to do anything.
Redirect to the same form.
And in your view give error information to the visitor.
There are two ways you can do this.
Use this error in your view. This will show validation error info.
echo validation_errors('<p class="error">','</p>');
Or you can use flashdata()
In your controller
...
...
$this->session->set_flashdata('msg', 'All fields are required. or other useful info here. Please try again!');
redirect('yourcontroller');
And in your view, you need to show it.
<?php
if ($this->session->flashdata('msg')){ //change!
echo "<div class='message'>";
echo $this->session->flashdata('msg');
echo "</div>";
}
?>
Had the same problem and discovered that a redirection makes you lose the data that would have been provided by form_error(...) or validation_errors(), except you store such data in a session or in an array being passed into the loaded view.
The point to note is that you should redirect only if the data you want passed around is in session, else you should just load a view. The latter ensures that you have your validation errors intact when you reach the loaded view.
Just load same view if form validation failed
controller
$userData=array(
'username'=NULL,
'password'=NULL
);
#set form validation rules
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
#get all posted data ,this helps you in two ways,
# 1. Get all form data and can be use here server side
# 2. repopulating the form data by passing to view page
$userData=$this->input->post(NULL, TRUE);
#check form validation result
if ($this->form_validation->run() == TRUE) {
//do the operation
redirect(URL);
}else{
$this->load->view($view, $userData);
}
View page
<form method=post action='URL'>
<input type='text' name='username'value='<?php echo $username?>'/>
<?php echo (form_error('username')) ? form_error('username', "<div style='color:red'>", "</div>") : ""; ?>
<input type='text' name='password' value='<?php echo $password?>'/>
<?php echo (form_error('username')) ? form_error('username', "<div style='color:red'>", "</div>") : ""; ?>
<input type='submit' value='submit'/>
</form>
This code display form errors and repopulate the form

Resources