How to send js variable to Spring controller? - javascript

I have this html code
<button onclick="var pdata = $('textarea').froalaEditor('html.get');">Submit article</button>
So I want to send this pdata variable to controller. How do I do this? Or should I use a form?

If you already use jQuery, consider the jQuery.post() method.
$.post("controller/path", pdata)
.done(function(response) {
comsole.log("Response: " + response);
});
You could move this code to a function, for example, like this:
<button onclick="submitArticle()">Submit article</button>
and in JS:
function submitArticle() {
var pdata = $('textarea').froalaEditor('html.get');
$.post("controller/path", pdata).done(function(response) {
comsole.log("Response: " + response);
});
}
Note that according to jQuery docs your pdata should be
A plain object or string that is sent to the server with the request.

$("#button").click(function(){
$.ajax({
type : "POST",
url :"url",
data : {id: $("#field").val()},
timeout : 100000,
success : function(response) {
alert(response);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);},
done : function(e) {
console.log("DONE");
}
});

Hey here is working example of post action ajax+jquery
consider one textfield and one button for example
MyButton
see following ajax call:
function updatData() {
var value= $("#sample").val();
$.ajax({
type : "POST",
url :"url",
data : {id:value},
timeout : 100000,
success : function(response) {
alert(response);
},
error : function(e) {
console.log("ERROR: ", e);
display(e);},
done : function(e) {
console.log("DONE");
}
});
}

Related

Reducing Duplicate Javascript Code for Ajax Request

I'm writing this question because I have an AJAX request for deleting posts into my website that is working fine but I have duplicated it multiple times to match the URL for different Custom Post Type that I have in the page.
Here the original code:
jQuery(".delete-listing-btn").on("click", function(e) {
var thisPost = jQuery(e.target).parents(".agent-dashboard-listing-card")
jQuery.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader('X-WP-Nonce', msSiteData.nonce);
},
url: 'https://mallorca-select.com/wp-json/wp/v2/properties-for-sale/' + thisPost.data('id'),
type: 'DELETE',
success: function () {
alert(" Listing Deleted Successfully! ");
},
error: function (request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
}
});
});
In these functions the only thing that changes is a part of the URL request like this:
'https://example.com/wp-json/wp/v2/post-type-1/' + thisPost.data('id')
'https://example.com/wp-json/wp/v2/post-type-2/' + thisPost.data('id')
'https://example.com/wp-json/wp/v2/post-type-3/' + thisPost.data('id')
'https://example.com/wp-json/wp/v2/post-type-4/' + thisPost.data('id')
I'm wondering if there is a method for detecting the post type of the post where the delete button is clicked and inject inside the URL request so I don't have to duplicate it 4 times only to change the custom post type inside the url.
Move the common AJAX code to a separate function and pass the specific URL you need in each case.
jQuery(".delete-listing-btn").on("click", function(e) {
var thisPost = jQuery(e.target).parents(".agent-dashboard-listing-card")
sendRequest('properties-for-sale');
});
const sendRequest = (requestUrl) => {
jQuery.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader('X-WP-Nonce', msSiteData.nonce);
},
url: `https://mallorca-select.com/wp-json/wp/v2/${requestUrl}/${thisPost.data('id')}`,
type: 'DELETE',
success: function () {
alert(" Listing Deleted Successfully! ");
},
error: function (request, error) {
console.log(arguments);
alert(" Can't do because: " + error);
}
});
};
To do what you require you can use another data attribute to hold the post type URL route - as you already are for the id:
jQuery($ => {
$(".delete-listing-btn").on("click", e => {
let $button = $(e.target);
let $thisPost = $button.parents(".agent-dashboard-listing-card");
let url = `https://example.com/wp-json/wp/v2/${$button.data('post-type')}/${$button.data('id')}`;
console.log(url);
// your AJAX request here...
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<button class="delete-listing-btn" data-post-type="post-type-1" data-id="1">Post Type 1</button>
<button class="delete-listing-btn" data-post-type="post-type-2" data-id="2">Post Type 2</button>
<button class="delete-listing-btn" data-post-type="post-type-3" data-id="3">Post Type 3</button>
<button class="delete-listing-btn" data-post-type="post-type-4" data-id="4">Post Type 4</button>

Sending a variable from JavaScript to Java

I've created a game that collects a User's time on the browser with JavaScript. What I'd like to do is grab that JavaScript data and send it to the backend, which is written in Java (I'm using a local server running on Tomcat). How can I accomplish this?
I've looked into AJAX and here is what I've come up with...
var myTime = // however long it took for user to win game
var data = {}
data["myTime"] = myTime;
$.ajax({
type : "POST",
url : "/path-to/hosting/save",
data : JSON.stringify(data),
dataType : 'json',
timeout : 100000,
contentType:'application/json',
success : function(data) {
console.log("SUCCESS: ", data);
},
error : function(e) {
console.log("ERROR: ", e);
},
done : function(e) {
console.log("DONE");
}
});
When I finish the game, I receive this error on the console:
statusText:"parsererror"
My initial thought was that I didn't form my JSON correctly, but I am not sure. Any help would be appreciated. Thanks in advance!
As your code it seems like myTime is a single value why you store it in array you can pass that as follows
var myTime = // however long it took for user to win game
//var data = {}
//data["myTime"] = myTime;
$.ajax({
type : "POST",
url : "/path-to/hosting/save",
data : JSON.stringify({
'myTime': myTime
}),
dataType : 'json',
timeout : 100000,
contentType:'application/json',
success : function(data) {
console.log("SUCCESS: ", data);
},
error : function(e) {
console.log("ERROR: ", e);
},
done : function(e) {
console.log("DONE");
}
});

MVC5 Ajax update

I have a dropdown with selection id StaffId. What I am doing is once an item is selected I want to pass on the StaffId to controller to fetch records in a database using the staffId. This is giving an error on page load without passing the StaffId to the controller. below is the snippet
controller
[HttpPost]
public PartialViewResult GetStaffPosts(int? id)
{
var sPost = db.StaffPosts.Where(a => a.StaffId == id.Value);
return PartialView(sPost.ToList());
}
<div id="divPartialView">
#{Html.RenderPartial("GetStaffPosts");}
</div>
<script type="text/javascript">
$(document).ready(function () {
$("#StaffId").change(function (event) {
var options = {};
options.url= "/StaffPost/GetStaffPosts/" + $(this).val(),
options.data= { id: $(this).val() },
options.cache= false,
optionstype= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest) {
$("#divPartialView").html(data); // HTML DOM replace
$.ajax(options);
}
});
});
</script>
Your current code is not actually making an ajax call on the change event because you are invoking the $.ajax(options); call inside the success callback of the options object. You are not calling the $.ajax method on the change event!
This should work (assuming your controller code is returning a 200 response).
$("#StaffId").change(function (event) {
var options = {};
options.url= "/StaffPost/GetStaffPosts/" + $(this).val(),
options.data= { id: $(this).val() },
options.cache= false,
options.type= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest) {
$("#divPartialView").html(data); // HTML DOM replace
}
$.ajax(options);
});
You may also simplify your code using the $.post method.
$("#StaffId").change(function() {
$.post("/StaffPost/GetStaffPosts/",{ id: $(this).val() } ,function (data) {
$("#divPartialView").html(data);
});
});
Or even using the $.load method and a one liner
$("#StaffId").change(function(event) {
$("#divPartialView").load("/StaffPost/GetStaffPosts/", { id: $(this).val() });
});
Hi just put your ajax call outside of the success function and make an url like the below code and try again
Your changed code:
<script type="text/javascript">
$(document).ready(function () {
$("#StaffId").change(function (event) {
var options = {};
options.url= "../StaffPost/GetStaffPosts,
options.data= { id: $(this).val() },
options.cache= false,
optionstype= "POST",
options.dataType= "html",
options.success= function (data, textStatus, XMLHttpRequest)
{
$("#divPartialView").html(data); // HTML DOM replace
}
$.ajax(options);
});
});
</script>

Sending a JSON object to Django backend through AJAX call

I have the following code (jQuery) to create a json file:
$( ".save" ).on("click", function(){
var items=[];
$("tr.data").each(function() {
var item = {
item.Code : $(this).find('td:nth-child(1) span').html(),
itemQuantity : $(this).find('td:nth-child(4) span').html()
};
items.push(item);
});
});
Now this is my AJAX function:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ //I need my items object, how do I send it to backend server (django)??
calltype:'save'},
dataType: "application/json", // datatype being sent
success : function(jsondata) {
//do something
},
error : function() {
//do something
}
});
}());
Now, my doubt is how do I send the 'item[]' object that I created to the backend? I do need to send both the item[] object and the variable 'calltype' which signals what made the AJAX call, as I have the same Django View (its the Controller equivalent for Django) in the backend being called by different AJAX functions.
How will my AJAX function look like?
Hey guys just got my answer right.
I used the following ajax function to get it right:
(function() {
$.ajax({
url : "",
type: "POST",
data:{ bill_details: items,
calltype: 'save',
'csrfmiddlewaretoken': csrf_token},
dataType: 'json',
// handle a successful response
success : function(jsondata) {
console.log(jsondata); // log the returned json to the console
alert(jsondata['name']);
},
// handle a non-successful response
error : function() {
console.log("Error"); // provide a bit more info about the error to the console
}
});
}());
So, this is sort of a self answer!!! :) Thanks a lot SO!!

Fetch http status code in jquery

Below is an existing jquery code in our code base.
$("#download_").click( function() {
$("#error").html('');
$.ajax({
type : "GET",
cache : false,
async : false,
url : "/download",
success : function(data) {
var json_obj = $.parseJSON(data);
if(json_obj !== undefined && json_obj != null){
if(json_obj.download=="success"){
location=json_obj.url;
}
}
},
error : function(data) {
// TODO
$("#error").html(failed);
}
});
});
Here, In case of error (marked as TODO), I want to check if the http status is 404, then I need to redirect user to different url.
Can any one tell me how do I get the http status in this error: function(data) method?
Thanks!
Did you even look at the docs?
$.ajax({
...
statusCode: {
404: function() {
alert('page not found');
}
}
});
try: statusCode
from documentation:
$.ajax({
statusCode: {
404: function() {
alert('page not found');
}
}
});
http://api.jquery.com/jQuery.ajax/
EDIT:
Now that I think about it, do you only want to redirect if it's a 404? What about other error codes?

Categories

Resources