My current base for a simple contact form is:
A page containing the form and the form validation in the php section with a native function like so:
function onStart(){if(Request::isMethod('post')) /* do stuff */}
Above is my "no-script" solution.
Now, when I want to enable OctoberCMS' Javascript API I have to call a self defined function in the php section, for example:
function onSubmit(){/* do stuff */}
How could I combine both in one function so that /* do stuff */ triggers, regardless if the request was send via Ajax or pure php?
I found the answer.
OctoberCMS provides a native method to let a form trigger a custom onMyfunction(), just by using another way of implementing the form.
For anybody who might get into the same problem, here's the code:
<?php
function onMyfunction(){}
?>
==
<html>
{{ form_open({ request: 'onMyfunction', id: 'my-form' }) }}
</html>
This will send the post data to the php handler, regardless if Javascript is enabled or not.
Now you only need to initiate your Ajax API with:
<script>
$('#my-form').submit(function(evt){
evt.preventDefault();
$(this).request('onMyfunction',{})
});
</script>
Could you use the html <noscript> tag?? In your css you would put .noscript {display:none;} .script {display:block;} then in your pages, component template, layout etc you could have two forms that change depending on if the user is using script or not. They can use the same onSubmit function.
Any user interaction with any of the sites I have made assume some might not use Javascript so I default to use standard forms and not js or ajax.
Related
I am currently building a program using Symfony2 framework and also taking advantage of the many nice new features that come with the platform such as Doctrine, Twig etc.
One of my pages requires me to load a big load of data via AJAX after pageload is complete. This is easily achieved uing JQuery/Ajax but i'd like to think that something like this would have a way of injecting ajax directly into the Twig template maybe via JSON and have it populate in a for loop.
<table>
<tr><td>header</td></tr>
{% for row in rows %}
<tr><td>{{row.data}}</td></tr>
{%endfor%}
</table>
Something like this crude example.
I did browse the docs quickly for this but there search is down and i couldn't find anything directly. A link to documentation could suffice if its what im looking for.
I think the cleanest way would be to generate your Json in the controller.
Something around:
/**
* #route("/json", name="json_generator")
*/
public function jsonAction() {
// do your for loop and build up a $jsonArray
return new Response( json_encode($jsonArray) );
}
And then test the response of this in the browser and load this with Javascript in the twig template.
Don't have the specific code right now, but from the top of my head:
$(document).ready(function() {
$.ajax({
ajax: true,
url: "{{ path('/json') }}"
});
};
Just so you get the idea. Hopefully it serves you as a base example-
There is 2 ways:
1. Make AJAX request, in controller render html and return it to the script. Then add when it is needed.
2. Make AJAX request, return JSON and build html in the script, then add ready html to your specific place.
I think better way is render html in your action and return it to your AJAX script
Just getting into Codeigniter and I'm planning out a large application. I'm a bit confused about how CI handles JS files and AJAX requests.
I am using mod_rewrite with my project.
In a regular webpage, I'd reference separate JS scripts at the header of my doc to keep my code segregated and clean. Since I'm using mod_rewrite, I need functions from the url helper to find my files. This is a problem in separate js docs because they don't execute php. So when it comes to AJAX calls, how am I supposed to reference a PHP controller function from my JS file when I don't have use of the site_url() function?
How would I go about writing functions that can be accessed through AJAX but not through the address bar? So, let's say I have a User Controller. You can go to user/pictures and you can see their pictures. You go to user/friends and you can see their friends. But I don't want you to be able to go to User/getData and see all the printed out raw data.
tl;dr What is standard JS and AJAX practice when using separate docs and mod_rewrite?
Cheers guys.
What I personally do is declare a js variable in the header section of my template before any js declaration like this:
var base_url = <?=base_url()?>
This base_url will then be accessible by any js file you integrate. About the second point you can always redirect the user from your controller like this:
public function some_function(){
if($this->input->post(null)){
//your ajax code here
}else{
redirect(base_url(), 'refresh')
}
}
I also declare a js variable in the <head> like
var baseUrl = '<?php print(base_url()); ?>';
Then when you do your AJAX call you can call the controller like
baseUrl + 'controller/method'
In terms of making sure that methods can only be called from AJAX calls and not through the address bar one option is to send a post value and check for this before you do anything like
if($this->input->post('ajax_call'))
{
//Do something
}
If you put all your ajax methods into the same controller you'd only have to have this check once in the __construct()
I'm a super beginner in php, and I'm using a MVC php framework called Yii. I can't seem to find any articles that explain how to get values of html elements with PHP. Everywhere I look it's all about how to get values from form fields after a POST in some other view. Is there anyway to get field values and send them to a controller in PHP and just come back to the original view.
In .Net MVC I just use jquery to get form fields and do an ajax call. It's not sensitive data so I'm not worried about security. I like ajax because I don't do any page post back, I just send my data over and remain on the same page I was on.
Is there any way to do MVC AJAX kind of thing with PHP? Read html element values and send them to a controller for data manipulation?
It works the same way. Yii comes bundled with jquery, so you
just use jquery to get form fields and do an ajax call
to some controller function, do whatever you want with it, and return a response, with php's echo.
If you already know some jquery, then the client-side shouldn't be much different from .net mvc.
Edit:
To add a <script> to the generated html see registerScript.
To create urls use the createUrl function.
To add ajax options to html tags code looks similar to:
echo CHtml::checkBox('mybox',false,
array(// array for htmloptions, we also pass ajax options in here
'class'=>'checkBoxes_class',
'ajax'=>array(// this is ajax options for jquery's ajax
'type'=>'POST',
'url'=>Yii::app->createUrl('xyz',array('clickedboxid'=>'mybox')), // here you passed clickedboxid as a get variable
'beforeSend'=>'function(){}',
'success'=>'',
// etc etc
)
)
);
Every html tag generator helper function takes htmlOptions array, where we can also pass ajax options.
While reading these values in the controller:
public function actionSomeAction($id){
// $id is mybox
echo "Hello"; // this is returned as response to the client
}
Hope this is enough for you to get started.
I am working on a Symfony application that works mainly with form submissions and our team needed extreme customisation on validations therefore we chose to not use the forms helper and widgets. Now each form has an action method for submission and retrieval. In between one of those forms I need an auto fill but I don't know how I should send this to a new action method on the keyup event and return data from there. I am completely unable to return the data from there I have checked using Firebug. I have found articles that submit the whole form for a search auto fill. I can't do that because my auto fill field is not the only one on the form. It's a city field which I have to give suggestions on. I am expected to use the jQuery framework. Please help.
Moreover I don't understand the AJAX concept in Symfony very well. It would be really helpful if you could link me to some good articles.
Appreciate all the help.
Thanks a lot.
The main difference of response in Symfony for ajax request is the action wouldn't decorate the view (actionSucces.php) with the Layout (so it won't include the web debug toolbar either).
In your case, you can use the jQuery Autocomplete plugin (http://docs.jquery.com/Plugins/autocomplete) to produce your extreme customisation form :D
you can use slot to define your jQuery object definition in layout
<head>
<?php if (has_slot('head_script')): ?>
<?php include_slot('head_script') ?>
<?php endif ?>
</head>
define your jQuery Autocomplete in the extreme customisation form template
<?php slot('head_script') ?>
<?php echo javascript_tag('$(function{
$("#example").autocomplete("'.url_for('search/cities').'");
});') ?>
<?php echo form_tag('form/result') ?>
<?php echo tag('input', array('name'=>'example','id'=>'example'));
</form>
don't forget to include your jQuery and Autocomplete plugins, when user start typing a request sent to specified backend with a GET parameter q that contains the current value of the input box and a parameter "limit" with the value specified for the max option. (please refer to the doc :D )
now create action search/cities and use $request->getParameter('q') to populate the response
public function executeCities(sfWebRequest $request){
//process the $request->getParameter('q')
return $this->renderText("First Second Third Fourth");
}
cheers and happy new year :D
Sorry for this but I searched the whole web for a solution to my probleme but in vain :(
What I want to achieve is creating a normal Post and adding a form to it that once submitted, goes to a database and gets back a value.
I created a plugin for that and integrated it in the admin menu then set a function that queries the db :
myfunc_getcode($db, $table, $value, $return) // returns a value
how can I achieve this!? I mean, when a user inserts some data in the form (that exists inside a post or page) then he clicks on submit, Ajax talks to the db and gets the results back.
I don't even know if wordpress 3.0.1 allows such things!
I got it to work by using
add_action('the_content', 'my_function');
this hooks my plugin to the posts and pages.
then in the function I transmit the content like;
function my_function($content) {}
Then I used Ajax by integrating jquery inside my script;
<script type="text/javascript">
jQuery(document).ready(function($) {}
for submitting forms I used jquery/ajax to listen to the form
$("#my_form_id").submit(function() {
and used jquery's $.post to pass variables to a php page that handeles my results and returns them by echo.
hope this helps someone!