Two different actions on one button - ajax

I have created a form in my view that calls some method in controller.
I want to do two things on my submit button function:
Use Ajax function to display output on the same page,
Get data (in the same method that is displaying the output) using $this->input->post function

You can write two functions on your button ... For type="button"
<input type="button" value="Don't show this again! " onclick="function1();function2();" />

You can do using ajax like this:
$.ajax({
url: "Here is the url path",
type: "GET",
data: {},
beforeSend:function(){
//do something like loading image
},
success:function(response){
alert(response); //do something
},
error:function(e){
alert("something wrong"+e);
}
})

Related

How do I handle multiple submit buttons in a single form with Laravel?

Is it possible multiple submit button without refresh in a single form and pass data to designed page through database? I have a from(section.blade.php) in which I have 3 section one for man scheduled 2nd for women scheduled and 3rd for child scheduled and only one submit button, but I want on 3 submit button on form for each section, so I could post data like for men(1), women(1+) and child(1+) on single design page. Please tell or give any relevant link or example, Many Many thanks.
Have you tried ajax request and response?
For example . When onclick event fired on button , make a function for onclick event .
I have added a code here .
Html
<button type ="button" onclick="licenseDelete(sendIdorAnyOtherValue);">
Click me to get value
</button>
JS
function LicenseDelete(Get the value) {
var img = key;
var d_id = $("#driv_id").val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
jQuery.ajax({
url: "{{ url('/vehicle/imgdestroy') }}",
method: 'post',
data: {
img : img,
d_id : d_id,
},
success: function(result){
var vehicle=JSON.parse(result);
console.log(vehicle);
//alert(result);
if(result){
toggleAlert();
}else{
$( "Failed . Try again" ).empty();
$("#send_id").attr("disabled", false);
}
}});
}

PATCH AJAX Request in Laravel

Is it possible to make AJAX PATCH requests to laravel, or am I restricted to POST? Laravel uses PATCH in input hidden fields, however, I am not using form elements—just buttons that should partially update a record when clicked (via an AJAX request).
How would the route look like for this?
Routes file
Route::patch('questions/{id}', 'QuestionController#update')->before('admin');
I am not sure if laravel routes support PATCH.
Controller
public function update($id) {
if (Request::ajax() && Request::isMethod('patch')) {
//partially update record here
}
}
JS
$('div#question_preview <some button selector>').click(function (event) {
$.ajax({
url: 'questions/'+question_id,
type: 'PATCH',
data: {status: 'some status'}
});
});
I am just looking for clarity, thanks!
Yeah, it's possible try
In Your JavaScript
$('#div#question_preview <some button selector>').click(function() {
$.ajax({
url: 'questions/'+question_id,
type: 'PATCH',
data: {status: <SOME VALUE I WANT>, _method: "PATCH"},
success: function(res) {
}
});
});
In Your Route
Route::patch('questions/{id}', 'QuestionController#update')->before('admin');
In your QuestionController Controller's update method
dd(Request::method());
You will see the respond like
string(5) "PATCH"
Read more about Request Information on Laravel doc.
It's possible!
You should need to provide an extra parameter in the form request called as _method with a value PATCH.
JS
$('div#question_preview <some button selector>').click(function (event) {
$.ajax({
url: 'questions/'+question_id,
type: 'PATCH',
data: {status: 'some status',_method: 'PATCH'}
});
});
You can provide a hidden input in the view file with the value PATCH for better readability
HTML
<input type="hidden" name="_method" value="PATCH">
If you are using FormData, you need to send the request as POST. The Laravel application will automatically get it as a PATCH request because you included #method('PATCH'). So your route and method for that will get triggered.
JS with FormData
$('div#question_preview <some button selector>').click(function (event) {
let form_data= new FormData();
form_data.append('status','some status');
form_data.append('_method','PATCH');
$.ajax({
url: 'questions/'+question_id,
type: 'POST',
data: form_data
});
});

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>

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.

Yii, how to custom submit button in cactiveform

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

Resources