Send Table cell value to Servlet Through ajax - ajax

I need to post values from a table cell to a servet through Ajax but the response is returning a null. My Javascript is not that strong and I am certainly doing something wrong and need some direction. Below are my JSP and Ajax script:
**My JSP code**
<td><button type="button" class="btn btn-default btn-md" class="itemData" tableData="${item}" onclick="saveData()"><span class="glyphicon glyphicon-save"></span></button> </td>
**My Ajax code**
function saveData(){
$(document).ready(function(){
var dataID = $(this).attr('tableData');
$.ajax({
url : 'DataCtrlServlet',
type: 'Post',
data : dataID,
success : function(responseText) {
$('#submissionSuccessContainer').text(responseText);
}
});
return false;
});
}

Romve return false; and $(document).ready ,also you need to change the data format to pass the parameter correctly
function saveData(){
var dataID = $(this).attr('tableData');
$.ajax({
url : 'DataCtrlServlet',
type: 'Post',
data : {
dataID:dataID
},
success : function(responseText) {
$('#submissionSuccessContainer').text(responseText);
}
});
}

Related

parameter not send in ajax request

I want to call the action method(AddCompare) using an Ajax request at the View,
My problem is that the parameter sent to AddCompare Action always has zero value,
While the parameter value in the function AddToCompare is correct
this is my code
View:
#model IEnumerable<Products>
#foreach (var item in Model)
{
<li>
<div class="left-block">
<div class="quick-view">
<a title="Add To Compare" class="heart" href="#" onclick="AddToCompare(15)"></a>
</div>
</div>
</li>
}
<script>
function AddToCompare(param) {
alert(param); //display correct value 15
$.ajax({
type: "GET",
url: "#Url.Action("AddCompare")",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
id: param
}),
success: function (response) {
var myObject = eval('(' + response.d + ')');
if (myObject > 0) {
$(".errMsg").append("<ul><li>Data saved successfully</li></ul>");
}
else {
$(".errMsg").append("<ul><li>Opppps something went wrong.</li></ul>");
}
$(".errMsg").show("slow");
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
</script>
Controller
public JsonResult AddCompare(int id)
{
//id is zero !!!
int param=id;
}
Where is the problem?
try to use
$.get
this is the syntax
$.get(URL,data,function(data,status,xhr),dataType)
In your AJAX call you don't need to stringify
$.ajax({
// your code
data: {id: param},
Decorate your action method with HttpGet even if it is GET by default. Just a better practice.
[HttpGet]
public JsonResult AddCompare(int id)
{
}
Since you are using a Get verb you can do this:
$.ajax({
type: "GET",
url: "/Controller/Action?ID=" + id,
dataType: "json"
}).done(function (response) {
//response code here
});
Change the controller and the action to your needs and you can add other settings to the ajax if needed.

Delete a record without using form in laravel

Need to delete a record without using form tag. Just pass a id in url and get a id need to process.
Thanks
follow below steps
HTML
Delete
JS
$('a#btnDelete').on('click',function()
{
var thisElement = $(this);
$.ajax({
type: 'post',
url: "{{url('/')}}" + '/deleteRecord/'+thisElement.attr('thisRecordId'),
data : {'_token': '{!! csrf_token() !!}'},
async: false,
success:function(response)
{
console.log(response)
}
});
});
Route
Route::post('deleteRecord/{id}','YourController#deleteRecord');
Controller
public function deleteRecord($id)
{
$findRecord = ModelName::findOrFail($id);
$findRecord->delete();
return 'success';
}
hope you will find your solution !
Try like this
<a type="button" class="label label-danger" href="/user/delete/{{$user->id}}">Delete</a>
Controller method
public function getDelete($id)
{
echo $id;
}

How to add value in a $.ajax url in CakePHP 2

Im trying to use ajax to sent request. I have CartsController and a method add. Please help!
<?php
echo $this->Html->link('Add', array('controller'=>'carts',
'action'=>'add', 'product_id'=>$product['Product']['id']),
array('class'=>'btn btn-primary col-md-offset-4',
'data-product-id'=>$product['Product']['id']));
?>
$('a.btn').on('click', function(e){
var this = $(this);
var product_id = this.data('product-id');
this.html('Item Added');
$.ajax({
url: '/cartphp_cart/carts/add/',
type: 'POST',
data: {product_id: product_id},
success: function(count) {
$('#number-of-items').text(' ' + count);
console.log(count);
}
});
e.preventDefault();
});
If the ajax request is OK, than in your add method of CartsController
you can get it by
if ($this->request->is('post') || $this->request->is('put')) {
debug($this->request->data['product_id'])
}
You should be able to access the data you've put in your ajax request by
if( $this->request->is('ajax') ) {
pr($this->request->data['product_id']);
// Or try printing the whole $this->request->data if you need other items.
}

Rendar partial view in another partial view along with data model using jQuery .Ajax function

I am working on MVC 5 app and I want to render partialView in another partialview with model data using jQuery ajax function. when javaScript function is called, it suppose to send ID of selected element back to controller which is working fine, and in return bring partial view along with model which is not working from following code
<td>
<a href="#" class="SearchUser_Icon Hyperlink_Text" onclick="load_getUserListByGroupID(this)" id=#item.GroupID></a>
</td>
.
JavaScript function
function load_getUserListByGroupID(element)
{
var selectedGroupID = element.id;
alert(selectedGroupID);
$.ajax({
type: "POST",
url: "/UserManagement/SearchUsersByGroupID/",
dataType: "json",
data: { 'GroupID': selectedGroupID },
success: function (viewHTML) {
alert("success");
$("#userContentBlock").html(viewHTML);
},
error: function (errorData) { onError(errorData); }
}).done(function (result) {
alert("done!");
});
}
.
<div id="userContentBlock"></div>
Controller Method
[HttpPost]
public ActionResult SearchUsersByGroupID(string GroupID)
{
int intID = Convert.ToInt32(GroupID);
var UsersListByGroupID = _userServices.GetUsersByGroupID(intID);
return PartialView("GetUsersListByGroup_Partial", UsersListByGroupID );
}
You are returning HTML while expecting JSON in the ajax call. Just remove the dataType: "json" from the settings and everything should work as expected.
jQuery.ajax() dataType:
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response.

Ajax post data attribute to MVC controller action

I'm new in Js. This is my code:
<button class="btn btn-primary" data-id = "#item.Id" id="accept">Accept</button>
var tempId;
$('button.accept').click(function () {
tempId = $(this).attr('data-id')
$.ajax({
type: "POST",
url: "/TabRequest/AcceptRequest",
data: { 'id': tempId },
success: function (msg) {
}
});
})
As you can see I'm trying to post "data-id" to Action. When I click to to button, does nothing. Can anybody help me?
You need
$('button#accept')
instead of
$('button.accept')
Since accept is an ID for the button, use # as selector and you can use . for class selector.
you can see reference for jQuery seletors

Resources