Codeigniter: Submit parameters to controller, need correct URI - php

I have a form with 4 dropdowns and a submit button. When a user clicks the submit button I want to go to my controller handling the input/output giving the users choices, but with a correct URI.
The dropdowns are dynamically generated from Ajax depending on the users choices, bar the first dropdown. They are working absolutely fine.
The method handling the user input is located in this controller: /app/controllers/shop/kategorier, index method looks like this:
public function index($fabrikat, $type, $model, $produktnr = '0')
{
// get all the data from the model
$data['all'] = $this->fetch->get_kategorier($fabrikat, $type, $model, $produktnr);
print_r($data['all']);
}
My goal is this: When users hit the submit button, I wan't them to view the page with that exact URL including the parameters, eg. http://app.com/shop/kategorier/index/LG/WASH/FL9834X/0/ That's all I really want.
Note: Accessing this URL manually works fine, and the controller/model handles the parameters as they should.
How do I accomplish this? I tried two things, they both failed. Sort of.
I tried with jQuery, and generated a encodedURL string with all the
parameters with a '/' delimiter, and changed the .attr('href') on
submit. But that was a nightmare, since some of the $model's can be
eg. 'CE1000C-T / XEE' etc.
I tried to make a 'proxy' method in the Kategorier
controller taking all the input->posts and appending them to a
redirect('kategorier/'.$fabrikat.'/'.$etc), but that was rather
stupid.
I would rather not use query strings like /kategorier?fabrikat=LG&type=WASH etc
My form looks like this:
<?php echo form_open('shop/kategorier/'); ?>
<select id="fabrikat" name="fabrikat">
<option name="0">Vælg Fabrikat</option>
<?php foreach ($fabrikater as $f) : ?>
<option value="<?php echo $f->Fabrikat; ?>" name="<?php echo $f->Fabrikat; ?>"><?php echo $f->Fabrikat; ?></option>
<?php endforeach; ?>
</select>
<select id="type" name="type">
</select>
<select id="model" name="model">
</select>
<div id="produktnummer-wrap" style="display:none">
<select id="produktnummer" name="produktnummer">
<option name="0" value="">Vælg Produktnummer</option>
</select>
</div>
<?php echo form_submit('findparts', 'Find Reservedele'); ?>
<?php echo form_close(); ?>
I believe I'm somehow overcomplicating things, but right now I can't think straight. I will be more than happy to elaborate anything.
I really hope someone is able to help me out, thanks in advance.

You can't really achieve this without using some JavaScript:
<script type="text/javascript">
function update_selections()
{
var base_url = '<?php echo site_url('shop/kategorier/index'); ?>/' + $('#fabrikat').val() + '/' + $('#type').val() + '/' + $('#model').val();
if( $('#produktnummer').val() != "" )
{
base_url = base_url + '/' + $('#produktnummer').val();
}
document.location.href = base_url;
}
</script>
Remove the current form and use an onclick event to trigger this.

#Repox I did figure out an approach last night which was actually pretty similar to your solution. Here's what I did:
$("#find-btn").on("click", function() {
var fab = $("select#fabrikat").val();
var type = $("select#type").val();
var model = $("select#model").val();
var produktnummer = $("select#produktnummer").val();
// we have to replace spaces in models and types
model = model.replace(/\s+/g, '-');
type = type.replace(/\s+/g, '-');
// produktnummer can be empty
produktnummer = (produktnummer === '') ? "0" : produktnummer;
// we also have to URI encode the model and prodnr since it
// can be horror strings like 'xy762 / ø23'
model = encodeURIComponent(model);
produktnummer = encodeURIComponent(produktnummer);
// our url string to update the href
var url = fab + '/' + type + '/' + model + '/' + produktnummer;
// update the href with the specific parameters
$(this).attr("href", "http://app.dev/kategorier/index/"+url);
});
Although I need to be very wary when handling the parameters in my controllers and models, they need to be encoded and decoded correctly afterwards. A slight portion of the model strings could be something like:
'EX+ 340-34 / Ø14' OR '77773+ -/ 23IK'
Which isn't ideal with the decoding in my controller using str_replace('-', ' ', $str); I therefore need to examine lots of the data before choosing a replacement character.
However, this is probably the best solution if one wishes to do this without having to use query strings in Codeigniter.

