Yii, how to custom submit button in cactiveform - ajax

I am using CJuidialog widget to wrap a view file, and I don't want the default 'save' button because I would like to use a javascript to make an ajax call to the server for data validation, then save it. I tried below:
<?php
if($model->isNewRecord)
echo CHtml::submitButton('Create');
else
echo '<button onClick="javascript: _updatedata('.$model->id.');">Save</button>';
?>
when the save button is clicked. it still will go to the actionUpdate to save the form data, however I have created an action to just save my data.
function updatedata(id)
{
var url = '<?php echo Yii::app()->request->baseUrl ?>' + '/index.php?r=user/profileupdate&id='+id;
......
$.ajax({
url: url,
type: 'POST',
dataType: "html",
data:
{
...
},
success: function(data, textStatus, XMLHttpRequest) {
if (data != null && data == "success")
{
//$('#xccdfgrid').trigger('reloadGrid');
$('#userprofile').dialog('close');
}
else
alert(data);
},
......

If you got your question correct then what you are saying that instead of default button you need something that you can perform Ajax Things rite? if yes then you need to have Ajax Submit Button. Yii gives you liberty to use ajax more easily then you are trying to do. Please see CJuiDialog and AjaxSubmitButton

Related

CakePHP Friendsofcake search ajax results

sorry if I am missing something simple here. I am using CakePHP 3 and the Friendsofcake Search plug-in and trying to load my results with AJAX. I am not sure what to set for the URL - my understanding is the FormHelper url and the AJAX url must match for SecurityComponent. However even with that disabled I cannot get the form to submit. Any help is appreciated. The plugin is working fine otherwise and I can submit other forms using AJAX just fine - I suspect I am missing something here (or it's not possible - I am a beginning programmer)
<?php
$formUrl='//'.$_SERVER['HTTP_HOST'].Router::url(['controller'=>'Treasures','action'=>'frontIndex']);
echo $this->Form->create('Treasure',['id'=>'myForm','url'=>$formUrl]);
echo $this->Form->input('q');
... (Form submit, end, etc.)
?>
<script>
$( "#myForm" ).submit(function( event ) {
event.preventDefault();
$.ajax({
async:true,
data:$(this).serialize(),
dataType:"html",
success:function (data, textStatus) {
$(".ajax-result").html(data);
},
type:"POST",
url:"<?=$formUrl?>"
});
</script>
<div class="ajax-result"></div>
Can someone tell me what I should be setting for the $formUrl? Currently the Controller action I am using this on successfully filters data with the search plugin and I have specialized the view to return AJAX results when requested - but there is obviously something else going on I am missing.
This works if I leave the URL blank and use GET instead of POST - should've thought of that sooner.
echo $this->Form->create('Treasure',['id'=>'myForm']);
...
?>
<script>
$( "#myForm" ).submit(function( event ) {
event.preventDefault();
$.ajax({
async:true,
data:$(this).serialize(),
dataType:"html",
success:function (data, textStatus) {
$(".ajax-result").html(data);
},
type:"GET"
});
</script>
Works as expected. Hope this helps someone!

Yii :My view file does not opens on ajax call

I have a button in my form .i am passing some parameters to another form on button click.
My code is
<?php echo CHtml::link('newForm',"",
array('class'=>'btn btn-success',
'onclick'=>'test()'
));?>
My js code is like this:
<script type="text/javascript">
function test(){
$.ajax({
type: 'POST',
url: '<?php echo $this->createUrl('company/registration'); ?>',
data:{ids:values},
success:function(data){
}
error: function(data) {
alert("Error occured.please try again");
}
});
</script>
My controller code is:
public function actionRegistration()
{
$arrList=array();
$arrList=$_POST;
$model=new Registration;
$this->render('_newRegistration',array('model'=>$model,));
}
Here my view doesnot open.What is problem with my code???
If i understood you correctly, this few things does matter
1.Do you want open another file in modal popup (bootstrap)?
2.And in your controller you should use renderPartial instead of render.
3.and in your ajax success function you should render the data to the modal popup body
so your code in controller something like .
public function actionRegistration()
{
$arrList=array();
$arrList=$_POST;
$model=new Registration;
$this->renderPartial('_newRegistration',array('model'=>$model));
}
and in your ajax success function (if you are using modal popup),then your code something like
$.ajax({
type: 'POST',
url: '<?php echo $this->createUrl('company/registration'); ?>',
data:{ids:values},
success:function(data){
$("#your_modal_popup_id").html(data);//bootstrap modal popup
$("#your_modal_popup_id").modal('show');//bootstrap modal popup
}
error: function(data) {
alert("Error occured.please try again");
}
});
hope this help you

how do basic jquery ajax in typo3 flow?

I am trying to do some very basic ajax. I just want an onchange event on a select that will call an ajax function that will get the options for another select and fill it in. However I am not sure how to do this in a simple way in Typo3 Flow. My php code for the action just looks like this:
public function getProductsByCategoryAction( $category='' ) {
$postArguments = $this->request->getArguments();
echo __LINE__;
TYPO3\Flow\var_dump($postArguments); die;
}
and my ajax call looks like this:
jQuery('#get_category').change(function(event) {
event.preventDefault();
alert('get products');
var category = jQuery('#get_category').val();
alert(category);
jQuery.ajax({
url: "/admin/orders/getproductsbycategory.html",
data: {
'category': category
},
async: true,
dataType: 'html',
success: function(data) {
alert('hi mom');
...
}
});
});
when I try this url in the browser mysite-dot-com/admin/orders/getproductsbycategory.html?category=17ca6f3e-a9af-da7d-75cd-20f8d6a05ed0
on the page the var_dump just gives me array(empty). Why doesn't the request->getArguments() call work and give the category argument?
The getproductsbycategory.html is created in Neos and has the right plugin for the action call. So I know the right action gets run but it does not get any args. At this point the argument is just a string and not an _identity even though I should eventually do it that way, I'm trying to keep things simple for now for the sake of expediency.
Thanks
Update: as a temp workaround shameless hack I just did this to get the variable:
$categoryID = $_GET['category'];
which works but I'd like to know the proper way especially if it does not involve writing my own view helpers.
First define variable in your html file
<script>
var ajaxUrl = '<f:uri.action action="actionName" controller="(controllername)Ajax"/>';
</script>
Your Ajax code will look like :->
$.ajax({
data: '&lookup='+{somevalue},
type: 'POST',
url: ajaxUrl,
success: function(data) {
$('.lookup-id').append(data);
},
});
Your conroller action will look like :->
public function getLookupIdAction(){
// Get company detail for set logo of company
$companyDetail = $this->getUserCompany();
// Template Name
$templateName = 'GetLookupID.html';
$viewVariables = $this->lookupIdentifierRepository->findByCompany($companyDetail);
$templatepath = 'resource://WIND.Alertregistration/Private/Templates/LookupIdentifier/' . $templateName;
$this->standaloneView->setLayoutRootPath('resource://WIND.Alertregistration/Private/Layouts');
$this->standaloneView->setPartialRootPath('resource://WIND.Alertregistration/Private/Partials');
$this->standaloneView->setFormat('html');
$this->standaloneView->setTemplatePathAndFilename($templatepath);
$this->standaloneView->assignMultiple(array("lookUpValue" => $viewVariables));
$this->standaloneView->setControllerContext($this->getControllerContext());
return $this->standaloneView->render();
}
Your view file look like :->
<f:layout name="Lookup" />
<f:section name="Content">
<label for="lookupId" style="box-sizing: border-box;">Identifier</label>
<div class="select-box" style="box-sizing: border-box;">
// Your Code
</div>
</f:section>

AJAX avoid repeated code

I'm using Symfony2.1 with Doctrine2.1
I'd like to use AJAX for many features on my site , editing a title , rate an article , create an entity on the fly , etc.
My question is simple :
Do I need to create a JQuery function for each functionnality , like this :
$('#specific-functionality').bind('click', function(e){
var element = $(this);
e.preventDefault();
// the call
$.ajax({
url: element.attr('href'),
cache: false,
dataType: 'json',
success: function(data){
// some custom stuff : remove a loader , show some value, change some css
}
});
});
It sounds very heavy to me, so I was wondering if there's any framework on JS side, or a specific method I can use to avoid this. I was thinking about regrouping items by type of response (html_content , boolean, integer) but maybe something already exists to handle it nicely !
From what I understand, you are asking for lighter version of JQuery ajax method. There are direct get/post methods instead of using ajax.
$.get(element.attr('href'), {'id': '123'},
function(data) {
alert(data);
}
);
To configure error function
$.get(element.attr('href'), {'id': '123'}, function(data) {alert(data);})
.error(function (XMLHttpRequest, textStatus, errorThrown) {
var msg = jQuery.parseJSON(XMLHttpRequest.responseText);
alert(msg.Message);
});
Also, you can pass callback function to do any synchronous operations like
function LoadData(cb)
{
$.get(element.attr('href'), { 'test': test }, cb);
}
And call
LoadData(function(data) {
alert(data);
otherstatements;
});
For progress bar, you use JQuery ajaxStart and ajaxStop functions instead of manually hiding and showing it. Note, it gets fired for every JQuery AJAX operation on the page.
$('#progress')
.ajaxStart(function () {
//disable the submit button
$(this).show();
})
.ajaxStop(function () {
//enable the button
$(this).hide();
});
Instead of $('#specific-functionality').bind('click', function(e){, try this:
$(".ajax").click(function(){
var url = $(this).attr("href") ;
var target = $(this).attr("data-target") ;
if (target=="undefined"){
alert("You forgot the target");
return false ;
}
$.ajax(....
And in html
<a class="ajax" href="..." data-target="#some_id">click here </a>
I think it is the simplest solution. If you want some link to work via ajax, just give it class "ajax" and put data-target to where it should output results. All custom stuff could be placed in these data-something properties.

Form submitted via dialog opens dialog again

I have a form in a jquerymobile dialog box that I am submitting via jQuery Ajax.
Currently my problem is that once the form is submitted the same dialog box is opened again on top of the original dialogbox.
So that my url reads before submission:
url/index.php#&ui-state=dialog
and then after submission:
url/index.php#&ui-state=dialog#&ui-state=dialog&ui-state=dialog
Has anyone ever encountered something like this before?
[edit added code example]
$(function(){
$("#form").submit(function(e){
e.preventDefault();
var dataString = $("#form").serialize();
errorInput = $("input[name=valOne]#valOne").val();
$.ajax({
type: "GET",
url: "formHandler.php",
data: dataString,
dataType: "text",
success: function(data){
if(data.toLowerCase().indexOf("error") >= 0){
alert(data);
$(".ui-dialog").dialog("close");
$("#valOne").val(errorInput); //the reentering info so user doesn't have to
}else{
$(".ui-dialog").dialog("close");
location.href="index.php";
}
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
}
});
});
});
You can set your own handler on form with this submit
Use two forms for page and for your dialog window.
Have you tried using $.mobile.changePage("url here") instead of location.href?
More details here http://jquerymobile.com/test/docs/api/methods.html
Would it not be easier to just refresh the page with JS instead of loading it again? It might be calling the dialog functions twice.
I had similar problem with forms. I decided to use <div data-role="fieldcontain"> instead. Now it works good with no "refresh effect". In this case you shouldmake your own message instead of .serialize.

Resources