I am newbie to AngularJs. I am using AngularJS as front end and Laravel As backend.
I have a situation where I want page to be refreshed on ajax success (when user post data).
I have template index.blade.php like this :
#extends(layout)
#section
header page
post page
main page
footer page
#endsection
Now thing is that User is posting update from post page and
on that success i want data to be refreshed which is on main page
function addpost ($scope, $http){
$scope.loadData = function(){
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8';
$http.post( baseurl+"alldata").success(function(data)
{
$scope.posts = data;
});
}
$scope.addComment = function(post){
if("undefined" != post.hoot){
// Angular AJAX call
$http({
method : "POST",
url :baseurl+ "url",
data : "post="+post
}).success(function(data){
$scope.posts = data;//json response
// here i want page to be refreshed or div refresh of sub-main page
});`
$scope.post = ' ';`
}
}
$scope.loadData();
}`
Now thing is that if i am posting data from other sub page and then showing it on other sub page. Iam calling addcomment to add posted data in model and then loaddata() to get all data from model for ng-repeat in a view.
if i am going to fire watch event . it will keep on refreshing model thus view data. Suppose i am working on comment section where we can like , dislike and comment on post. and i want to use ng-click event inside ng-repeat(which is refreshing view).
Test.controller('Testing',['$scope', '$http', function($scope,$http){
$scope.products = {};
$http.post( baseurl+"ajax/getall").success(function(data)
{
$scope.products = data;
});
$scope.$watch("products", function(newValue, oldValue) {
if (newValue === oldValue) { return; } // AKA first run
$scope.products= newValue;
});
});
$scope.Hello= function(){
alert("hello");
}
}]);
It will keep on refreshing page and thus don't click event inside ng-repeat which is ng-click.
I have fired ng-click="Hello()" event but it doesn't fire.
You can register a listener to $scope.data in any part of the application that had a reference to scope. This way, everything will keep up to date when data is updated.
Like so:
$scope.$watch('data', callback)
You are thinking the jQuery way. You have to put that away and think data-binding and angularjs.
To do what you are asking is pretty easy if you think the angularjs way.
First of all, you need the php page of yours to print out a html page with a {{updateMe}}
then in your code
.success(function(data){
$scope.updateMe = data
......
Related
I am trying to reload data tables that have been inserted into tabs.
Please refer to question: AJAX Update DataTable after On Success
A PHP class userX.php has 3 data tables with client-side implementations. I am able to change a row of the first table using a button, once it is done the record will go to tab 2 -> and the content of it table two. I am changing the status now using AJAX as this:
$(".changeStatus").click(function(event){
if(confirm("Are you sure changing status?")){
event.preventDefault();
var status = "In Production";
var id = $(this).attr('data-id');
$.ajax({
url : 'dbo.php',
method : 'POST',
data : {status : status , id : id},
success : function(data){
$('tr#'+id+'').css('background-color', '#ccc');
$('tr#'+id+'').fadeOut('slow');
}
});
}
else{
return false;
}
});
In the meantime it has to be updated in the tab 2 table as well. I have tried achieving this using div contents; neither of them seems working. What am I missing? I am open to suggestions.
The table can simply be reloaded by reinitializing method of the datatable also reloading it through its built in AJAX. The below code block would help.
$(document).on('click','#ChangeNext',function(event){
if(confirm("Are you sure changing status?")){
event.preventDefault();
var statusid = $(this).attr('data-id');
$.ajax({
url : 'dbo.php',
method : 'POST',
data : {statusid : statusid},
success : function(data)
{
$('#exampleone').DataTable().ajax.reload();
}
});
}
else{
return false;
}
});
the best way for putting data in a DataTables with ajax requests, is DataTables ajax api that you can see it in following link:
DataTables Ajax sourced data
jQuery sample:
jQuery('.changeStatus').click(function(event){
$('#example').DataTable({ ajax: 'data.json' });
});
JSON Sample:
{
"data": [
[
"Roshan Zaid",
"Stackoverflow user",
"New member"
],
[
"AmirAli Esteki",
"Stackoverflow and AskUbuntu user",
"New member"
]
]
}
the response of your ajax requests should be json by default
I'm learning Laravel and I have a view with a contact list and inside of this table I have a button to display more details about the clicked item. I want to return a view inside the actual view, I don't want to go to another page.
Someone can explain me how can I do that and show me examples of that if it is possible?
I already try do that using ajax but I don't now how can I return a view without go to other page.
$("#detailsItemSize").click(function()
{
var itemId = $(this).attr('data-id');
alert("details");
alert(url);
$.ajax
({
method: 'GET',
url: url + "/" + itemId,
data: {'itemId': itemId, _token: token }
});
.done(function (msg)
{
console.log(msg['message']);
});
});
Best regards
The basic premise is to have a route that renders your partial view:
Route::get('item/{item}', function($itemId){
$someitem = Item::findOrFail($itemId);
return view('partial', compact('someitem'));
});
//partial.blade.php
<h1>Items id is {{$someitem->id}}</h1>
//main view
<div id="details></div>
//js
$.get('/item/27', function(response){
$('#details').html(response);
});
the #details div in the page will contain <h1>the items id is 27</h1> when the ajax call returns
In order to delete a person from the database, I would like to check its connections with other objects like inventories before deleting then display a bootstrap dialog message within the same page.
Using CodeIgniter, I have a page named "Person's details" that has a link to check these connections like so:
<a class="btn btn-custom" href="person/checkConnections/<?=$ID_Person?>">Delete</a>
In the controller "person", the method "checkConnections" looks like:
public function checkConnections($ID_Person)
{
$data["strConnections"] = "3 connections with inventories found";
$this->load->view("person/showdetails", $data)
// launch the dialog box #deleteMsg
???
}
How can I launch the bootstrap dialog box which has an id="deleteMsg" and which is in the "Person's details" page?
if it was an html url, the url would look like : http://mywebsite/person/showdetails/134#deleteMsg. But how can I have the same result using the codeIgniter method to render a view?
I can check these connections when loading the page the first time. But it wouldn't be efficient to do it every time since the delete action is rarely used.
You can use ajax to call the delete method and then show the response in a model form like below.
$('.btn-custom').click(function(e){
var url = $(this).attr('href');
$.ajax({
type: 'GET',
url: url,
success: function(rtn)
{
//load the bootstrap model setting the rtn as html content.
}
});
return false;
});
the controller should return the html output of your view.
public function checkConnections($ID_Person)
{
$data["strConnections"] = "3 connections with inventories found";
echo $this->load->view("person/showdetails", $data, true);
}
note the third parameter true of the view load method, this will return the output of the view.
I thought the easiest way would be to explain it with an image of what I have.
Summary -
I have a form to submit posts (pretty much like what you would find in twitter). Within each post there is an <ol> where comments to that post will reside.
Problem -
When I submit the first comment (button submit 2 in the picture), it doesn't call the ajax and just goes to a page where it presents me the php output of the comment. It seems it is not reloading or aplying DOM events to that portion of code. If I go back, the comment is presented (because it refreshs the page) and when adding the 2nd comment, everything goes normal, as expected. The problem is just the first comment.
Flow -
1) insert new post
2) click the textarea, put some text and press submit
3) Jumps to a page where php output for comment is presented
3a) no ajax call is done. It never enters the code
Could you please help me out understand what is going on? Thanks in advance.
In case you need more of the code just tell me.
JS (post_comment.js - associated with submit 2 in picture. I use ajaxForm - jquery form plugin - though I also tried with the standard .ajax call and the result is the same)
$(function () {
var options = {
success: function (html) {
var arrHTML = html.split(',');
var postId = $.trim(arrHTML[0]);
var html_code = arrHTML[1];
$('ol#post_comment_list' + postId).load(html_code);
//$('ol#post_comment_list'+postId 'li:first').slideDown('slow');
$('.footer-post').hide();
$('.comments-feed').delay(2000).slideUp({
duration: 1000,
queue: true
});
$('.small-textarea-main-feed').removeClass('set-large');
resetForm($('.footer-comment'));
},
error: function () {
alert('ERROR: unable to upload files');
},
complete: function () {
},
};
$(".footer-comment").ajaxForm(options);
function ShowRequest(formData, jqForm, options) {
var queryString = $.param(formData);
alert('BeforeSend method: \n\nAbout to submit: \n\n' + queryString);
return true;
}
function resetForm($form) {
$form.find('input:text, input:password, input:file, select, textarea').val('');
$form.find('input:radio, input:checkbox')
.removeAttr('checked').removeAttr('selected');
}
});
I'm looking to find out how I can accomplish this next task. I have a controller that loads a view with a table that lists pages in my database. In every row that is made in the table there is a spot for a icon that when clicked will do one of two things.
If the user does not have javascript enabled:
Clicking on the icon will redirect to the delete function in the controller with id of the page as a paramter
Delete controller function will run delete function in model sending page id to delete model function
Delete function in model will delete the page from the database and when returned back to page controller delete function it will redirect back to index function to show list of pages table again.
After redirect it will display a title and message as to a success/fail.
If the user does have javascript enabled:
Send a post to the delete function in controller with jquery post
method with the data page id
Delete controller function will run delete function in model sending page id to delete model function
Delete function in model will delete the page from the database and when returned back to page controller delete function it create a message array for the json object to return to the success function of the post request.
A message with my pnotify plugin will create a message that is formed from that json object and display it to the user
What I would like to know is with doing this how to properly accommodate for these two scenarios? I have started attempting this but would like to some clarification if I have made a mistake so far.
<?php
// Controller delete function
public function delete($content_page_id)
{
if (isset($content_page_id) && is_numeric($content_page_id))
{
$content_page_data = $this->content_page->get($content_page_id);
if (!empty($content_page_data))
{
//update is ran instead of delete to accompodate
//for the soft delete functionality
$this->content_page->update('status_id', 3);
if ($this->input->is_ajax_request())
{
//return json data array
}
}
}
}
?>
Global JS file to be used for multiple tables with delete buttons
/* Delete Item */
$('.delete').click(function(event) {
event.preventDefault();
var item_id = $(this).attr('rel');
$.post(<?php echo current_url(); ?>'delete', { item_id : item_id }, function(data)
{
if (data.success)
{
var anSelected = fnGetSelected( oTable );
oTable.fnDeleteRow( anSelected[0] );
}
}, 'json');
});
I think that you should have two functions in PHP:
public function delete($content_page_id) {
// Your delete code
return "a string without format";
}
public function deleteAjax($content_page_id) {
return json_encode($this->delete($content_page_id));
}
So, when the user has JS enabled, you call deleteAjax passing a parameter in your $.post function to let PHP know that JS is enabled:
$.post(<?php echo current_url(); ?>'delete', { item_id : item_id, js: 1 }, function(data)
{
if (data.success)
{
var anSelected = fnGetSelected( oTable );
oTable.fnDeleteRow( anSelected[0] );
}
}, 'json');
And if JS is disabled, call the other function. You should use an AJAX specialized controller instead a function in the same class.
1) As far as "displaying a message" - the view-itself could be ready for a 'message' if one exists. Bringing us back to...
2) Can you have your delete function return the message you want displayed? Your AJAX approach will ignore this message while your View will display it...
3) I agree that your 'Controller delete function' should 'finish' with different outcomes based on whether the request is AJAX or not. I like what #Skaparate (answered Aug 30 at 18:37) was doing with adding: js:1 In your delete function, you could use this in a simple conditional:
if js = 1
header('HTTP/1.1 200');
else
call view and include/pass-in the 'message'