Related

One POST index shows up true, another undefined, yet both have been implemented (what seems to be) the same way

I have this problem I've been working on and can't seem to figure out. At the end of the day I would like to pass some values to a php script from a user form. I am working with files that were written a long time ago and have tried to treat the variable I am trying to pass the same way the original author tried to treat his own. Yet, despite trying to keep the approach the same, I am getting different results. Specifically, in the php script where I want to pass these variables, when I echo the value of $_POST['whole'] I get true or false, yet when I echo the value of $_POST['plotX'] I get a variable undefined error.
I apologize for the large amount of code, but I hope that if you search for terms queryDataCenterOfMass and plotX you will see what I am referring to.
The HTML portion comes out as follows. This is where the user selects true or false for 'whole' and true or false for 'plotX'. This is actually code from the webpage, php is used to generate this code, but I thought it would be simpler to paste the HTML.
<div id="wholeDiv" class="dynamicDiv">
<b>Whole</b>
<br>
<select id="whole" name="whole" class="atomTypeSelect">
<option value="">>>Select<<</option>
<option value="true">Yes</option>
<option value="false" selected="">No</option>
</select>
</div>
<div id="plotXDiv" class="dynamicDiv">
<b>Plot x dimension</b>
<br>
<select id="plotX" name="plotX" class="atomTypeSelect">
<option value="">>>Select<<</option>
<option value="true">Yes</option>
<option value="false" selected="">No</option>
</select>
</div>
The next part is the code that creates the submit button. The important part is, I belive, the onclick portion, which calls the function queryDataCenterofMass, which is given in a separate javascript file and I pasted below this.
<input type="hidden" name="table" value= <?php echo $_GET['schema'] ?>/>
<input type="hidden" name="queryName"
value= <?php echo $result[0]['query_id'] ?>/>
<input type='Submit' value=' Query Data' name='funcSearch'
onclick="queryDataCenterofMass(('<?php echo $result[0]['query_id'] ?>'),('<?php echo $_GET['schema'] ?>'),($('#firstFrame').val()) ,($('#lastFrame').val()) ,($('#skip').val()) , ($('#minX').val()) , ($('#minY').val()) ,
($('#minZ').val()), ($('#maxX').val()), ($('#maxY').val()), ($('#maxZ').val()), ($('#whole').val()), ($('#whole_pcb').val()), ($('#molName').val()),($('#atomTypeDll').val()), ($('#atomID').val()), ($('#molID').val()) ), ($('#plotX').val()), ($('#plotY').val()), ($('#plotZ').val()); false;"
class='dynamicParamButton'><br/><br/>
Here is the definition of queryDataCenterofMass. It seems to use a jQuery function to pass everything via post to comfunction.php.
function queryDataCenterofMass(queryId, schema, firstFrame, lastFrame, frameSkip, minX, minY, minZ, maxX, maxY, maxZ, whole, wholePcb, molName, atomType, atomID, molID, plotX, plotY, plotZ) {
$("#waiting").show(500);
$("#interface").hide(0);
// generate a random number to pass to function.php and append to the end of our gnuplot files to make them unique
var random_num = Math.floor((Math.random() * 1000000) + 1);
$.post('./function_files/comfunction.php',
{
random_num: random_num,
query_id: queryId,
simschema: schema,
firstFrame: firstFrame,
lastFrame: lastFrame,
frameSkip: frameSkip,
minX: minX,
minY: minY,
minZ: minZ,
maxX: maxX,
maxY: maxY,
maxZ: maxZ,
whole: whole,
whole_pcb: wholePcb,
molName: molName,
atomType: atomType,
atomID: atomID,
molID: molID,
plotX: plotX,
plotY: plotY,
plotZ: plotZ
},
function (data) {
$("#waiting").hide(0);
$("#results").show(500);
var img = document.getElementById("com_img");
img.src = "../queries/gnuplot_tmp_files/gnuplot_output" + random_num;
$('div#message').html(data).fadeIn({duration: 700});
$('html,body').animate({
scrollTop: $('div#message').offset().top
});
});
}
So that's it. I am not sure why in comfunction.php the variable $_POST['plotX'] is undefined yet other variables, including $_POST['whole'] are not. Solving this problem is very important to me... if there is some way I can better ask this question, or more information I can provide, please don't hesitate to let me know. Thanks.
The onclick line
($('#molID').val()) ),
Seems to have an extra bracket here. Which makes the onclick callback end early, before the plotX and other elements could be sent.
Protip/s:
- Bad idea to load mix such javascript eventhandlers inside HTML
- I simply loaded the html in a IDE which showed the syntax error (among others)
- use browser developer tools.

