Render different Zend forms based on Ajax post request - ajax

I am trying to display different forms based on user type using Ajax post request. The request response works fine but I don't know how to display the form. For example, if the user selects parent then I want the parent form to be displayed and so on. I'm using ZF 1.12.
public function init() {
$contextSwitch = $this->_helper->getHelper('AjaxContext');
$contextSwitch =$this->_helper->contextSwitch();
$contextSwitch->addActionContext('index', 'json')
->setAutoJsonSerialization(false)
->initContext();
}
public function indexAction() {
$this->view->user = $this->_userModel->loadUser($userId);
//if($this->_request->isXmlHttpRequest()) {
//$this->_helper->layout->disableLayout();
//$this->_helper->viewRenderer->setNoRender(true);
if ($this->getRequest()->isPost()){
$type = $_POST['type'];
$this->view->userForm = $this->getUserForm($type)->populate(
$this->view->user
);
}
}
And here's what I have on the client side. What do I need to write in the success section?
<script type="text/javascript">
$(document).ready(function(){
$('#userType').on('change', function(){
var type = $(this).val();
select(type);
});
});
function select(type) {
$.ajax({
type: "POST",
url: "admin/index/",
//Context: document.body,
data: {'type':type},
data: 'format=json',
//dataType: "html",
success: function(data){
// what to do here?
},
error: function(XMLHttpRequest, textStatus, errorThrown) {}
});
}
</script>
<form id="type" name="type" method="post" action="admin/index">
<select name='userType' id='userType' size='30'>
<option>admin</option>
<option>parent</option>
<option>teacher</option>
</select>
</form>
<div id="show">
<?php //echo $this->userForm;?>
</div>

If your ajax request form returns you the HTML from the Zend_Form, you could simply write the HTML in the #show div.
In you view you will need to do this :
echo $this->userForm;
This way, all the required HTML will be written on the server side, before sending the response to the HTML page. In the HTML page you then just have to write the response in the right location with the method $('#show').html(data). You also have to make sure that each of your forms has the right action when you render them.
The other option would be to have all three forms hidden in your page (through Javascript) upon loading and based on the select (Generated with JS), display the right form. This way you don't have to load data from an external source and if someone have JS disabled, he still can use the application. On the other hand, this method will have each page load about 1/2 a KB more of data.

Related

Spring controller does not load view

I calling a controller via button click using ajax. I want it to load hello.html page but I want spring to do it not ajax.
What happens after I click the button is nothing but I'm sure the controller is being hit.
Here is the controller I'm calling via button click using ajax.
#RequestMapping(value="/submitName", method=RequestMethod.GET)
public String submitName(#RequestParam String name, Model model) {
System.out.println(name);
model.addAttribute("name", name);
return "hello";
}
Here is the ajax call.
$('#submit-button').on('click', function() {
$.ajax({
type: 'GET',
url: '/submitName',
data: {name: $('#name').val()}
});
});
Funny thing is in the chrome network tab it shows the page that I'm expecting. Here is a snippet.
I think everything is ok here, except you didn't mention how you want to show your page or where. You have to declare a container where your html returned from controller would appear, like under a div id or something like that.
So, just in your current html page, declare a new tag, may be <div id="current-page-id"></div>
Now, append the hello.html page to your current page using jquery:
$("#current-page-id").html(responseData);
So, basically, do this:
$.ajax({
type: 'GET',
url: '/submitName',
data: {name: $('#name').val()},
dataType: 'html',
success: function (responseData) {
$('#current-page-id').html(responseData);
},
});
Or, simply, load the page as separate html page, not via ajax.
Update:
instead of using ajax-as you asked for in comment section, do this as follows:
function getHtmlPage(String name)
{
location.href = 'submitName/' + name;
}
Now call your method on button click:
$('#submit-button').on('click', function() {
var name=$('#name').val();
getHtmlPage(name);
});
AJAX Calling just send the request to the server (controller) and received a response,
By default, It's dos not responsibility for reloading the page.
In this why when you click the button it hit the server-side but stay on the same page.
Simple there is two way you can load your new page ( hello.html )
1| With AJAX calling:
On the button click method, you have to explicitly load the page (Best practice in Ajax Success block)
adding this window load metbod:
window.location.href = "http://localhost:8080/hello.html";
Like:
$('#submit-button').on('click', function() {
$.ajax({
type: 'GET',
url: '/submitName',
data: {name: $('#name').val()}
window.location.href = "http://localhost:8080/hello.html";
});
});
2| Direct Http Call on the Button
HTML
<a class="btn btn-primary btn-lg pull-right" href="http://localhost:8080/hello" role="button">Hello Page</a>
JSP:
<a class="btn btn-primary btn-lg pull-right" href="${pageContext.request.contextPath}/hello" role="button">Hello page</a>
Thymeleaf
<a class="btn btn-xs" th:href="#{/hello})}">Hello Page </a>

