I wrote a function to sent a simple request trough Controller via JavaScript in my Symfony project. My alert is triggered when I refresh the page and it should be triggered when I am clicking the Submit button.
What I am doing wrong?
Button:
<button type="button" id="request" data-path="{{ admin.generateObjectUrl('change_status', object) }}" class="btn btn-primary">Submit</button>
My JS code:
var path = $("#request").attr("data-path");
$.ajax({
type: "POST",
url: path,
data: {id : 'aaa'},
"success":function(data){
alert('ok');
}
});
and Controller:
$data = $request->request->get('request');
return new Response($data);
You have to set the onclick property in your button and wrap your JS code in a function that will be called by this onclick
Related
I'm trying to make a function 'add to my list' in my web application.
When user clicks on an icon, this fuction should change the color of the icon after sending data to server.
It doesn't throw any errors, it sends data to server successfully, but it never changes the icon. 'console.log' inside ajax success handler is working fine, so what is the problem here?
Thanks in advance!
<div class="buttons">
<button type="button" class="btn threeButtons" onclick="request_access(this)" id="{{ elem['isbn'].split()[0] }}">
<i class="fas fa-plus"></i>
</button>
</div>
function request_access($this){
console.log("button clicked");
var request_data = $this.id;
var me = $(this);
$.ajax({
url: "/admin_add_books",
type: "POST",
data: request_data,
success: function(){
console.log("data: " + request_data)
me.find('i').addClass('green');
}
})
}
If you want to do sthg just after data is sent but response is not sent from server, then you should do sthg like:
var response = $.ajax({
url: "/admin_add_books",
type: "POST",
data: request_data
});
// Change color just after data is sent
me.children("i").addClass("green");
response.done(function(result){
// Server returned result
me.children("i").addClass("green");
});
*Note:- success is depreciated in modern version of jquery. Link
I need to submit HTML(with Thymeleaf) form and open a bootstrap modal at the same time. In order to submit a form I set type="submit" in a button tag. When I need to only open a modal I set type="button". And it works. But how to do these two actions with one button?
form with the button:
<div class="button-view">
<form id="view-form" action="/view-modal" method="get">
<input type="hidden" th:value="${n.getId()}" name="viewNoteId">
<button class="btn btn-info" data-toggle="modal" data-target="#view-modal"
type="button">View</button>
</form>
</div>
method in Spring Controller which submits the form:
#GetMapping("/view-modal")
public String viewNote(#RequestParam(value = "viewNoteId") Long id, Model model) {
model.addAttribute("noteToView", noteService.getNoteById(id));
prepareHomepage(model);
return "/fragments/view-modal";
}
Use javascript to submit your data via AJAX using an onclick function.
button example :
<button th:onclick="'submit(\'' + ${n.getId()} + '\');'" class="btn btn-info" data-toggle="modal" data-target="#view-modal"
type="button">View</button>
javascript example :
function submit(userId) {
$.ajax({
url : yourURLString,
type : 'POST',
data : userId,
dataType: 'json',
contentType: 'application/json',
success : function(returndata) {
},
fail : function() {
}
});
}
Controller :
#RequestMapping(value = "admin/users", method = RequestMethod.POST)
public RedirectView addUser(#RequestBody int id) {
/////
}
Something like that.
I have the following code which runs when a button is clicked.
$.ajax({
type: "POST",
url: base_url+"/controller/method",
data: {val: value},
success: function(data){
data = jQuery.parseJSON(data);
if(data.status === true){
show_notify_message("Success",data.msg,'success');
} else {
show_notify_message("Error",data.msg,'error');
}
}
});
HTML Code:
<button class='btn btn-xs alert-success' onclick='method(1)'><font color='black'>Take</font></button>
Once the changes are made the entire page refreshes and the updated values are seen in the view.
How can I perform the same action without the entire page refreshing?
try it this way
HTML code
<button class='btn btn-xs alert-success' data-method='1'><font color='black'>Take</font></button>
JQuery script
$(document).ready(function(){
$("[data-method]").click(function(event){
event.preventDefault();
//value from the button
value=$(this).data("method");
// ajax call
});
});
if you use a <button> element, set it's type to "button" like this:
<button type="button">Click Me</button>
for some reason the default type is "submit"
I am having a some problem in my java script and to get the request.
This is the HTML
<form method="post" id="searchform">
<div align="center" class="col-md-10">
<input type="text" id= "contentSearch" name="contentSearch" >
</div>
<div class="form-group"><button type="submit" class="btn btn-default" id="submitSearch">
<i class="fa fa-search"></i> Search
</button></div>
</form>
<----Scenario 1 ---->
This script works fine and post the value and as ajax it never reload the page
<script>
$(document).ready(function () {
$("#submitSearch").on('click', function (e) {
e.preventDefault();
e.stopPropagation();
var data = {};
data['contentSearch'] = $('#contentSearch').val();
// Submit data via AJAX§
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (data) {
// do i need to do something here !!
}
});
});
});
</script>
When i check the POST value i can see the value is been POST.
The Problem is when i try to get the request data from controller like ---
$post_value = $request->request->get('contentSearch');
print_r($post_value);
OUTPUT : empty
<----Scenario 2 ---->
This script have a problem i think, because it reload the page for returning the result and displaying the value ---
<script>
$(document).ready(function () {
$("#searchform").on('submit', function (e) {
e.preventDefault();
var data = {};
data['contentSearch'] = $('#contentSearch').val();
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (data) {
}),
return false;
});
});
</script>
than i am able to get the post value like so--
$post_value = $request->request->get('contentSearch');
But the problem is in the second script the page is always loading when return the request which is not a ajax behave.
And in the first script i think because of the **e.preventDefault();** i am not getting the POST value in my controller.
Expected result ---
Option 1 : Do something so i can get the POST value in my controller
Option 2 : Fix this script so the page do not load to return the result and display
I am working on symfony framework .
Can someone please help me to fix this problem, i am really getting sick of to solve this problem.
Thanks a lot on advanced.
Like I mentioned in the comments, you need to be targeting the submit on the form. Not a click event. When targeting the click you are firing both the click and submit events, hence the reload.
$(document).ready(function () {
$("#searchform").on('submit', function (e) {
var data = {};
data['contentSearch'] = $('#contentSearch').val();
$.ajax({
url: '/home',
type: 'post',
data: data,
success: function (data) {
}
});
return false;
});
});
I have a formRemote that calls a function in my controller when it is submitted like this:
<g:formRemote name="editIndivRecForm" url="[controller: 'customer', action:'saveEditedIndividualRecord']" onSuccess="doResult();">
This form is submitted by clicking on a button. Rather, a button that is clicked called 'save' will do other things among clicking the form's submit button via Javascript. Here is the click handler for this button:
$('#save').click(function () {
$("#uniqueId").prop('disabled', false); // Have to enable before form submission else it doesn't go back as a param to controller.
$("#secondaryId").prop('disabled', false);
$("#submit").trigger("click"); // formRemote's submit button
$('#editIndivRecForm').reset;
<g:remoteFunction controller="customer"
action="remediationSearch"
update="content_area"
params="{rerender: true}"/>
});
The problem I'm running into is that I need the function of my controller called by the click handler remediationSearch to run AFTER the function of the controller called by the formRemote's submission saveEditedIndividualRecord is done executing. But it is happening the other way around. And for some reason the function onSuccess="doResult();" doesn't even execute otherwise I was going to move the following code into its body to make things work the way I want:
<g:remoteFunction controller="customer"
action="remediationSearch"
update="content_area"
params="{rerender: true}"/>
here is how doResult is now:
function doResult() {
console.log("done.");
}
the formRemote is submitted but the doResult function prints nothing to the console.
Seeing as all of the Grails AJAX related tags have been deprecated, I would recommend trying it this way:
Markup:
<form id="editIndivRecForm" onsubmit="return false;">
<!-- add fields here -->
<input type="text" id="uniqueId" value="${something}">
<input type="text" id="secondaryId" value="${something}">
<button id="save" type="button">
</form>
JavaScript:
// Function to update your content_area div
function updateContentArea() {
var params = { rerender: true };
var url = "${createLink(controller: 'customer', action: 'remediationSearch')}";
$.get(url, params, function(data) {
$("#content_area").empty().append(data);
});
}
$("#save").on('click', function() {
// Collect values from form and submit ajax request
// Using name and description for example fields here:
var data = {
name: $("#name").val(),
description: $("#description").val(),
uniqueId: $("#uniqueId").val(),
secondaryId: $("#secondaryId").val()
};
var url = "${createLink(controller: 'customer', action: 'saveEditedIndividualRecord')}";
// Submit the (first) AJAX request
$.ajax({
type: "post",
url: url,
data: data,
success: function() {
doResult();
$('#editIndivRecForm').reset();
updateContentArea();
}
});
}