How do I go back in controller? - javascript

I have forms with id's formularregister and formularadresa and one button to submit with id comanda.
I want to submit both forms with one button (<a type="submit" id="comanda" class="btn btn-default" onclick="submitForms()">Finalizare comanda</a>) and go back to controller action (zend framework 2) to validate the values from post.
My JS function is this:
function submitForms() {
$(document).ready(function() {
$("#comanda").click(function() {
$.post($("#formularregister").attr("afisarecos.phtml"), $("#formularregister").serialize() + $("#formularadresa").serialize(), function() {
});
});
});
}

You need to make an AJAX request to your controller action. You'll find a lot of examples on the Web, but the most important parts to know for using Ajax in ZF2 are:
Enable ViewJsonStrategy in your /module/Application/config/module.config.php
'view_manager' => array(
// ....
'strategies' => array(
'ViewJsonStrategy',
),
),
Ajax request in your view
$.ajax({
url : 'url/to/yourController/action',
type: 'POST',
dataType: 'json',
data : fromData,
async: true,
success:function(data, textStatus, jqXHR)
{
//success function
}
error : function(xhr, textStatus, errorThrown)
{
// error function
}
});
In your controller action
if ($request->isXmlHttpRequest()) { //ajax call
// your logic here
$jsonModel = new JsonModel(
//...
);
return $jsonModel;
}
Please see this simple example (Code + Demo) for more details.

Related

How to run JavaScript code on Success of Form submit?

