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.
Related
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},
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'm trying to create an ajax form using laravel. The display is a table with names and next to the names are buttons enclosed by forms to do actions.
Here is the html:
<div style="margin-top: 100px;">
<h2>Character settings</h2>
<table class="table table-striped table-bordered table-hover">
<tr>
<th>Name</th>
<th>Map</th>
<th>Move</th>
</tr>
#foreach($chars as $char)
<tr>
<td>{{$char['name']}}</td>
<td>{{$char['map']}}</td>
<td>
{{Form::open(array('action' => 'UsersController#move', 'id' => 'mover'))}}
<input type="hidden" name="charID" id="charID" value="{{$char['id']}}" />
<button type="submit" class="btn btn-small btn-info">Move</button>
{{Form::close()}}
</td>
</tr>
#endforeach
</table>
Here is the javascript ajax processing:
$('#mover').on('submit', function(e){
e.preventDefault();
var $form = $( this ),
method = $form.attr( "method" );
$.ajax({
url: "{{action('UsersController#move')}}",
dataType: "json",
data: $('#charID').val(),
type: method,
success: function (response) {
console.log(reponse['test']);
}
});
});
Here is the controller:
public function move() {
return Response::json(array('test' => 'test'));
exit();
}
The table looks like:
Image here
If I click the first button for Sambte, it works and I see "test" in the console. But when I click the 2nd link it doesn't send as ajax and sends me to a new page with the json object as the content of that page so I see {"test":"test"} in the new page it brought me to.
I can't figure out what's wrong. Hopefully its a small error somewhere.
Thank you
ID's are unique, you need to use a class on the form instead.
'class' => 'mover'
Then just use the class instead of the ID in the selector
$('.mover')
Sidenote, the same needs to be done for the charID, here's how I'd tackle that:
class="charID"
then, in your submit handler:
data: $form.find('.charID').val()
$(document).on('submit','.mover', function(e){
e.preventDefault();
var $form = $( this ),
method = $form.attr( "method" );
$.ajax({
url: "{{action('UsersController#move')}}",
dataType: "json",
data: $(this).serialize(),
type: method,
success: function (response) {
console.log(reponse['test']);
}
});
});
change id=mover to class=mover
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
}
});
I shyly trying to make friends Angular and backend database.
Simple operations. Get database to angular model. Save entry in database, and delete entry.
I'm stacked on DELETE action. When i delete entry that loaded from database it's ok. But when i delete newly created row by push method, i got error.
This occurs because in the model absent id. After inserting entry to database, i trying repeatedly refresh Angular model from database.($http.get) But in this case, a view didn't refresh (only blinks). I saw new entry only refresh page F5.
Help!
Books
<div ng-app="App" ng-controller="MyCtrl">
<table class="">
<th>
<tr style="font-size: 20px">
<td>ID</td>
<td>Name</td>
<td>Price</td>
<td>Action</td>
</tr>
</th>
<tr ng-repeat="book in books">
<td style="width: 200px">{{book.id}}</td>
<td style="width: 200px">{{book.name}}</td>
<td style="width: 50px">{{book.price |currency}}</td>
<td>
<button ng-click="removeItem($index)">Удалить</button>
</td>
</tr>
<tr>
<td></td>
<td><input type="text" ng-model="name"/></td>
<td><input type="number" ng-model="price"/></td>
<td>
<button ng-click="addBook()">Добавить книгу</button>
</td>
</tr>
</table>
</div>
<script>
var App = angular.module('App', []);
App.controller('MyCtrl', function ($scope, $http) {
$http.get('http://ang:8888/index.php?r=site/api2').success(function (data) {
$scope.books = data;
});
$scope.removeItem = function (index) {
var id = $scope.books[index].id;
$scope.books.splice(index, 1);
$http.post('http://ang:8888/index.php?r=site/del2', {id: id});
}
$scope.addBook = function () {
var newBook = ({name: $scope.name, price: $scope.price});
$scope.books.push(newBook);
$http.post("http://ang:8888/index.php?r=site/post2", {name: $scope.name, price: $scope.price})
.success(function (data, status, headers, config) {
console.log("inserted Successfully");
});
$http.get('http://ang:8888/index.php?r=site/api2').success(function (data) {
$scope.books = data;
});
}
})
The problem is due to async nature of all remote calls. You call the post and get methods in sequence without realizing that both are sync in nature. So your post is immediately followed by get.
Change the code for post to
$http.post("http://ang:8888/index.php?r=site/post2", {
name: $scope.name,
price: $scope.price
}).success(function (data, status, headers, config) {
console.log("inserted Successfully");
$http.get('http://ang:8888/index.php?r=site/api2').success(function (data) {
$scope.books = data;
});
});
In the above code you only do get when post is done.