dynamicly fill table using zpt and ajax as update - ajax

I'm creating a webproject in pyramid where I'd like to update a table every few secondes. I already decided to use ajax, but I'm stuck on something.
On the client side I'm using the following code:
function update()
{
var variable = 'variable ';
$.ajax({
type: "POST",
url: "/diagnose_voorstel_get_data/${DosierID}",
dataType: "text",
data: variable ,
success: function (msg) {
alert(JSON.stringify(msg));
},
error: function(){
alert(msg + 'error');
}
});
}
Pyramid side:
#view_config(route_name='diagnose_voorstel_get_data', xhr=True, renderer='string')
def diagnose_voorstel_get_data(request):
dosierid = request.matchdict['dosierid']
dosieridsplit = dosierid.split
Diagnoses = DBSession.query(Diagnose).filter(and_(Diagnose.code_arg == str(dosieridsplit[0]), Diagnose.year_registr == str(dosieridsplit[1]), Diagnose.period_registr == str(dosieridsplit[2]), Diagnose.staynum == str(dosieridsplit[3]), Diagnose.order_spec == str(dosieridsplit[4])))
return {'Diagnoses ' : Diagnoses }
Now I want to put this data inside a table with zpt using the tal:repeat statement.
I know how to use put this data in the table when the page loads, but I don't know how to combine this with ajax.
Can anny1 help me with this problem ? thanks in adance.

You can do just about anything with AJAX, what do you mean "there's no possibility"? Things become much cleaner once you clearly see what runs where and in what order - as Martijn Pieters points out, there's no ZPT in the browser and there's no AJAX on the server, so the title of the question does not make much sense.
Some of the options are:
clent sends an AJAX request, server does its server-side stuff, in the AJAX call success handler the client reloads the whole page using something like window.location.search='ts=' + some_timestamp_to_invalidate_cache. The whole page will reload with the new data - although it works almost exactly like a normal form submit, not much sense using AJAX like this at all.
client sends an AJAX request, server returns an HTML fragment rendered with ZPT which client then appends to some element on your page in the AJAX success handler:
function update()
{
var variable = 'variable ';
$.post("/diagnose_voorstel_get_data/${DosierID}")
.done(function (data) {'
$('#mytable tbody').append(data);
});
}
client sends an AJAX request, server returns a JSON object which you then render on the client using one of the client-side templating engines. This probably only make sense if you render your whole application on the client and the server provides all data as JSON.

Related

Print fetched data with ajax in codeigniter

I am trying to make chat room with ajax. Till now I am able to store data in db without page load. And also able to fetch data and display onscreen using ajax. Here is what I did with ajax
$('#chat').submit(function(){
var chatmsg = $("#chatmsg").val(); //chat message from input field
var chatroomid = $("#chatroomid").val(); //hidden input field
$.ajax({
url: baseurl+'User_dash/chatmessage', //An function in ctroller which contains only insert query
type: 'post',
data: {chatmsg:chatmsg, chatroomid:chatroomid},
dataType: 'json',
success: function (argument) {
if(argument['status']){
$("#chatting").append(" <li id='"+getvalue+"'>"+argument['msg']+"</li>."); //Here I am printing chat message which resently submitted in database
}
}
},
error: function (hrx, ajaxOption, errorThrow) {
console.log(ajaxOption);
console.log(errorThrow)
}
});
return false;
});
This method with ajax is working fine. But issue I faced here is that, this display chat message only to current user. Not to other side of user whome message is being sent via chat.
To solve this issue I come up with one idea which doesn't seems to be working as I planed. Here it is how I modified my previous ajax code..
$('#chat').submit(function(){
var chatmsg = $("#chatmsg").val();
$.ajax({
url: baseurl+'User_dash/chat', //controller function which contains insert query, after that select query to fetch chat data from db and store in view
type: 'post',
data: {chatmsg:chatmsg},
dataType: 'json',
success: function (argument) {
if(argument['status']){
//Not doing anything here this time
}
},
error: function (hrx, ajaxOption, errorThrow) {
console.log(ajaxOption);
console.log(errorThrow)
}
});
return false;
});
In updated version of script I thought If I will call a controller function which is storing data in view (chat page) then It will run query and print data without page load.
But with this method, I am getting chat onscreen only after page load, although it is getting submit in db with ajax fine.
Here is controller code for my second method with ajax if needed
public function chat(){
if(!empty($_POST['chatmsg'])){
$chatdata = array('CHAT_ROOM'=>$_POST['chatroomid'],
'VENDOR'=>$this->session->userdata('USER_ID'),
'BUYER'=>49,
'MESSAGE'=>$_POST['chatmsg']
);
$this->db->insert('tbl_chat', $chatdata); //inserting data
}
$data['chatroom'] = $this->db->where('CHAT_ROOM', 1)->get('tbl_chat')->result_array(); //fetching data from db
$this->load->view('userDash/chat', $data);
}
How do I achieve to run insert and then select query and print data on screen without page load?
Where I am getting wrong?
I solved my issue earlier, What I did was, just added this jquery script which keep refreshing (every second) a certain div inside page in which I have put query to fetch chat from db and printing them.
setInterval(function(){
$("#chatting").load(location.href + " #chatting");
}, 1000);

Do I sent two requests to the ActionResult?

