Welcome Guest, Not a member yet? Register   Sign In
passing variable from javascript to a controller via link
#1

[eluser]agubski[/eluser]
Hi Everyone,

I wonder if somone can share the knowledge. I need to pass a variable from Javascript to a controller via link. I was thinking along the lines of hidden inputs, but not sure if this can work. It should be possible to send the data in URL request i.e. <a > ...

Thanks

Alex
#2

[eluser]jdfwarrior[/eluser]
Since URL's for CI are in the form of..

http://www.example.com/controller/method/arg1/arg2/etc/

Yes you can pass a variable. Just make your variable the next part of the URI after the controller and method(function)
#3

[eluser]agubski[/eluser]
thanks for your post. I wonder if there is a less transparent way to send variables
#4

[eluser]TheFuzzy0ne[/eluser]
What do you mean by "less transparent"?
#5

[eluser]kgill[/eluser]
If you want to submit it via a link then what jdfwarrior said is the right way, if you want it less transparent don't use a link, submit the form via post.
#6

[eluser]agubski[/eluser]
As I understand Post method will require submission button. I'd like to try to avoid new buttons as they don't align well with overall site design. I wonder if I could still use link, but send variable without exposing it in URL.
#7

[eluser]Mushex Antaranian[/eluser]
I you're using js frameworks, it's pretty simple (and with pure js it's not so hard Wink )

In your markup
Code:
&lt;form id="the-form"&gt;
<label for="input">Input</label>&lt;input type="text" value="" name="input"/&gt;
<label for="input-2">Second Input</label>&lt;input type="text" value="" name="input-2"/&gt;
&lt;/form&gt;
<a href="#" id="submit-the-form">Submit Form</a>

In js (!this is jQuery code)
Code:
$sumbitLink = $('#submit-the-form')
$submitLink.click(function(){
    $.ajax({
               url: 'url/to/post/',
               type: 'POST',
               // how you'll receive data controller outputs (can set as html, xml, json)
               dataType: 'json',
               data: $('#the-form').serialize(),
               success: function(data){
                            //do something with response
                        }
    }) // close $.ajax
}) //close .click
#8

[eluser]Mushex Antaranian[/eluser]
Ooh, sorry, I get you wrong..
You can just style your submit button as link with css, if it is the problem Smile
#9

[eluser]agubski[/eluser]
Thanks a lot. Will try and let you know




Theme © iAndrew 2016 - Forum software by © MyBB