How does the browser load content of the previous page?

I'm creating a web page with laravel and the main menu pages contents are loaded with ajax. The problem is when I go back to the previous page with the back button of the browser, the browser loads not only the content received by the ajax call but the entire page. So I get two headers and two footers.
This is my code:
base.blade.php:
<html>
<body>
// list of menu
...
<div class="main">
#yield('main')
</div>
</body>
</html>
page.blade.php:
#extends('base')
#section('main')
<div class="main">
My page content.
</div>
#stop
// user clicks on the menu link and calls this script
script.js:
$(".menu_list").on("click", "a.menu_page", function(e) {
// get some variables
$.ajax({
type: "GET",
url: url,
dataType: "html",
success: function (result) {
// get only div.main content from result
var mainContent = $(result).find("div.main").html();
// and load this data
$("div.main").html(mainContent);
} ...
I also tried not to return the full page data but only the main section in the controller:
controller.php:
...
if(Request::ajax()) {
return view('page')->renderSections()['main']; }
And in script.js:
success: function (result) {
$("div.main").html(result);
but it did not have any effect.
So I don't understand why the browser loads the entire page into the #yield section after returning to the previous page, although the controller only returned part of the page content.

Django: populate modal with a form through Ajax

I´m trying to show a prepopulated form in a modal so users can click on an item, the modal opens showing a form with that item´s data that users can edit and save.
I can send data from a view to a modal with json serializer but I can´t find how to send a form.
When I test this, I get an error declaring that "Object of type FormularioTareas is not JSON serializable"
The problem seems to be clear, I can´t send the form through a json response. How can I handle this?
Thanks in advance!
The modal call in the template
<form name="form" action="#" id="form_tarea_{{tarea.id}}" method="POST">
{% csrf_token %}
<input name="id" id="tarea_id_submit" type="text" value="{{tarea.id}}" hidden="true"/>
<a href="" id="{{tarea.id}}" class="show_tarea" data-toggle="modal" >Este link</a>
</form>
The Ajax script
Here I´m using now $('#caca').text(tarea_data.caca); only to test I can send some info to the modal correctly. It works.
I guess I should update that "text" type to another one in order to work.
<script>
$(function(){
$('.show_tarea').on('click', function (e) {
e.preventDefault();
let tarea_id = $(this).attr('id');
$.ajax({
url:'/catalog/tareas-detail/',
type:'POST',
data: $('#form_tarea_'+tarea_id).serialize(),
success:function(response){
console.log(response);
$('.show_tarea').trigger("reset");
openModal(response);
},
error:function(){
console.log('something went wrong here');
},
});
});
});
function openModal(tarea_data){
$('#caca').text(tarea_data.caca);
$('#modal_tareas').modal('show');
};
</script>
The view
def TareaDetailView(request):
context = {}
tareas = Tareas.objects.values()
context[tareas] = Tareas.objects.all()
if request.method == 'POST' and request.is_ajax():
ID = request.POST.get('id')
tarea = tareas.get(pk=ID) # So we send the company instance
tareas_form = FormularioTareas(tarea)
caca = ID
return JsonResponse(tareas_form, safe=False)
else:
return render(request, 'catalog/artista.html', context)
Django forms are not json serializable. Either pass your model to json response or return your form as text/json.
return JsonResponse(serializers.serialize('json', tarea), safe=False)
I never use django or phyton before but I will try to help you:
First your ajax, try to use a done insteand of success, in this example you are getting info from some select to fill a form inside a modal with specific
function getData(clientId){
return $.ajax({
method: "POST",
url: "YourUrl",
data: { action: "SLC", clientId: clientId}
})
}
then you get your stuff:
getData(clientId).done(function(response){
//manage your response here and validate it
// then display modal, note: you must have some conditions to get the array
//and fill each input use JSON.parse to get the json array elements
openModal(response);
})
hope it helps

How to use the AJAX response in FLUID templates TYPO3 Extbase

I finally made my AJAX working in Extbase Typo3 6. However, I'm trying to use the returned array from AJAX in my FLUID view.
my Ajax action in Controller:
public function ajaxAction(){
$id = $this->request->getArgument['id'];
$record = $this->articleRepository->findByUid($id);
return json_encode(['record'=>$record,'status' => 'Loaded']);
}
My AJAX :
function dropCall(selectFieldObj) {
$.ajax({
type: 'POST',
url: link,
dataType: 'json',
success: function(data){
alert(data.status);
}
});
}
Now the question is how do I use the data object sent from the controller action in my View ? The alert is being displayed.
My List.html view
<script type="text/javascript">
var link
= '<f:uri.action action="ajax" controller="Article" pageType="99" arguments="{data:1}"/>';
</script>
<script type="text/javascript" src="fileadmin/myScript.js"></script>
<select id="drop" onchange="dropCall(this)">
<option value="1">Apple</option>
<option value="2">Mango</option>
<option value="3">Grape</option>
</select>
In my view, I should be able to do something like
<h1> {record.name} </h1>
EDIT
The object record might contain many properties and each record.property like record.name will be under <h1> tags and record.somethingelse can be under some under tag.
Just like we send objects from controller to view and use them in FLUID, I would want to do the same with AJAX

How to change submit value of form after used by AjaxForm

I am using AjaxForm extension to submit form with ajax as following
var options =
{
url:'<?php echo site_url('user/ajaximage')?>',
dataType: 'json',
success: function(data)
{
if(data.messagecode==1)
{
$(".wrap label").hide();
$("#preview").html("<img src='"+data.content+"'class='preview'>");
$("#errormessagepic").hide();
}
else if(data.messagecode==0)
{
$("#errormessagepic").html(data.content);
$("#preview").html('<img width="100" height="100" src="<?php echo base_url();?>/images/avatar_generic.png" />');
}
//$('#SignupForm').resetForm();
//$("#SignupForm").attr('action','<?php echo site_url('user/individualprofile')?>');
} ,
};
$("#SignupForm").ajaxForm(options);
$("#SignupForm").submit();
but after this ajax submission I want to resend form to another URL other than '' but it does not work. Any help
Ok so you want to post a form using ajax to two different urls. I dont know about your extension but i can tell you how to do this.
1- create a function and run this function when the user clicks on the submit
<-input type="button" name="submit" value="Submit" onclick="post_form()"-/>
2- Create the body of the function, this function will submit data to two urls
function post_form(){
// save the values in text boxes in variable
var val1=$("#text1").val();
var val2=$("#text2").val();
var data={name:val1,age:val2};
var url1="savedata.php";
var url2="updatedata.php";
$.post(url1,data, function(response){
alert(response);
// so when the form is submited to ur1 this callback function runs and here you can submit it to another url
$.post(url1,data,function(response){alert(response)});
});
}
</script>

Resources