I have an Asp.Net MVC web application. I want to run some code on the successful response of the API method which is called on form submit.
I have the below Code.
#using (Html.BeginForm("APIMethod", "Configuration", FormMethod.Post, new { #class = "form-horizontal", id = "formID" }))
{
}
$('#formID').submit(function (e) {
$.validator.unobtrusive.parse("form");
e.preventDefault();
if ($(this).valid()) {
FunctionToBeCalled(); //JS function
}
}
But FunctionToBeCalled() function gets called before the APIMethod(), but I want to run the FunctionToBeCalled() function after the response of APIMethod().
So I made the below changes by referring this link. But now the APIMethod is getting called twice.
$('#formID').submit(function (e) {
$.validator.unobtrusive.parse("form");
e.preventDefault();
if ($(this).valid()) {
//Some custom javasctipt valiadations
$.ajax({
url: $('#formID').attr('action'),
type: 'POST',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
}
}
function FunctionToBeCalled(){alert('hello');}
So I am not able to solve the issue.
If you want to execute some work on success, fail, etc. situation of form submission, then you would need to use Ajax call in your view. As you use ASP.NET MVC, you can try the following approach.
View:
$('form').submit(function (event) {
event.preventDefault();
var formdata = $('#demoForm').serialize();
//If you are uploading files, then you need to use "FormData" instead of "serialize()" method.
//var formdata = new FormData($('#demoForm').get(0));
$.ajax({
type: "POST",
url: "/DemoController/Save",
cache: false,
dataType: "json",
data: formdata,
/* If you are uploading files, then processData and contentType must be set to
false in order for FormData to work (otherwise comment out both of them) */
processData: false, //For posting uploaded files
contentType: false, //For posting uploaded files
//
//Callback Functions (for more information http://api.jquery.com/jquery.ajax/)
beforeSend: function () {
//e.g. show "Loading" indicator
},
error: function (response) {
$("#error_message").html(data);
},
success: function (data, textStatus, XMLHttpRequest) {
$('#result').html(data); //e.g. display message in a div
},
complete: function () {
//e.g. hide "Loading" indicator
},
});
});
Controller:
public JsonResult Save(DemoViewModel model)
{
//...code omitted for brevity
return Json(new { success = true, data = model, message = "Data saved successfully."
}
Update: If SubmitButton calls a JavaScript method or uses AJAX call, the validation should be made in this method instead of button click as shown below. Otherwise, the request is still sent to the Controller without validation.
function save(event) {
//Validate the form before sending the request to the Controller
if (!$("#formID").valid()) {
return false;
}
...
}
Update your function as follows.
$('#formID').submit(function (e) {
e.preventDefault();
try{
$.validator.unobtrusive.parse("form");
if ($(this).valid()) {
$.ajax({
url: $('#formID').attr('action'),
type: 'POST',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
}
}
catch(e){
console.log(e);
}
});
Check the browser console for fetching error. The above code will prevent of submitting the form.
I think line $.validator.unobtrusive.parse("form") were throwing error.
For that use you need to add the following jQuery libraries.
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validation-unobtrusive/3.2.11/jquery.validate.unobtrusive.min.js"></script>
I think you should remove razor form tag if you want to post your form using ajax call and add post api URL directly to ajax request instead of getting it from your razor form tag using id:
Here is the revised version of your code :
<form method="post" id="formID">
<!-- Your form fields here -->
<button id="submit">Submit</button>
</form>
Submit your form on button click like:
$('#submit').on('click', function (evt) {
evt.preventDefault();
$.ajax({
url: "/Configuration/APIMethod",
type: 'POST',
dataType : 'json',
data: $('#formID').serialize(),
success: function () {
console.log('form submitted.');
FunctionToBeCalled(); //JS function
}
});
});
function FunctionToBeCalled(){alert('hello');}
You need to use Ajax.BeginForm, this article should help [https://www.c-sharpcorner.com/article/asp-net-mvc-5-ajax-beginform-ajaxoptions-onsuccess-onfailure/ ]
The major thing here is that I didn't use a submit button, I used a link instead and handled the rest in the js file. This way, the form would nver be submitted if the js file is not on the page, and with this js file, it initiates a form submission by itself rather than th form submitting when the submit button is clicked
You can adapt this to your solution as see how it respond. I have somthing like this in production and it works fine.
(function() {
$(function() {
var _$pageSection = $('#ProccessProductId');
var _$formname = _$pageSection.find('form[name=productForm]');
_$formname.find('.buy-product').on('click', function(e) {
e.preventDefault();
if (!_$formname.valid()) {
return;
}
var formData = _$formname.serializeFormToObject();
//set busy animation
$.ajax({
url: 'https://..../', //_$formname.attr('action')
type: 'POST',
data: formData,
success: function(content) {
AnotherProcess(content.Id)
},
error: function(e) {
//notify user of error
}
}).always(function() {
// clear busy animation
});
});
function AnotherProcess(id) {
//Perform your operation
}
}
}
<div class="row" id="ProccessProductId">
#using (Html.BeginForm("APIMethod", "Configuration", FormMethod.Post, new { #class = "form-horizontal", name="productForm" id = "formID" })) {
<li class="buy-product">Save & Proceed</li>
}
</div>

Not working : Send POST Data with Ajax to a Symfony2 Controller

I would like to send Post Data to a Symfony Controller, but it doesn't work. When I send my data with AJAX, it is sending the POST data, but it is showing red link in the console with no error message or status; but 200ok in net FF. It is sending the request successfully through a normal form.
Here is my Javascript code:
function addprivate() {
var form_data = $('#private_tuition').serialize();
var getTeamsUrl = Routing.generate('addprivatetuition', {
id: form_data
});
$.ajax({
type: "post",
url: getTeamsUrl,
data: form_data,
success: function(response) {
if (response) {
} else {
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$.notify('Error : Record not found !!', {
"status": "danger",
"pos": "top-center"
});
}
});
}
Below is the form tag and js funxtion:
<form method="post" role="form" id='private_tuition' action="{{base_url}}/privatetutionpdf/" >
<button type="submit" class='btn btn-primary' onclick='addprivate()' name="btn-save">
<strong>Generate PDF for client</strong>
</button>
Here is the PHP Symfony Controller method which received data:
namespace Suntec\Marcus\AssignmentBundle\Controller;
use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
class DefaultController extends Controller
{
....
/*****************************************************************/
/**
* #Route("/addprivatetuition", name="addprivatetuition", options={"expose"=true})
* #Template()
*/
public function addprivatetuitionAction(){
return array();
//return array();
}
...
}
looks like you have to prevent the default action of the form, because when you click your submit button the html form will be submitted.
to only submit via javascript do sth. like:
$('#private_tuition').submit(function(e){
e.preventDefault();
}
or
$('#private_tuition').submit(function(){
return false;
}

Ajax load different wordpress content based on user click

I'm trying to load different templates through $.ajax based on what buttons a user clicks. I know how to do it with one template file, but can't seem to find a way to adjust the code to load different template based on click (without repeating the code).
Here's the relevant part of the ajax call:
var $this = $('#my-data');
$('#button-foo').click(function() {
$.ajax({
url: myAjax.ajax_url,
data: {
action: 'my_ajax_action'
},
cache: true,
beforeSend: function(){
$this.empty();
$this.addClass('loading');
},
complete: function(){
$this.removeClass('loading');
},
success: function(data) {
$this.append(data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
And here's my Wordpress function:
function my_ajax_action() {
include(locate_template( 'part-template-foo.php' ));
die();
}
add_action('wp_ajax_nopriv_my_ajax_action', 'my_ajax_action');
add_action('wp_ajax_my_ajax_action', 'my_ajax_action');
Now what I need would be to include 4 different templates (part-template-bar.php, part-template-foobar.php, etc) based on user click. Something like:
function my_ajax_action() {
if ($_REQUEST['template'] == 'foo') {
include(locate_template( 'part-foo.php' ));
die();
}
if ($_REQUEST['template'] == 'bar') {
include(locate_template( 'part-bar.php' ));
die();
}
...
}
Any hint on how could I do this without having to repeat the js code and wp function four times? Thank you.

Jquery Add Argument to Function on $.ajax

I want to return my button value if ajax failure.
This HTML (on PHP):
<a href="javascript:void(0);" id="follow-topic" value="7">
<button class="btn btn-xs btn-primary pull-right"><?php echo $_LANGS['forum']['follow']; ?></button>
</a>
This JS (on PHP):
$("#follow-topic").click(function(event) {
var topicid = $(this).attr('value');
var button_follow_html = $(this).html();
if ($(this).is("a[disabled]")){ return false; }
$("#follow-topic button").html('<?php echo $_LANGS['system']['loading_button']; ?>');
$(this).attr({ disabled: true});
$.ajax({
url: "",
data: { follow_topic: topicid },
type: "POST",
success: function (data) {
$("#follow-topic").html(data);
$("#follow-topic").attr({ disabled: false});
},
error: function(data, button_follow_html) {
handleRequestError(data);
$("#follow-topic").attr({ disabled: false});
$("#follow-topic").html(button_follow_html);
}
});
});
I've change a button value to $_LANGS['system']['loading_button'] but i want return to $_LANGS['forum']['follow'] if ajax failure or client lost connection.
This system using multiple languages and if ajax is success, button will be replaced to followed button so i can't use $("#follow-topic button").html('<?php echo $_LANGS['forum']['follow']; ?>');.
Sorry for My English and Thank you
From jQuery documentation, the error function called if ajax call fails takes 3 parameters:
error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
So you are actually getting the textStatus respond in your button_follow_html variable in this code:
error: function(data, button_follow_html) {
handleRequestError(data);
$("#follow-topic").attr({ disabled: false});
$("#follow-topic").html(button_follow_html);
}
The parameters are optionnal, so instead you can just do:
error: function(data) {
handleRequestError(data);
$("#follow-topic").attr({ disabled: false});
$("#follow-topic").html(button_follow_html);
}
button_follow_html won't be redefined and will still have the same value as before the ajax call so you can use it as is.

Play framework JavaScript function as scala template parameter

I want to reuse a javascript function using a scala template so I would only have to pass a different success/failure function, but I don't seem to be able to able to pass a javascript function to a scala template.
Please note I'm veeeeerry new to this and don't even know if what I am doing is possible.
This is kind of what I'm trying to achieve:
#(formId: String, success: JavaScript, fail: JavaScript)
<script type="text/javascript">
$("#formId").submit(function(e)
{
var data = $(this).serializeArray();
var action = $(this).attr("action");
$.ajax(
{
url : action,
type: "POST",
data : data,
success:function(data, textStatus, jqXHR) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
#success()
/*console.log("save succesfull, progress!")
alert('Save successfull, now move on!');*/
},
error: function(jqXHR, textStatus, errorThrown) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
//if fails
#fail()
/*console.log(jqXHR.responseText);
var errors = JSON.parse(jqXHR.responseText);
console.log(errors);
alert('Woops, something went wrong: ' + jqXHR.responseText);*/
}
});
e.preventDefault();
});
</script>
How it would be used:
#snippets.ajaxFormSubmit("#form",
function()
{
alert("Save successfull, now move on!");
},
function()
{
alert("Save failed!");
}
)
You can pass any content to a template via Html type.
#(formId: String, success: Html, fail: Html)
<script type="text/javascript">
$("#formId").submit(function(e)
{
var data = $(this).serializeArray();
var action = $(this).attr("action");
$.ajax(
{
url : action,
type: "POST",
data : data,
success:function(data, textStatus, jqXHR) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
#success
},
error: function(jqXHR, textStatus, errorThrown) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
#fail
}
});
e.preventDefault();
});
</script>
In a client view you can user it as follows:
#successFunc = {
alert("Save successfull, now move on!");
}
#failureFunc = {
alert("Save failed!");
}
#snippets.ajaxFormSubmit("#form", successFunc, failureFunc)

Categories

Resources