I have an ASP.net MVC project and depending on the filter options chosen by the user I am sending different ajax requests to the same actionresult, for example:
$(document).on("click", "#filter_reset_button", function () {
var url = "/Admin/Index";
ajaxRequest({
url: url,
type: "get",
data: { reset: true },
successCallback: function () {
window.location.href = url;
}
});
});
Other listeners sent different data, something like:
data: { page: 2, filterUpdate: true }
and so on. The Index ActionResult returns different lists of items, depending on different options chosen in the data and the code works completely fine.
A colleage of mine told me, that my code is actually sending two get requests to the AR everytime, so its not efficient. Is that true? And if its the case, how can I refactor it. to make it just one request? If I let window.location.href = url part out, the site actually doesnt load the server response.
Yes you are doing 2 request in button click. First in Ajax Get, Second in Success Call Back.
But Why are you calling window.location.href = url; success call back. ?
If you want update the page after click, you can do partial updates to page. Check this post.
That is correct 2 request called.
First request when you call AJAX get to Action Index in Admin Controller.
Second request when you set window.location.href = url, it will same as you enter /Admin/Index in browser.
In this case you only need window.location.href = '/admin/index?reset=true' in click function
You can see the post here at this post
Actually on success callback you must change your code accordingly to the above post

AJAX response returns current page

I was searching for a similar issue for a while now, but none of the solutions worked for me (and I couldn't find exactly the same issue).
First of all, the website I'm working on is running on Zend Framework. I suspect that it has something to do with the issue.
I want to make a pretty basic AJAX functionality, but for some reason my response always equals the html of the current page. I don't need any of Zend's functionality, the functions I need to implement could (and I'd prefer them to) work separately from the framework.
For testing purposes I made it as simple as I could and yet I fail to find the error. I have a page "test.php" which only has a link that triggers the ajax call. Here's how this call looks:
$('.quiz-link').click(function(e){
e.preventDefault();
$.ajax({
URL: "/quiz_api.php",
type: "POST",
cache: false,
data: {
'test': 'test'
},
success: function(resp){
console.log(resp);
},
error: function(resp){
console.log("Error: " + reps);
}
});
});
And this quiz_api.php is just:
<?php
echo "This is a test";
?>
When I click on the link I get the entire HTML of the current page. "This is a test" can't be found there. I'm also getting an error: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/."
I reckon it has to do with the JS files that are included into this HTML response, but I've also tried setting "async: true" and it didn't help.
I would like to avoid using Zend Framework functions for this task, because I'm not well familiar with it and even making a simple controller sounds rather painful. Instead I want to find out what's causing such behavior and see if it can be changed.
PS: I've also tried moving quiz_api.php to another domain, but it didn't change anything.
I know that it might be an older code but it works, simple and very adaptable. Here's what I came up with. Hope it works for you.
//Here is the html
Link Test
<div id="test_div"></div>
function test(){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// This is the php file link
var url = "quiz_api.php";
// Attaches the variables to the url ie:var1=1&var2=2 etc...
var vars = '';
hr.open("POST", url, true);
//Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange =
function(){
if(hr.readyState == 4 && hr.status == 200){
var return_data = hr.responseText;
console.log(return_data);
document.getElementById('test_div').innerHTML = return_data;
}else{
document.getElementById('test_div').innerHTML = "XMLHttpRequest failed";
}
}
//Send the data to PHP now... and wait for response to update the login_error div
hr.send(vars); // Actually execute the request
}
you can change the whole page with a document.write instead of changing individual "div"s

angularjs changes in data not affected in views ajax

I am developing an application with angular js
Question: When I have an ajax call to server and I need to change the views based on the result of ajax call, the views don't get affected by this call, I think it the page renders before ajax call is finished but I don't know how to resolve it
For example the following piece of code
$scope.addItem = function() {
$http({
method :'GET',
url : 'addItem',
headers : {'Content-Type': 'application/x-www-form-urlencoded'}
}).success( function(data) {
$scope.allItems = data;
});
}
the allItems changed after the ajax call but the view is not changed
how should I solve this?

Post or Get, which is more appropriate to call a simple asp page via jQuery Ajax

I have a html page that I need to call another asp page to get the date/hour via an ajax call. Which method would be better or best, Post or Get?
Since I am only retrieving a few bits of data and not sending any data to the page info is one method better or proper than the other?
This is the simple ASP page.
<%#LANGUAGE="VBSCRIPT"%>
<% Option Explicit %>
<%=Weekday(Date)%>
<%=Hour(Now)%>
And this is the Ajax call to the asp page above.
jQuery.ajax({
url: '/v/timecheck.asp',
type: 'GET',
cache: false,
success: function(data){
// do something with the data
},
error: function() {
//do something on error
return false;
}
})
The reason I have to make the Ajax call to this ASP page is I cannot query the server direct from this page.
My rule of thumb when deciding either one is:
The interaction involve database, POST
The interaction involve sensitive information, POST
Requesting simple data, GET
Sending user input, POST
Sending/requesting large data, POST
Clean URL, POST
As you can see, most cases involve POST for many reason. Such as in your case, you could use GET or POST. Either way, jQuery make calling both function easy.
A simpler $.POST
$.post("/v/timecheck.asp", function (data) {
if (data.time != "") {
//retrieve success
{
else
{
//retrieve fail
};
});
or simpler $.GET
$.get("/v/timecheck.asp", function(data) {
if (data.time != "") {
//retrieve success
{
else
{
//retrieve fail
};
});
I would use POST, I think there is a secirity reason in ASP.NET to use POST, but not sure if this relates to IIS (and possibly ASP)
The W3C have a paper with guidelines on when to use GET or POST at: http://www.w3.org/2001/tag/doc/whenToUseGet-20040321#checklist
Using a GET request allows the result to be cached by the browser whereas a POST request won't be cached and the page will be re-retrieved every time.
In your code example you are not changing any data as a result of the request and are only providing the day and hour, so using a GET and setting the cache HTTP headers to 1 hour would give you the best performance and reduce load on your server.

Resources