ajax call not sending data correctly - javascript

There is something wrong with the way I am using the ajax call.
When I place the ajax call inside the block, it executes the error function in the ajax callback. When the ajax call is moved outside the block, the variable subcate passed to server is undefined.
var that = this;
var subCate ='' ;
var tr = $('#tbl').find('tr');
//My block
tr.bind('click', function(event) {
var values = '';
tr.removeClass('highlight');
var tds = $(this).addClass('highlight').find('td');
subCate = tds.find('#myid').text();
alert(subCate);
//Tried moving it out of the block but not much of help
$.ajax({
url: '/playground',
type: 'POST',
data: { id: subCate},
success: function(data){
alert("Sub category recvd");
console.log("successs");
},
error: function(jqXHR){
console.log("failed");
alert("failed");
}
});
});
//Ajax call moved here
Here is the node.js server code :
app.post('/playground', function(req, res) {
debug("Inside post(/playground) ",req.body.id);
res.send('ok', 200);
});
Hi Here is the snippet of HTML table, that will give an idea what the jquery code is doing
<div id="category-container">
<div id="category-form">
<h1></h1>
<p id="sub1" class="subheading">Select a category</p>
<!--hr-->
<div style="margin:20px" class="container">
<table id="tbl" class="table table-bordered table-striped">
<thead>
<tr>
<!--th(style='width:40px') #-->
<th style="width:180px">Name</th>
<th style="width:200px">Location</th>
<th style="width:180px">Username</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div id="myid"><a id="item" href="/playground/:0">Electronics</a></div>
</td>
</tr>
<tr>
<td>
<div id="myid"><a id="item" href="/playground/:1">Real Estate</a></div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
Thanks in advance guys !

Add event.preventDefault() at the top of your bind.
Also, I recommend changing the event binding to the following:
$('#tbl').on('click', 'tr', function(event) {
event.preventDefault();
// your code
});

Related

How to reload / refresh the html table using jquery

Below I've added my full Index.cshtml code. In ajax call it's hitting to success method. but i'm not able to reload or refresh the table without page refresh.
The below code is simple while clicking the submit button for filters i'm calling SubmitFilter method it redirect to c# method there i'm storing the results in a JArray variable.. then trying to reload the table...
this is the sample output screen
I've tried these
$("#tblTransactions").DataTable().draw();
$("#tblTransactions").DataTable().ajax.reload();
But it's not working for me. please Let me know if you got any idea ..thanks in advance..
#page
#model IndexModel
#{
Layout = "_Layout";
}
<script>
$(document).ready(function () {
$("#tblTransactions").DataTable();
});
function SubmitFilter()
{
var transactionNumb = $("#transactionNumber").val();
var cardHolderName = $("#cardHolder").val();
alert("SubmitFilter");
$.ajax({
type: "GET",
url: "https://localhost:7197/Transactions?transaction_number="+transactionNumb+"&cardholder="+cardHolderName,
contentType: "application/json; charset=utf-8",
dataType: "html",
success: function (data)
{
}
});
}
</script>
<a style="max-width: 100px;max-height: 40px;margin-left: 10px;" href="#" onclick="SubmitFilter();" class="btn btn-primary">SUBMIT</a>
<table id="tblTransactions" class="table table-bordered table-condensed table-striped table-hover">
<thead>
<th scope="col">Transaction No</th>
<td scope="col">Type</td>
<td scope="col">Status</td>
</thead>
<tbody>
#foreach (dynamic transaction in #Model.Transactions)
{
<tr>
<td>#transaction.transaction_number</td>
<td>#transaction.type</td>
<td>#transaction.status</td>
</tr>
}
</tbody>
</table>

How can I pass an ID from selected table row to my AJAX function that fetching data

