how to create search form with into codeigniter uri format? - php

dear all, i'm a noob in codeigniter,
i would like to ask for advise, on how to create a search form that would result to url as:
http://domain/class/index/searchvar1/searcvar1val/searchvar2/searchvar2val
the form would be like
<form action="http://domain/class/index">
<input name="searchvar1" value="searchvar1val">
<input name="searchvar2" value="searchvar2val">
<input type="submit">
</form>
what is the best practice for this?
i've googled around including stackoverflow posts, still can't find any solution.
thanks :)
~thisismyfirstposthere
update ::
i would like to emphasize that my objective is to process search variables from the uri string (above), not from post vars; so i think setting the form search to POST is not an option? :)
update (2)
i don't think this can be done out of the box in codeigniter, i'm thinking of client-processing the form vars/vals into the form action in URI format using jQuery.
will post an update here later when done.

taking a look at the user_guide :
$this->uri->assoc_to_uri()
Takes an associative array as input
and generates a URI string from it.
The array keys will be included in the
string. Example:
$array = array('product' => 'shoes', 'size' => 'large', 'color' => 'red');
$str = $this->uri->assoc_to_uri($array);
// Produces: product/shoes/size/large/color/red
and i think if your form is this:
<form action="http://domain/class/index/search">
<input name="product" value="shoes">
<input name="size" value="large">
<input name="color" value="red">
<input type="submit">
</form>
then somewhere in the search controller do this $this->uri->assoc_to_uri($data); IMHO will produce product/shoes/size/large/color/red

hey guys, thanks for replying and discussing, I think imma go with flow:
View --> form --> jquery, on form submit: replace action attribute with form params --> controller with uri string --> rest of the process
the jquery part would be something like this
$("#searchFormID").submit(function(){
// $(this).serialize() outputs param1=value1&param2=value2 string
// var.replace(regex, string) outputs param1/value1/param2/value2 string
// newact would be http://localhost/class/index/param1/value1/param2/value2
var newact = $(this).attr("action") + "/" + $(this).serialize().replace(/&|=/g,"/");
$(this).attr("action", newact); // or $(this).attr("target", newact);
return true;
});
notes:
add an id attribute to the form -> for the form selector in jquery
use post method in the form (this is default in codeigniter) -> so action url will not be populated with the GET string

You may want to enable query strings and use $_GET. IMO, this is a perfect example what the query string is intended for.
Make sure to change your form to <form method="get" action="http://domain/class/index">
You will then have a query string in your URL like ?searchvar1=value1&searchvar2=value2
You can access parts of the string like this: $this->input->get('searchvar1')
With the method you are currently using, if a user searches for any characters that are not allowed in your $config['permitted_uri_chars'], you will have to do a lot of encoding and decoding yourself to make sure the string is safe/readable in your URL. The CI Input class takes care of this for you, so it is my recommendation.
Another disadvantage to URI segment based search params is that there is no proper way to express an array like ?values[]=one&values[]=two&values[]=three. There are hacks to work around this, but they are all exactly that: hacks. you will eventually run into trouble.
Using $_POST is very tedious and forces the use of form submits for paginated results and links, and also ensures that you cannot link to the search results or use the back button properly.
If you must use this method, simply have the form post to your controller, read the input, and then redirect() to the url that you construct from it. littlechad has the right idea for this method in his answer
// This URL:
http://domain/class/index/searchvar1/searcvar1val/searchvar2/searchvar2val
// With this:
$search = $this->uri->uri_to_assoc();
// Produces this:
array(
'searchvar1' => 'searchvarval1',
'searchvar2' => 'searchvarval2',
);
// And you can use it like this:
$arg1 = $search['searchvar1'];
$arg2 = $search['searchvar2'];
To get TO this url, you can do something like this with your form post (in the controller after post):
$var1 = $this->input->post('searchvar1');
$var2 = $this->input->post('searchvar2');
redirect('searchvar1/'.urlencode($var1).'/searchvar2/'.urlencode($var2));
I'm sure you can see how much more work this is than just using the tried-and-true query string...

Related

Posting JSON with http post and other data to php page

