How can I pass html array to laravel controller using ajax request?
I did like below in my view:
<form>
<table class="table table-striped border-top" id="modalTable">
<thead>
<tr>
<th>start-time</th>
<th></th>
<th>end-time</th>
<th>reserve</th>
</tr>
</thead>
<tbody id="change">
<tr>
<td name="startTime[]"></td>
<td></td>
<td name="endTime[]"></td>
<td name="reserved[]"></td>
</tr>
</tbody>
</table>
<input type="hidden" id="token" value="{{ csrf_token() }}">
</form>
and the ajax code is below:
<script>
$(document).on('click','.btn',function(){
var startTime = $('#startTime').text();
//alert(startTime);
var endTime = $('#endTime').text();
//alert(endTime);
var token = $('#token').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
})
$.ajax
({
url:'reservePrivateChat',
type:'post',
data:{startTime:startTime,endTime:endTime,'_token':token},
success:function()
{
alert('success');
},
error:function()
{
alert('error');
}
})
});
</script>
and in controller I did like below :
public function reservePrivateChat(Request $request)
{
$startTime = $request->startTime;
print_r ($startTime);
$endTime = $_POST['endTime'];
print_r($endTime);
}
In controller there is no difference between $request and $_POST. Both return just one column of the table that sent by ajax but I want all values of the columns...
You can't do what you're trying to do. You have to manually construct the array based on the correct names of the table data. The #startTime selector does not exist because it's looking for an element with id startTime but you only have an element with name startTime[].
You an probably create an array as follows:
var startTime = [];
$("[name='startTime[]]'").each(function () {
startTime.push($(this).text());
});
var endTime = [];
$('[name='endTime[]]'').each(function () {
endTime.push($(this).text());
});
var token = $('#token').val();
//No need for ajax setup if you're sending the token as a parameter
$.ajax({
url:'reservePrivateChat',
type:'post',
data:{ startTime:startTime,endTime:endTime,'_token':token},
Related
I am trying to alert something but on click function is running only once on the first button. but I have buttons on many rows.
I am fetching Data through Laravel from Database in a table. Only one button runs a function, then nothing happens with other buttons.
Jquery:
jQuery(document).ready(function(e) {
$('#restore-data').on('click', function(e) {
var val = $("#thisr").attr('value');
alert(val);
});
});
View:
<table id="recover-table" class="table" >
<thead>
<tr class="bg-info">
<th>Teacher Name</th>
<th>Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($trashs as $trash)
<tr id="thisr" value="{{$trash->id}}">
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap "><button type="submit" class="" name="id"
value="{{$trash->id}}" id="restore-data">Delete</button></td>
</tr>
#endforeach </tbody></table>
Right now even alert is not working, but I want to achieve Refresh table after a record is deleted from Table.
Update: Now Alert is working fine, but when I delete a record by pressing a button, only one row is deleting. the function runs once.
Complete Js:
jQuery(document).ready(function(e) {
$('#restore-data').on('click', function(e) {
let teacher_id=$(this).attr('value');
console.log('Restore button clicked!')
e.preventDefault();
$.ajax(
{
url: "/teachers/recover/" + $('#restore-data').attr("value"),
type: 'GET', // Just delete Latter Capital Is Working Fine
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: teacher_id,
success: function (data) {
console.log(data.msg);
console.log(teacher_id);
if(data.msg){
$('#thisr').remove();
$('#response').empty();
$(".toast").toast('show');
$('#response').append(data.msg);
}
},
error: function (xhr) {
console.log("Error Restoring Record");
//console.log(xhr.responseText);
},
});
});
});
You can try to use class 'restore-data'
$(document).ready(function(e) {
$(document).on('click', '.restore-data', function(e) {
var val = $('#thisr').val();
alert(val);
});
});
As id should be unique for each element.
You can try something like
#foreach($trashs as $trash)
<tr>
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap ">
<button type="button" data-trash-id="{{$trash->id}}" class="restore-data">Delete</button>
</td>
</tr>
#endforeach
and JS as
$(document).on('click', '.restore-data', function(e) {
var trash_id = $(this).attr('data-trash-id');
alert(trash_id);
});
Change this line.
var val = $("#thisr").attr('value');
to (since you have value attribute in button):
var val = $(this).attr('value');
or (since you have value attribute td):
var val = $(this).parent('tr#thisr').attr('value')
To remove a row.
$('#restore-data').on('click', function(e) {
var _this = $(this);
...
if(data.msg){
_this.parent('tr#thisr').remove();
....
Also change button type to button.
<button type="button" class="" name="id"
value="{{$trash->id}}" id="restore-data">Delete</button></td>
You gave same id to all button and id must be unique of particular button so you can define unique id with key of array and pass it to Function
#foreach($trashs as $key=>$trash)
<tr id="thisr{{$key}}">
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap ">
<button type="button" class="" name="id" value="{{$trash->id}}" id="restore-data{{$key}}" onclick="restoreData({{$key}})">Delete</button>
</td>
</tr>
#endforeach
function restoreData(key){
var val = $("#restore-data"+key).attr('value');
alert(val);
// you can use either
$("#restore-data"+key).closest('tr').remove();
// OR
$('#thisr'+key).remove();
}
I have UI with Input field and Submit Button,And After Entering Number in field and clicking on Submit Button. I want this to go to first.php file and second.php depends on the first.php response. At the end I want to show to value from second.php, Can you please help me on this.
And I am using AngularJS with PHP And I am creating 2 functions with in one controller and calling 2 functions at time by clicking on button Can you please suggest me on the approach?
HTML Code
<html>
<div ng-controller="get_controller">
<input type="text" ng-model="accountnumber" name="accountnumber" class="form-control search-query" placeholder="Enter Account Number">
<span class="input-group-btn">
<button type="submit" ng-click="sendAccountNumber();geValues()" class="btn btn-primary">Submit</button>
</span>
</div>
<div ng-controller="get_controller">
<table>
<tbody>
<tr>
<th ng-repeat="list in personDetails">{{list.Name}}
</th>
</tr>
<tr>
<td class="features" ng-repeat="list in personDetails">{{list.Location}}
</td>
</tr>
</tbody>
</table>
</div>
</html>
AngularJS
var app = angular.module('myApp', ["ngTable"]);
app.controller('get_controller', function($scope, $http) {
$scope.sendAccountNumber = function() {
var request = $http({
method: "post",
url: "first.php",
data: {
accountnumber: $scope.accountnumber
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
/* Check whether the HTTP Request is successful or not. */
request.success(function(data) {
console.log("Account Number " + data + " Sent to first.php");
});
}
$scope.geValues = function() {
$http({
method: 'POST',
url: 'second.php'
}).success(function(data) {
$scope.post = data;
$scope.personDetails = Employee;
})
},
});
You can call your next function call in the promise of the first call in the following way:
//First function
$scope.firstFunction = function(){
$http({
method: 'POST',
url: 'first.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: data
}).then(
function (response) {
var data = response.data;
$scope.secondFunction(data);
// not relevant
}, function (error) {
var data = error.data;
// not relevant
});
}
//Second function
$scope.secondFunction = function(data)
{
$http({
method: 'POST',
url: 'second.php',
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: data
}).then(
function (response) {
var newData = response.data;
// not relevant
}, function (error) {
var newData = error.data;
// not relevant
});
}
And call a one function firstFunction() on button click only.
<button type="button" ng-click="firstFunction();" class="btn btn-primary">Submit</button>
FYI,
I would recommend to use ng-submit() event for form to submit the form data rather then submitting by submit event of your form.
And one more thing, why would you request two ajax calls ?
You can do both the server side operations in single call only.
Hope this helps you :)
I need to refresh the table to show newly added row after sending the data from $http method. Below is my working code for adding the form values to mysql table. Appreciate if anyone can help me out with the angular way to achieve this.
JS Code:
var myApp = angular.module('myApp', ['ngRoute']);
myApp.controller('bookmarkCtrl', function($scope, $http) {
$scope.addThis = function() {
$http({
url: "addbookmark.php",
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: $.param({
bookmarktitle: $scope.bookmarktitle,
bookmarkurl: $scope.bookmarkurl
})
}).success(function(data, status, headers, config) {
//refresh the table after success
}).error(function(data, status, headers, config) {
});
}
});
HTML
<div class="panel-body" ng-app="myApp" ng-controller="bookmarkCtrl">
<input ng-model="bookmarktitle" type="text" class="form-control" required>
<input ng-model="bookmarkurl" type="text" class="form-control">
<button type="button" class="btn btn-default" ng-click="addThis();">Submit</button>
<table class="table table-responsive">
<thead>
<tr>
<th>...</th>
</tr>
</thead>
<tbody>
<!-- repeat row -->
<tr>
<td>
<?php echo $row['bookmark_title'] ?>
</td>
</tr>
<!-- repeat row -->
</tbody>
</table>
</div>
#ismailvtl, angular is a client-side library, so typically the data would be populated through an ajax call from the client. In order to dynamically add a row, the data has to be accessible to the controller.
$scope.bookmarks = [];
$scope.getBookmarks = function() {
$http.get('/bookmarks').then(function(response) {
// should do validation here
$scope.bookmarks = response.data
}
}
$scope.getBookmarks();
Then, in your html, it should look like
...
<tr ng-repeat="bookmark in bookmarks">
<td>{{bookmark.bookmarktitle}}</td>
<tr>
...
Then, lastly, in your addThis() function:
$scope.addThis = function() {
$http({
url: "addbookmark.php",
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: $.param({
bookmarktitle: $scope.bookmarktitle,
bookmarkurl: $scope.bookmarkurl
})
}).success(function(data, status, headers, config) {
var bookmark = {
bookmarktitle: data.bookmarktitle,
bookmarkurl: data.bookmarkurl
}
$timeout(function() {
$scope.bookmarks.push(bookmark)
}
}).error(function(data, status, headers, config) {
// handle error here
});
}
Alternatively, you can assign the bookmarks array directly in the view from the php using ng-init (something like ng-init="bookmarks=[{bookmarktitle: 'titlea',bookmarkurl: 'urla'},...]" with the values being supplied by php.
I'm stuck in multiple input. My code is not showing all data. below is the html I am using:
<form id="matkul" class="form-horizontal" method="POST">
<table class="table table-condensed">
<thead>
<tr>
<th>Matakuliah</th>
<th>Data Lain</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</form>
<button id="post" type="submit">Save</button>
<button id="get">Get Data!</button>
below is the code to get the data
<script>
$(document).ready(function() {
$("#get").click(function() {
var url = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22https%3A%2F%2Funisys.uii.ac.id%2Fuii-ras%2Fmatakuliah.asp%3Fidx%3D1%26session_id%3DxxbKiKJawuyrbaaiJ3Kabybabi3JJiKJrJyb3wiuKbbry0JbKiKbKr0yyrKK15933511%26no_mhs%3D%22&format=json';
$.getJSON(url,
function(data) {
var id = data.query.results.body.table.tr.td.table.tr[2].td.table.tr;
for (var i = 1; i <= id.length; i++) {
$("<tr> <td> <input name='fmatakuliah' value='"+id[i].td[1].a.content+"'> </td> <td> <input name='fdata' value='" + id[i].td[1].a['href'] + "'> </td> </tr>").appendTo("#matkul tbody");
};
});
});
});
</script>
from the above code output will be
Matakuliah Data Lain
StringOne OtherData
StringTwo OtherData
below is the ajax post code, but when it is already sending the data, the alert does not show all the data
<script type="text/javascript">
$(document).ready(function(){
$("#post").click(function(){
string = $("form").serialize();
alert(string); // this alert is normal, show all data
$.ajax({
type: "GET",
url: "/save.php",
data: string,
success: function(data){
alert("Success!"+data); //this not normal, not show all data
}
});
});
});
</script>
below is the code on save.php
print_r($_GET);
The latest response is showing like this
Array
(
[fmatakuliah] => Wide Area Network
[fdata] => matakuliahdetail.asp?session_id=xxbKiKJawuyrbaaiJ3Kabybabi3JJiKJrJyb3wiuKbbry0JbKiKbKr0yyrKK15933511&mk=52323605&kur=2010
)
My question is how to show all data and save it to the database?
It looks like you need to change the AJAX type from GET to POST:
$.ajax({
type: "POST",
url: "/save.php",
data: string,
success: function(data){
alert("Success!"+data); //this not normal, not show all data
}
});
Trying to display all users from a MySQL database in Knockout and CodeIgniter. I'm getting a json response back from the server but Knockout isn't displaying the Json data.
I keep getting:
Uncaught ReferenceError: Unable to parse bindings.
Bindings value: text: id
Message: id is not defined
Html:
<!-- Users -->
<table class="table table-condensed table-striped table-bordered table-hover">
<thead>
<tr><th>User Id</th><th>Name</th><th>Email</th><th>Role</th></tr>
</thead>
<tbody data-bind="foreach: users">
<tr>
<td data-bind="text: id"></td>
<td><input data-bind="value: name" /></td>
<td><input data-bind="value: email"/></td>
<td><select data-bind="options: $root.roles, value: role, optionsText: 'role', optionsValue: 'role'"></select></td>
<td><a href="#" data-bind="click: $root.removeUser" class='icon-remove'></a></td>
</tr>
</tr>
</tbody>
</table>
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
Knockout:
<script type="text/javascript">
function User(data) {
this.name = ko.observable(data.name);
this.email = ko.observable(data.email);
this.id = ko.observable(data.id);
this.role = ko.observaveble(data.role);
}
function UserListViewModel(data) {
// Data
var self = this;
self.users = ko.observableArray([]);
// Operations
self.addTask = function() {
self.tasks.push(new Task({title: this.newTaskText()}));
self.newTaskText("");
};
self.removeTask = function(task) {
self.tasks.remove(task)
};
// Load initial state from server, convert it to Task instances, then populate self.tasks
$.get("/sws/users/index", function(data) {
var mappedUsers = ko.mapping.fromJSON(allData);
self.users(mappedUsers);
});
}
ko.applyBindings(new UserListViewModel());
</script>
Json:
{"users":[{"id":"1","email":"example#gmail.com","password":"tacos","permissions":null,"activated":"1","activation_code":null,"activated_at":"2013-09-23 20:19:42","last_login":"2013-09-23 20:19:42","persist_code":null,"reset_password_code":null,"name":"Chris","created_at":"2013-09-23 04:17:24","updated_at":"2013-09-23 07:16:23"}]}
You're passing allData as an argument to the mapping, but it isn't defined anywhere. You want data.users instead (not data because then ko.mapping.fromJSON will return a single object with one key, users whose value will be an observableArray; you'll confuse Knockout if you try to use that object as the value of another observableArray, namely self.users).
Switching to this .ajax call seemed to resolve the issue.
// Load initial state from server, convert it to User instances, then populate self.users
$.ajax({
url: '/sws/users/index',
dataType: 'json',
type: 'POST',
success: function (data) {
self.users(data['users']);
console.log(data['users']);
}
});