Sorry to bother, I'm having a trouble passing and ID to my AJAX function.
I wanted to pass the ID of the selected table row to my AJAX function and use it for my query in my controller
this is the code for my table row
<div class="container">
<h2 style="margin-top: 12px;" class="alert alert-success">Details</h2><br>
<div class="row">
<div class="col-12">
<table class="table table-bordered" id="">
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<td colspan="2">Action</td>
</tr>
</thead>
<tbody id="users-crud">
#foreach($merchants as $merchant)
<tr id="user_id_{{ $merchant->id }}">
<td>{{ $merchant->id}}</td>
<td>{{ $merchant->first_name }}</td>
<td>{{ $merchant->email }}</td>
<td><a id="getData" onClick="getData({{$merchant->id}})" class="btn btn-info">Show</a>
</td>
</tr>
#endforeach
</tbody>
</table>
{{ $merchants->links() }}
</div>
</div>
</div>
upon click show ID should pass it to my AJAX function,
this is the code of the script
<script type=text/javascript>
$(document).ready(function() {
});
function getData(id){
$('#myModal').modal('show');
$.ajax({ //create an ajax request to display.php
type: "GET",
url: "getproducts/",
// dataType: 'json',
data: {id: id}, // This will be {id: "1234"}
success: function (data) {
$("#id").html(data.id);
$("#first_name").text(data.first_name);
}
});
};
</script>
And ID will be use for my query in my controller, this is my controller's code, note that the number 1 in my where query is hard coded, I wanted to put the ID that I get from the selected table
public function getproducts()
{
$merchants = DB::table('merchants')
->select('merchants.*', 'product.product_name as product_names')
->join('product','product.id','=','merchants.id')
// THE NUMBER 1 IS HARD CODED
->where('merchants.id', 1)
->paginate(8);
return response()->json($test, 200);
}
Every method in a Laravel Controller can have arguments "injected" into them, including the Request $request variable. Add this to the top of your Controller after your namespace declaration:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
Then modify your method:
public function getproducts(Request $request) {
...
}
Then, instead of hard-coding the value 1, you pull it from your $request object:
->where('merchants.id', $request->input('id'))
The full documentation can be seen here:
https://laravel.com/docs/9.x/requests#accessing-the-request
Your code seems fine to me. What is the issue you are facing? But you can improve code by bit more.
<td><a id="getData" onClick="getData({{$merchant->id}})" class="btn btn-info">Show</a>
Instead you can use a global class. Also using same HTML id in a class is not good practice.
<td><a class="merchant_info" data-id="{{$merchant->id}}" class="btn btn-info">Show</a>
Now need modification to jQuery code
<script type=text/javascript>
$(document).ready(function() {
$('.merchant_info').click(function(e){
e.preventDefault();
var dataId = $(this).attr("data-id");
// Now do the Ajax Call etc
});
});
</script>

Make button in a table cell to change the color of the row it's in