I have a php page and I want to be able to submit a JSON string, and a few other fields back to itself (http post) so I can do some server-side PHP work. Since I'm new to PHP I see a lot of ways of doing this, but some of them aren't working the way I wanted because I wanted to post to the actual page itself so it can do some backend with a lot of session data, page specific data depending where the page came from, etc before moving on. For this reason AJAX is out of the question.
My JSON string is being created in javascript using JSON.stringify off an object array that I have created. Right now I just output my JSON using..
var output = JSON.stringify(objectTable);
console.log(output);
And the JSON is created perfectly no issues there. I have a few input fields on the page as well that I need to be posted back. Up to this point (before I needed to send the JSON) I just been doing..
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" onsubmit="return validateData()" method="post">
<input type="text" id="itemName" value="page1" />
<input type="text" id="itemColor" value="red" />
<input type="submit" value="submit">
</form>
This of course works perfectly fine, but now with the JSON I'm starting to wounder if I should be doing something else? I know I could maybe create an and then when my javascript runs and does the JSON.stringify then just set the input value to the JSON. However these seems kind of "cheap" and doesn't seem to be the best practice to me. I also worry if there are any downfalls to doing this method such as special character issues or anything? Is there a different, more logical, or professional way I should be doing this?
Simple, Works, Totaly okay method
So if the objectTable object needs to be sent to the same PHP script at the same time as the other data in the form, then just create a hidden field in the form and when the user hits submit, set the hidden value to that of the object.
<input id='secretSHhhhhh' type='hidden' value='false'>
Then in JS (I am using some jQuery notation because I am lazy).
$('form').on('submit',function() {
/* ... stuff ... */
$('#secretSHhhhhh').val(JSON.stringify(objectTable));
});
Otherwise if you want to send the json encoded object to a PHP script that is kind of independent of the form, then I recommend using ajax. Once again I am using jQuery because it is easy, especially for ajax. In this case I am using the post subset of ajax, but there are many more options in the jQuery library.
$.post("somePage.php", objectTable,function( stuffThePageReturned ) { // No need to stringify
console.log(stuffThePageReturned);
});
My preferred method
$('form').on('submit',function(e) {
e.preventDefault();
var PostData = {};
PostData.itemName = $('#itemName').val();
PostData.itemColor = $('#itemColor').val();
// === Any extra fills from input elements === //
PostData.objectTable = objectTable;
$.post("somePage.php", PostData,function( stuffThePageReturned ) {
console.log(stuffThePageReturned);
});
});

How to handle form submit button when submit button has no name

I have a search form, and the submit button looks like this:
<input type="submit" name="search_submit" value="Go"/>
I handle this form using the following php:
if (isset($_GET['search_submit'])) {
do blah
}
Works fine. But my url then includes &search_submit=Go. I do not want that to show up.
I know that to fix this, I need to remove the name attribute from my the forms input line.
But then my php no longer works and I'm not sure how to change it to handle the form. I tried changing it to:
if (isset($_GET['submit']))
and
if (isset($_GET['Go']))
But they did not work either. If anyone can help me with an answer, it would be awesome.
You cannot remove the name of the input element, as PHP would not know which value to look for. If you want to completely hide the string after the URL, use the request method POST instead of GET:
<form action='myscript.php' method='POST'>
<input type="submit" name="search_submit" value="Go"/>
</form>
Your PHP will use the following:
$_POST['search_submit']; // Instead of $_GET['search_submit'];
A good answer to when to use GET and POST can be found here.
edit: If you just want to not have the button show up in the URL, but everything else should still be there (according to your comment), you can simply remove both the value and name of the submit button.
Instead of looking for search_submit to be set, you can look for the other values:
if (isset($_GET['username'], $_GET['password'])) {
// Do your stuff here
}
If you don't want to show string in the URL, you can use the POST method. The main difference between GET and POST are listed below as :
GET:
Parameters remain in browser history because they are part of the URL
Can be bookmarked.
GET method should not be used when sending
passwords or other sensitive information.
7607 character maximum
size.
Url example: new.php?category=sport
POST:
Parameters are not saved in browser history.
Can not be bookmarked.
POST method used when sending passwords or other
sensitive information.
8 Mb max size for the POST method.
URL example: new.php
Sample Code :
if (isset($_POST["search_submit"])) {
do blah
}
If the submit button doesn't have a name, then it won't be a successful control and won't appear in the submitted data at all.
Test for the presence of data from some other field in the form instead.

How do I build on a query string?

