Welcome Guest, Not a member yet? Register   Sign In
can I call a javascript from within a controller ?
#1

[eluser]vickel[/eluser]
I'm creating a modalwindow with a javascript call. This modalwindow has a form submit button, which when clicked must:
close the modalwindow itself (javascript)
and execute a corresponding PHP form method post action "dosomething.php" (e.g. open a new view which echos "success")

what happens, when using from my view:

Code:
echo form_open('controller/dosomething);
...
$js='onClick="parent.mywindow.hide()"';
echo form_submit('my_submit_ID', 'click me!',$js);

is: the javascript is executed first (window is closed) but the form method post action "dosomething.php" is only executed, once I reopen the modalwindow

that is why I'd like to know if I can call the javascript from the controller :
I could first execute the javascript to close the modalwindow and as I'm allready in the controller "dosomething" anything like (echo "success") would be next...

thanks for any help
#2

[eluser]vitoco[/eluser]
First you must get understand the difference between server side and client side, the two of them only communicates trough HTTP REQUEST ( client to server ) and HTTP RESPONSE ( server to client ).

SERVER :
- controller
- model
- view
that creates an html[+js+css+images] that it's sent to the browser ( client side )

So, the javascript it's only text in the controller/model/view, and it gets executed in the browser when the C/M/V doesn't exist anymore.

You can solve your problem with and ajax call from the javascript and echoing the html ( text) created in the controller.
#3

[eluser]bretticus[/eluser]
To add to vitoco's sentiments. No, you cannot call javascript from PHP code. Get in the habit of putting javascript in the View part of MVC. Javascipt is only ran from the clients browser (thus client-side code) and PHP runs on your server to generate dynamic content for your browser (server-side code.)

Another suggestion: you can (and should) seperate your javascript from your view. IN other words, use something like jquery to "latch on" to your HTML DOM elements instead of having PHP render javascript calls inline. I did a project several years ago (and failed miserably because it was huge and I had all this javascipt mixed into my coding. What a kludge!) I learned the hard way that having your javascript as a separate container of your layout is crucial to keeping your code and functionality easy to debug and update. In fact, the principle of hijax is just so darned appealing that I'm providing link's:

the principle

A good video example. (He doesn't mention hijax but that is what he is doing when he turns javascript off.)

A short written example
#4

[eluser]sandeep nami[/eluser]
@bretticus
thanks for those good tuts.




Theme © iAndrew 2016 - Forum software by © MyBB