PHP - get data from select box without the value

I'm having a bit of a confusing question but hopefully you'll get what I mean:
In my website I'm trying to implement a select box which is updated based on the value from a previous select box. For that I'm using a javascript that takes the values. For example an option from the select box looks like this:
<option value="22"> Apple </option>
I need the value in order to filter the select boxes but in my PHP script I need to get that 'Apple' text. Is there a way to do that?
Sorry for the noob question but web development is new for me.
Edit:
This is the java script I'm using for filtering the second select box:
$("#select1").change(function() {
if ($(this).data('options') == undefined) {
/*Taking an array of all options-2 and kind of embedding it on the select1*/
$(this).data('options', $('#select2 option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#select2').html(options);
});
If I try to change this 'value' in the filter function to some other attribute it doesn't work for some reason. I don't know JavaScript at all.
Try this
var pName = document.getElementById('selectname');
var name = pName.options[pName.selectedIndex].text;
Send the name value to your php script by hidden form field or ajax request,
It will contain the text of the option
try this
function getSelectedText(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1)
return null;
return elt.options[elt.selectedIndex].text;
}
var text = getSelectedText('test');
or
this.options[this.selectedIndex].innerHTML
fruits_array.php
<?php
$fruits= array(
22 => 'apple' ,
23 => 'orange'
);
form_handler.php
if( isset($_POST['chosen_fruit']) && (int)$_POST['chosen_fruit'] > 0 ){
include 'fruits_array.php';
echo you chose ' . $fruits[$_POST['chosen_fruit'];
}
pick_your_fruit.php
<form action='form_handler.php' method= POST>
<select name='chosen_fruit'>
<?php
include 'fruits_array.php';
foreach($fruits as $key=$fruit)
echo '<option value=' . $key . '>' . $fruit .'</option>' . PHP_EOL ;
?>
<input type=submit />
</form>
Give this a try. Maintain an array of fruit in one place. Include it where you need it. If necessary that array could be from a database.
Use the array to
generate the form elements
generate the message
But, essentially, transferring the number of the key between the form and the form handler eases the thorny question of validating the incoming data.
DRY. Dont Repeat Yourself. Now if you have 99 fruit, and you add another, you only add it in one place.
(the main thing missing is the handling of a fruit number which does not exist, which probably means someone is tampering with you input form, leave that for another question, eh?)
Try like this
<form method="post" action="getvalue.php">
<select name="fruit">
<option value="">select the option</option>
<option value="1">Apple</option>
<option value="2">Banana</option>
<option value="3">Mango</option>
</select>
</form>
<?php
$option = array('1'=>'Apple','2'=>'Banana','3'=>'Mango');
echo $option[$_POST['fruit']];
?>
The Apple is not passed to the server, only your value, in this case 23. You can see that when you change your formular method to GET, it will look like script.php?some_select=23.
Two solutions to solve it:
The first one (the easy one) would be:
<option value="Apple" data-filterid="22"> Apple </option>
And in your js:
var options = $(this).data('options').filter('[data-filterid=' + id + ']');
So you get Apple in your php script instead of 22. You could then filter it in javascript by accessing data-filterid instead of value.
The second solution would be to store an associative dictionary which maps the value to the number, e.g.:
<?php
$mapped = array(22 => "Apple", 23=>"Orange");
$value = $mapped[$_GET['option_name']];

pass the value inside php while loop to javascript using button onclick

I have a huge form and in part of the form I want to insert some value to database using js. I might not be clear about how to present the question but here my needs are:
suppose, I have two tables in database table1, table2. In a html form:
<select name="tab1" id="tab1">
<?php while($row = fetch from table 1){ ?>
<option value"<?=$row['name']?>" name="option1"><?=$row['name']?></option>
<?php } ?>
</select>
<input type="file" name="file">
<input type="button" name="button" onclick="submit_form(true,'');">
Now, I want to pass the $row['name'] value to submit_form() function in javascript. The javascript code will check the value and return it to the form to submit it. My question is since the $row['name'] from table1 is inside the while loop, I cannot pass the value to javascript. If the form was small I could have done using submit button and check $_POST('submit') type. I want to insert the $row['name'] in this form to table2 as file name associated with the name.
As i understand you want to pass selected value from form to submit_form() function?
function submit_form(param1, param2){
var passedValue = document.getElementById('tab1').value;
// here is your old submit_form() function. passedValue contains
// your selected $row['name']
}
#Jhilke Dai, First of all your php code is little buggy, '=' sign must be in html not in php the correct code is
<select name="tab1" id="tab1">
<?php while($row = fetch from table 1) { ?>
<option value="<? echo $row['name'] ?>" name="option1"><? echo $row['name'] ?></option>
<?php } ?>
</select>
<input type="file" name="file"> <input type="button" name="button" onclick="submit_form(true,'')">
You can use generic functions or even jQuery itenerations, to fetch form values
See the similar question answer : Get selected value/text from Select on change
function getDomValueByID( id ) {
return document.getElementById(id).value;
}
function submit_form( a, b ) {
var formValue = getDomValueByID( 'tab1' );
//OR
var jQueryFormValue = jQuery( "#tab1" ).val();
//Do what u want here.
}
In fact several consider it a very bad idea to pass the option data over via javaScript, if its already generated on page for the following reasons
Duplicate data, wasted bandwith.
Less portable code, non-OOP.
Harder to maintain, changes in your php code, requires changes in your javaScript code.
Also if you are really interested (this practice is sometimes frowned on). You can use the following as PHP code somewhere in the header. To pass PHP variables to JavaScript. However there are lots of better ways to do this, from JSONS to XML.
<?php optList = ['one', 'two', 'three']; ?>
<script type="text/javascript">
//Window represents the global variable space, and doing this is really bad practice as listed above.
window.optionList = [ <?php echo( implode(' , ', optList) );?> ];
</script>

In joomla, how do I use a form to return dynamic content in an article via ajax

I want to output the results of an ajax form that resides in a module into the article that is currently on display. Below is a screenshot of what I'd like to accomplish. I'd like to modify the mysql query that is in the article via the form input from the module(in sidebarA) via ajax.
Here is some truncated form code from the module via jumi:
<form action="http://fsdsonline.com/menumanager/index.php/menustab/all-meals/77-component-menus/124-alcohol-n" method="post">
<option value="AND plate = '1'">Plate FSDS only</option>
<option value="AND plate = '1'">Prep FSDS only</option>
<option value="">Plate and Prep FSDS</option>
</select><br /><select style="font-size: 12px;" name="menu">
<option value="">All Meals</option>
<input style="font-size: 12px;" onclick="location=document.menuselector.menu.options[document.menuselector.menu.selectedIndex].value;" type="button" value="Show" /></form>
<div class="success" style="display: none;">View your menu</div>
And here is the php code that is in the article via jumi.
mysql_connect($hostname,$username, $password) OR DIE ('Unable to
connect to database! Please try again later.');
mysql_select_db($dbname);
$plateprep = $_POST['plateprep'];
$meal = $_POST['meal'];
$pub = $_POST['pub'];
$avocado = $_POST['avocado'];
$alcohol = $_POST['alcohol'];
$result = mysql_query("SELECT catnum, ctgry, Shrt_Desc, `desc`, ROUND(`Energ_Kcal`*`yield`*`qty` ) AS `cal` FROM allinnot a
LEFT JOIN allinfsds b
ON a.`NDB_No2` = b.id1
LEFT JOIN fdcat h ON b.product_type = h.unik
LEFT JOIN allinnot2 g ON a.`NDB_No2` = g.NDB_No
LEFT JOIN allincomp j ON a.`NDB_No2` = j.fsds_num
WHERE `own_id` = $user->id $plateprep $pub $meal $avocado $alcohol
ORDER BY `catnum`, `order`");
$cat = null;
$first = true;
while ($row = mysql_fetch_array($result)) {
if ($row['catnum'] != $cat) {
if (!$first) {
echo '</table>'; // close the table if we're NOT the first row being output.
}
$first = false; // no longer the first table, so disable this check.
echo '<p style="line-height: 12pt; font-size: 12pt;"><strong>' . $row['ctgry'] . '</strong></p>';
echo '<table>'; // start new table
$cat = $row['catnum'];
}
echo "<tr><td>" . $row['Shrt_Desc'] . "</td><td> " . $row['desc'] . " " . $row['cal'] . " cal</td></tr>";
}
?>
</table>
</body>
</html>
I think that I've coded my query correctly, and the form looks nice, but how do I connect the two via ajax??
Thanks!!
I'm afraid that I'm not familiar with jumi.
Normally to do an ajax request your javascript file will make an ajax request to a specific php file. You will need to trigger this in your form somehow if you are going to use ajax. The php file should echo the information that you want, back to the file that made the ajax request.
In this case, I think that the ajax request will have to go to the page that you have jumi embedded in, but I'm not sure.
If you are going to use ajax then I recommend using jquery to do it. It makes life a lot easier. Here is an example of a simple ajax request made using jquery.
$.ajax({
type: "POST",
url: "joomla_page.php",
data: { 'menu': menu },
success: function(){
informationfromphp= data.menu; //This is $menu echod from php
$('#menuid').html('<span class="food_results">Success!</span>');
}
})
In your php code, capture the ajax message with something like this
if (isset($_GET['menu'])) {
//do something ;
}
Then do something in the php (such as make a call to the DB). Afterwards you can return the information from the php to the ajax file using an echo.
echo $menu;
Please note that this is not a working example, it is just a rough idea to get your started. You will find plenty of other examples on stackoverflow.
Using jumi with joomla will give you path problems :
In your php code, ( server side ), you will have for all include and require to :
_use absolute path , using $_SERVER['DOCUMENT_ROOT'] .
_Or redefine the path for jumi tu use your includes ( not tested, seems to me macGiver fixing, as using jumi anyway...).
Actualy, there is another problem , client side, caused by joomla choices :
The html BASE is defined by joomla on every pages, by default, and the base is the human readable url ... so for your url in the html and javascript, be aware of relative uri ...
You will be ok with absolute uri.
So, in your case, with ajax , client side, you have to precise the target with an absolute url , and in your php, to give absolute path for all ressources used that are in other files.
Managed to make work a jquery autocompletion on joomla over jumi with that.
Note that joomla uses mootools, and that you can only include jquery late on the page ( all you do in jumi will be in the body) . And sometimes, jquery and mootols don't go well together : similar use of the $ . Sometimes you'll have to use the jquery.noConflict.
I will advice to use only one kind of javascript framework , but, sometimes, you have to manage with old choices...

header('Location: ) in php switch to execute url with onclick function

To put it simply I have this variable which carries a hyperlink:
$test3 = 'Move to Quotes';
and what I need is to execute this variable inside a switch case like below:
switch ($_POST['dropdown']) {
case "Select Folder":
echo "Please select";
break;
case "One":
exec($test3); <-- //here i want to run (if this is not execute, my misunderstanding) the link.
break;
case "Two":
header('Location: http://www.facebook.com/'); <-- //this is just a test
break;
default:
echo "<br></br>";
echo "Move multiple files:";
echo "<br></br>";
}
?>
<form method="post" name="theform" action="">
<select name="dropdown">
<option value="Move to Folder">Select</option>
<option value="One">One</option>
<option value="Two">Two</option>
</select>
<input type="submit" value="Move"/>
</form>
I'd like know how to execute the ahref link without the user clicking it, but simply set this link as a case and when the user submits the form, the selected case actions the hyperlink.
Any help appreciated.
MORE DETAIL
I understand that javascript and php are both seperate languages and that a better option would be to use Ajax, but my understanding of Ajax is limited.
To explain it better, this is what's going on in its entirety:
1) I have a mailbox with a selection of messages.
2) You are able to check these messages and then click a link "Trash Selected" which deletes the selected messages. This the link:
Trash Selected
The javascript function actions the php function in $muldel for all selected messages and updates the database.
This is the javascript function in question:
function inboxDelete(url) {
document.messages.action = url;
document.messages.submit();
}
archiveMove() is exactly the same, just duplicated temporarily to make things clear.
3) I have now re-used the ahref code to do the same procedure, but this time, for moving the selected messages into folders.
4) These folders can be selected from a drop down box - this is where the form comes in.
5) So although I can get it to work by adding a link like such:
$test3 = 'Move to Quotes';
echo $test3;
6) I now need this to work the same way but the link being changed, depending on which folder is selected.
That's the full extent to my problem, I hope this is more clear.
I am aware you can send variables into javscript using GET or POST and then carry out the function entirely through javascript. I have tried something like below, but to no avail:
<form method=post name="myform" action="<?php echo $PHP_SELF;?>">
<input type="hidden" name="formVar" value="">
<input type="text" value="Enter Text Here" name="myText">
<input type="text" value="Enter Text Here" name="myText2">
<input type="submit" value="Send form!" onClick="readmove()">
</form>
<?php
// Retrieve the hidden form variable (using PHP).
$myvar = $_POST['formVar'];
if ($myvar == "$mulmov"){
echo $mulmov;
}
?>
<script language="JavaScript">
<!--
function setText(){
document.myform.myText.value = document.myform.myText.value.toUpperCase();
}
function readmove(){
document.myform.myText.value = "<?php echo $myvar; ?>" ;
readmove2();
}
function readmove2(){
if (document.myform.myText.value == "$mulmov"){
document.myform.myText2.value = "<?php echo $mulmov; ?>" ;
<?php exec ('archiveMove(\''.$mulmov.'\'); return false;'); ?>
} else if (document.myform.myText.value == "$mulmov2"){
document.myform.myText2.value = "<?php echo $mulmov2; ?>" ;
}
}
</script>
First of all, you can't execute JavaScript from within PHP like this. At this point, the control has already moved to the server and JavaScript is run on the client-side.
Second of all Im assuming you dont want to just follow the link, you want to run the link's onClick event, since the href is just a hashtag. So you are trying to run a JavaScript function with PHP. You cant call a function in one language from a function in another language.
Its hard to tell what exactly you are trying to do, but if you want to run a function when a user selects a certain dropdown, write a php function that does what archiveMove() does. If you want this to happen without a page refresh, you can stop the submit process and call your archiveMove() function with javaScript and Ajax.
If elaborate on what exactly you are trying to do, maybe we can help more.
Ok, so the only difference between your working code and the not working code is that you want to dictate the submitted URL based on what is selected in the dropdown?
So you can use JavaScript to set the form action when the dropdown is selected.
BUT, It might be a better idea to submit the form with the same action everytime, and then use PHP to decide what to do. It seems like this is where you were headed initially. Just get the folder id in the switch statement and call a function to make your edits:
The PHP can be similar to the way you had it:
switch ($_POST['dropdown']) {
case "Two":
// set folder id
$folder_id = 2;
break;
}
moveMessages($_POST['Messages'], $folder_id);
function that moves the messages where they need to go.
function moveMessages($messages, $folder_id){
// depending on your form setup
foreach($data as $id => $value ){
if($value){
// code to move to folder
}
}
return true;
}
If there are other factors involved, let me know.
You can write JavaScript code that request a url using window.location.href in click hadler.
window.location.href="http://example.com";
Ok this was my solution but thank you also for your solution Jeff Ryan, this worked also.
<script language="javascript">
function buttons(str)
{
document.getElementById("txtHint").innerHTML = str;
if (document.f1.users.options[1].selected){
document.getElementById("txtHint").innerHTML ="<?php echo $mulmov; ?>";
document.messages.action = document.getElementById("txtHint").innerHTML;
}
else if (document.f1.users.options[2].selected){
document.getElementById("txtHint").innerHTML ="<?php echo $mulmov2; ?>";
document.messages.action = document.getElementById("txtHint").innerHTML;
}
}
function submit_mes(str)
{
document.messages.submit();
}
</script>
<form name="f1">
<select name="users" onChange="buttons(this.value)">
<option value="">Select a folder:</option>
<option value="Quotes">Quotes</option>
<option value="Projects">Projects</option>
<input type="button" value="Move" onClick="submit_mes(this.value)">
</select>
</form>
<div id="txtHint"><b>Folder will be listed here.</b></div>

Categories