What I have is that when someone clicks a link on my index it calls index.php?action=signup and that will display a signup form.
How do I then cause the signup form to maintain the action=signup portion of the query string so that when the user clicks "Submit" the new query string is index.php?action=signup&email=user#email.com?
What is the best way to set this up? Should I somehow split the actions into GET and the data into POST?
I am not sure if I am describing this correctly but I want to keep all my functions on the index.php so when I integrate .htaccess everything will be like www.site.com/signup, www.site.com/login and so on.
The best way to do this on a form submission is to change the <form> action to the correct URL and the method to GET, like so:
<form action="index.php?action=signup" method="GET">
Then, hidden in your form, you put something like the following:
<input type="hidden" name="action" value="signup" />
Then your URL will contain the correct parameters when it is submitted.
However, if you need to modify this server side, then you can get all of your query parameters via $_SERVER['QUERY_STRING']. Use parse_str to get an array of values, and use http_build_query to recreate the query string:
Example:
$params = array();
parse_str( $_SERVER['QUERY_STRING'], $params);
$params['email'] = 'user#email.com';
echo http_build_query( $params); // Will output a new query string for your URLs

Accessing text in a field placed by JS, via PHP

In PHP, in a particular CMS I am using a custom field, which works like google suggest.
As in, for each letter I type an SQL query is performed and matching records are displayed. When clicking on a record it fills the field with that record.
I am fairly certain this is all done with JavaScript.
I need to know how I can access the resultant content of that field, with the text placed through JS, before it is submitted so I can explode() it.
The CMS I am using is using mootools, so a solution relying on mootools would be ideal.
(This answer assumes that you have control over the markup of your forms (the form that requires a string "explosion" before submit) and/or you feel comfortable tinkering with whatever plugins you're using.)
first, make sure that you aren't submitting your form using an actual submit button (). We'll need to submit the form using javascript after fiddling with the field's contents.
next, make sure that your input box (the one you're grabbing text from) and your hidden inputs have unique ids. This will make it easier to query the DOM for the data we need.
Inside your form, in place of a "real" submit button, create a form button:
<form action="something.php" name="myform">
<input type="hidden" id="hiddenItem">
// SOME STUFF
<input type="text" id="autocomplete_field" value="whatever"/>
// SOME OTHER STUFF
<input type="button" value="Submit" onclick="processForm(this)"/>
</form>
Then, write a javascript function to process the string and submit the form:
processForm = function(el){
text = $('autocomplete_field').get('value');
// Lets assume the strings separates words (what you're exploding apart) using spaces
// something like 'DOGS CATS BIRDS PETS'
var array = text.split(' ');
// returns ['DOGS','CATS','BIRDS','PETS']
$('hiddenItem').set('value',array[0]);
// #hiddenItem now has the value 'dogs'
//SUBMIT THE FORM
el.getParent('form').submit();
};
Hope this helps!
You could try to use JS to send the field on some event (onkeyup?) to your php script. After it does it's part, store the result as a session variable and you can retrieve that later.
Try using jquery's get function.
Was that your question?

Submitting GET data with no input field?

I've never really thought about this, but it helps with some security of something I'm currently working on. Is it possible to submit GET data without an actual input field, and instead just getting it from the URL?
If so, how would I go about doing this? It kind of makes sense that it should be possible, but at the same time it makes no sense at all.
Perhaps I've been awake too long and need some rest. But I'd like to finish this project a bit more first, so any help you can offer would be appreciated. Thanks
Yes. If you add some query-string to yourl url, you can obtain that in php using $_GET without form submitting.
Going to this URL adress http://yoururl/test.php?foo=bar cause echoing foo (if there will be no foo query string, you'll get warning).
# test.php
echo $_GET['foo'] # => bar
Is this what you mean?
Link
// page.php
echo $_GET['type']; // foobar
This is what I understand of your question:
You have a <form method="get" action="foo.php">-like tag on your page
You have a series of <input type="text" name="bar"/> in your page
You want to pass additional GET parameters that are not based on an input from the form
If so, it is possible, but I hardly see how it could help with security. Input from a client cannot be trusted, so even if you hardcode the GET value, you have to check it serverside against SQL injection, HTML injection/XSS, and whatnot.
You have two ways:
Use a hidden input: <input type="hidden" name="myHiddenGetValue" value="foobar"/>
Add the GET parameter to the form action: <form method="get" action="foo.php?myHardcodedGetValue=foobar">
If what you meant is that you want to have a GET request without a form, you just need to pass all the GET parameters to the href of a link:
Click here!
Yes it's possible. Just append the GET data to the link.
For example:
<a href="main.htm?testGet=1&pageNo=54>Test</a>
You can also use Javascript to build the url.
If you happen to be using jQuery and want to build the GET data dynamically you can do this:
var getParams = { testGet:1, pageNo:54 };
$(".myLink").attr("href", url + "?" + $.param(getParams));

Categories