I'm trying to add a class to the same row that the button I click on is in. I use the jquery "closest" function but it doesn't work. I also tried .parent etc. Anyone know what I do wrong?
<table class="table table-striped table-bordered table-hover">
<tbody class="">
<tr class=''> //I want to change this class
<td style=''><div class='btn btn-xs btn-success cellButton'></td>
</tr>
</tbody>
$('.cellButton').on('click', function(){
$(this).closest("tr").addClass('info')
}
EDIT: I realise now that the code I posted should work (I simplified it before posting), and the problem is because it's referencing $(this) from a different function. This is the real javascript function:
$('.cellButton').on('click', function(){
var formData = {
'action': 'blabla',
'ID': ID,
};
$.ajax({
type: 'POST',
url: 'includes/jquery-actions.php',
data: formData,
dataType: 'json',
error: function (response) {
alert("error!");
},
success: function (response) {
var row = $(this).parents("tr"); //$(this) here not referencing the HTML button?)
row.addClass('warning');
}
})
}
Your version is working. Also
you can use jQuery#parents function. Give it the selector, it will tries to find the closest one and return that element.
parents
$('.cellButton').on('click', function() {
$(this).parents("tr").addClass('info');
});
.info {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped table-bordered table-hover">
<tbody class="">
<tr class=''>
<td style=''><div class='btn btn-xs btn-success cellButton'>Click me</td>
</tr>
</tbody>
closest
$('.cellButton').on('click', function() {
$(this).closest("tr").addClass('info');
});
.info {
color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped table-bordered table-hover">
<tbody class="">
<tr class=''>
<td style=''><div class='btn btn-xs btn-success cellButton'>Click me</td>
</tr>
</tbody>
UPDATED
There is an issue with context.
You can keep your this in above the ajax request and use that variable inside the function
var that = this;
...
success: function (response) {
var row = $(that).parents("tr");
row.addClass('warning');
}
Or just use arrow functions
success: (response) => {
var row = $(this).parents("tr");
row.addClass('warning');
}

How to get JSON with Angular JS

I am trying to get my table filled with data. The url gives json back, but I don't know how to call json in angular.
This my my services.js:
angular.module('OrganisatieApp.services', [])
.factory('organisatieAPIservice', function($resource) {
var organisatieAPIservice = [];
organisatieAPIservice.getOrganisaties = function(){
return $http({
method: 'JSON_CALLBACK',
url: 'http://jbossews-themaopdracht78.rhcloud.com/rest/json/org/Organisaties'
});
}
return organisatieAPIservice;
})
controller.js :
angular.module('OrganisatieApp.controllers', []).
controller('organisatieController',function($scope, organisatieAPIservice) {
$scope.organisatieList = [];
organisatieAPIservice.getOrganisaties().success(function (response) {
//Assign response in Callback
$scope.organisatieList = response();
});
});
app.js:
angular.module('OrganisatieApp', [
'OrganisatieApp.controllers',
'OrganisatieApp.services' ]);
My html div :
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Organisatie naam</th>
<th>Organisatie plaats</th>
<th>Organisatie Curriculum</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="organisatie in organisatieList">
<td>{{$index + 1}}</td>
<td>
<img src="/img/logos/{{organisatie.Organisatie.logo}}.png" />
{{organisatie.Organisatie.orgNaam}} {{organisatie.Organisatie.orgVolledig}}
</td>
<td>{{organisatie.Constructors[0].provincie}}</td>
<td>{{organisatie.curriculum}}</td>
</tr>
</tbody>
</table>
<ng-view></ng-view>
</div>
</div>
</div>
<div class="col-md-6">
<div class="page-header">
<h1>Opleidingsprofiel</h1>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">
<ul class="nav nav-pills" role="tablist">
<li role="presentation">Aantal Organisaties<span class="badge">3</span></li>
</ul>
</h3>
</div>
<div class="panel-body">
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>Organisatie naam</th>
<th>Organisatie plaats</th>
<th>Organisatie Curriculum</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="organisatie in organisatieList">
<td>{{$index + 1}}</td>
<td>
<img src="/img/logos/{{organisatie.Organisatie.logo}}.png" />
{{organisatie.Organisatie.orgNaam}} {{organisatie.Organisatie.orgVolledig}}
</td>
<td>{{organisatie.Constructors[0].provincie}}</td>
<td>{{organisatie.curriculum}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
What am I doing wrong? I know that i am trying to call jsonp but how do I call for json.
Seems like there are couple of problem with your code.
Your jsonp call url must have callback parameter with value JSON_CALLBACK like callback=JSON_CALLBACK & its should be of type jsonp.
Code
return $http.jsonp({'http://jbossews-themaopdracht78.rhcloud.com/rest/json/org/Organisaties?callback=JSON_CALLBACK'});
OR
return $http({
method: 'jsonp',
url: 'http://jbossews-themaopdracht78.rhcloud.com/rest/json/org/Organisaties?callback=JSON_CALLBACK'
});
You should do change $scope.organisatieList = response(); to $scope.organisatieList = response; because the response contains a data.
organisatieAPIservice.getOrganisaties().success(function (response) {
//Assign response in Callback
$scope.organisatieList = response;
});
In this line, just add the "$http" as a dependency of your service, like this:
angular.module('OrganisatieApp.services', [])
.factory('organisatieAPIservice', function($resource,$http) {
//your code here
You need to add this to be able to send the request, otherwise for angular the $http variable is not defined (or imported as a dependency). And yes, like #pankajparkar and #vishnu say, you need to change in your controller this line:
$scope.organisatieList = response();
For this one:
$scope.organisatieList = response;

ajax post from ajax get

I'm trying to post on ajax from a ajax get.
Here is my code below that I'm using:
$(window).load(function() {
$.ajax({
url: "/masterScreen/ajaxdealerpaid/{{$id}}",
type: "GET",
data: {},
success: function(data) {
document.getElementById("dealerPaid").innerHTML=data;
}
});
});
And then i'm trying:
$(".pay").click(function(){
alert('Order #'+id+' has been marked as paid for '+amountPaid+'');
var id = $(this).attr('data-id');
var amountPaid = $("#payAmount_"+id).val()
$.ajax({
url: "/masterScreen/dealermarkpaid/"+id+"/"+amountPaid,
type: "POST",
data: {},
success: function(data) {
alert('Order #'+id+' has been marked as paid for '+amountPaid+'');
location.reload();
}
});
});
My HTML is...
<table style="width: auto;" class="table table-striped table-condensed" border="0" cellspacing="0" cellpadding="0">
<thead class="navbar-static-top" style="display:block; margin:0px; cell-spacing:0px; left:0px;">
<tr>
<th class="span2">Quote ID</th>
<th class="span4">Customer name</th>
<th class="span4">Connection date</th>
<th class="span4">BDM</th>
<th class="span4">Owed</th>
<th class="span4">Amount</th>
<th class="span2"></th>
</tr>
</thead>
<tbody id="dealerUnpaid" style="display:block; overflow:auto; max-height:400px;">
</tbody>
<tfoot id="dealerUnpaidtot" class="navbar-static-top" style="display:block; margin:0px; cell-spacing:0px; left:0px; font-weight: bold;">
</tfoot>
</table>
It displays the data from the first javascript, but I also have this code from the view it's GET from...
<td class="span4"><input type="text" placeholder="Enter Amount" class="payAmount" data=name="amount" data-id="{{$unpaid->id}}" id="payAmount_{{$unpaid->id}}"></td>
<td class="span2"><input type="button" class="btn pay" value="Pay" data-id="{{$unpaid->id}}"></td>
When I press the Pay button it doesn't do anything :/
Any help to make this work would be nice please.
Thanks guys
If I understand correctly, you're loading your markup (including the .pay element) using AJAX and then attempting to bind something to the .pay element's click event. Since the .pay element doesn't exist in the page at the time you're doing the binding, the binding isn't working. Change your binding from:
$('.pay').click(function(){
to
$(window).on('click', '.pay', function(){
That will attach the binding to the window, which has the effect of working even on elements that are added after the window is loaded.
$(".pay").click(function(){...
Works only on already create elements with class pay, it doesnt work on newly created elements by ajax call.
You can use delegate function to handle newly created elements
$("body").delegate(".pay","click",function(event){
event.preventDefault(); // prevent default handlings
alert("Test");
//do other code...
});

Categories

Resources