Debugging PHP/JS in a CI web app - php

I thought I was doing great with this web app I'm working on, but alas.. I'm starting to think I designed it poorly, even though I started over like 6 times while learning the CI framework.
The application is here and my problem is as follows: when you go to, for example, december 31 2011 (by pressing the right arrow then clicking on the 31st), you get some red errors and my table headers (second part of the page) go crazy. After doing that, you should try going back to say.. april 1, you'll see that my headers go even more crazy, looping through some stuff that I don't know where it's coming from. If you go to april 2nd then, you'll see it still loops through that stuff, even though it shouldn't.
I'm not sure how to debug this, I don't even know where the problem lies: in my AJAX call or my PHP code.
My source code can be found here. The files involved are:
/logic/controllers/planner.php
/logic/models/planner_model.php
/logic/views/planner/days_content.php
/logic/views/planner/detail_content.php
Would anyone be so kind to look at this and help me find the problem here? I'm honestly not sure where to look for the solution to this issue. I can provide more information about how my application works if necessary.
I basically store everything in an array, and pass that to the view. When I do an AJAX call, I update the array and load the view again, after which I pass it into my page using .html().
Thanks a lot.

You can use firebug for firefox to debug ajax/javascript. When I click on a date there are multiple ajax calls. I think its happening because you have the js click handler inside dates_content.php which gets loaded every time you click right/left arrow. So your dates have multiple click handlers associated with it.
$("#day_list li").live("click", function() {
$(".selected").removeClass("selected");
var day = $(this).attr('value');
$(this).addClass('selected');
$.ajax({
type: "POST",
url: "/planner/change_detail",
data: { day: day, month: current_month, year: current_year },
success: function(data)
{
$("#detail_content").html(data);
}
})
});
I am talking about the above code you have

Related

jQuery event fires multiple times

I have a problem with jQuery events.
First let me explain the setup of the page:
The main-page.php is consisted of:
a) a header (where the logo is)
b) a navbar (where the various selections are)
c) a dynamic content area (Where the content of the clicked element on the navbar will be loaded)
d) Footer
Lets say that the navbar is consisted of | HOME | MESSAGES | ABOUT US | ...
The content of HOME is a separate PHP file, with a separate CSS and JS file. The same goes for all selections.
As soon as I select HOME (for example), i remove any content from the DYNAMIC CONTENT area and I place the content of HOME using AJAX. At the same time I remove any CSS/JS files associated with the previous content and I link the CSS/JS files associated with the one loaded. This part is working perfectly.
Now, if I switch from one selection to other selections (lets say from HOME --> MESSAGES --> ABOUT US and then back to HOME), if I click on a button inside HOME it will fire the event multiple times. This is even worse if that event is causing an AJAX call to the server (imagine calling the server 5 times instead of 1).
**The reason I use the on() event on the element with radio-element class is because is a future DOM element. Initially this element is not on the page.
A sample of JS code:
$(document).on('click', '.radio-element', function(){
$.ajax({
url: "js/ajax/ajaxcall.php",
success: function(output){
$('#ajaxcall-container').html(output);
}
});
});
What I do is, as soon as I click an element with the class of radio-element, I go in the server and i fetch the output of ajaxcall.php script.
Watching the NETWORK tab inside INSPECT ELEMENT, I see that the click event is executing the AJAX call multiple times. Sometimes 2, other 3 or even 5.
What I did to solve the problem (non of them is working 100%):
A) unbind the event before binding it using "off"
$(document).off('click','.radio-element').on('click', '.radio-element', function(){ .... });
B) Use event.stopImmediatePropagation()
$(document).on('click', '.radio-element', function(event){
event.stopImmediatePropagation();
//rest of code
});
Below is a solution that I haven't tried yet since I read in an article that it will not stop event binding process, it will just prevent multiple event execution (don't know if this will cause other problems).
$(document).on('click', '.radio-element', function(event){
if(event.handled !== true)
{
//Code goes here
event.handled = true;
}
});
The problem with multiple event firing is that there are AJAX calls that perform actions that are not supposed to be executed more than once (eg. send email to clients).
Also, this behavior (multiple event firing) is not something i can predict. Sometimes it works fine, some others it fires the event 5 times in a row.
I have been searching the web for a week now, but everything i tried did not solve the problem. Any solution will be much appreciated :)
Thanks!
Based upon what I am reading here - I would guess you are bringing on the js file with the click bind event more than once. If you are using custom routing or single page app and not refreshing the page, it is very likely based on what you are saying.
You could test this theory by adding a console.log inside the click event (above the ajax) and fool around with it and check the logs. If you are clicking it and it is logging whatever you logged more than once, then you know that this is the issue. I don't think it is the ajax.
I have also encountered the same problem quite a while. I solved this by unbinding all the events associated with the element before executing new event handlers.
Use like this:
$('#element').unbind().click()
{
//write something here
}
This will unbind previous event handlers before creating a new one. I think this will works well for you.
If you are using jquery version 1.7+
you can use off() like this
$('#element').Off().click()
{
//write something here
}
My guess based on your description is that you are not removing the event listeners. So every time you switch tab/page the same event will be added over and over again. Even though you have tried to do it, something is not going right. I doubt it has anything to do with Ajax.

Refresh PHP sql query without refreshing page

I have a question, and I'm hoping one of you will know the answer.
I am running a sql query from php fro a certain bit of information. I am then pulling that info into script and plugging it into an api. I want the api to have access to up to date info every 30 seconds. However, obviously, although the script can run again every 30 seconds ... the php cannot, thus the info is the same.
Is it possible therefore to have the php that runs the sql query refresh once every 30 seconds without refreshing the entire page?
Or ... is there a better way to be doing this. I believe it is no a good idea to be accessing the database from javascript?
Thanks in advance.
You're looking for AJAX. There are plenty of tutorials on the net explaining how to create simple pages powered by AJAX.
A quick example can be found here.
(function() {
setInterval(function() {
$.ajax({
async: true,
dataType: 'json',
type: 'GET',
url: '/echo/json',
success: function(data) {
// You'd use data variable here, but JSFiddle doesn't return anything
$('#test').html(Math.floor(Math.random()*100)-1); // Changes randomly after every fetch
}
});
}, 200);
}());
ajax is wath you are looking for,
ajax allows u to make a call to ur server whitout reloading your page.
i will recomend creating a page that only contains your data, then, on your aplication page load it into a div like
<div id="yourData"></div>
u can use James answer to load it, change '#test' for '#yourData' on any id u have on the div.
if u are using jquery u can use .load() also, for me is more clear, http://api.jquery.com/load/
$('#yourData').load('YourAplication/YourDataGeneratorPage.html');

jQuery .empty() causes AJAX populated div to blink

I am writing a dynamic website that uses AJAX to check the status of inventory items between front-end and back-end employees of a firm. One employee submits a request and the people in the back see it pop up on a queue and then respond if the requested item is or isn't in stock. The front-end employee then sees the status of their request change appropriately.
The problem I am having, and perhaps there is a better way of doing things, occurs when the code uses AJAX to retrieve all active requests from a table in a database and then uses jQuery 's .empty() function to clear out the container div which holds all of the old requests(setInterval() every 2 seconds) and regenerates the queue using a PHP script which builds a on the fly based on the AJAX results.
The setInterval() function which calls the function that .empty() the container div causes queue to visibly disappear and reappear. Is there a better way of updating a queue using jQuery rather than emptying out the entire queue and then rebuilding it based on updated statuses? I cannot simply query for the latest request because the statuses of older requests may have changed and need to be updated as well.
Hopefully this is clear, if not then please ask what more information is need, and any help will be greatly appreciated, thanks!
Something like this...
$(document).ready(function(){Update();});
function Update() {
$.ajax({
url: 'http://example.com/url/to/poll',
success: function(data) {
$('#MyDiv').html(data);
setTimeout('Update()', 2000);
},
fail: function() {
//Something went wrong. Inform user/try again as appropriate
alert('Failed');
setTimeout('Update()', 2000);
}
})
}
It only starts the next 2s delay after the current one completes. Also, it never actually empties the Div, it just replaces the old contents with the new.

Instant MySQL Update from a PHP Page - AJAX?

Had a search, but nothing really suggests a good route for me (might be my bad).
I've built a system to be run on an iPad - and to work as a counter for people entering a venue. Essentially, it's a simple insert into a MySQL database from PHP of a record each time a button is pressed on a web page.
That is, when someone enters the venue, a person on the door presses "In" when someone leaves "Out", an 'in time' is inserted into a MySQL database, and an 'out time' so at any time we can find out how many people were in the venue.
Simples. However, of course, it's quite slow, when multiple people are entering the venue at any one time, so I was wondering how you guys would deal with this. I've looked at AJAX, and I must admit this isn't really my field, but I've had a play. I'm naturally concerned about not losing any data, but also, we can't have the system waiting for 10 secs to reload the page.
My original idea was to have an AJAX 'thing' - which when the 'IN'/'OUT' button is pressed, it calls another PHP page to do the MySQL insert. Is this sensible? Or is there a better way of doing this? As my concern with the AJAX solution is that a new call of that 'insert.php' page, would cancel execution of a previous one, so data may get lost? Am I right?
Any insights anyone has would be VERY helpful.
Thanks in advance.
Ryan
You can achieve this easily using jquery.
First post data from main file and catch data in another file using $_POST['message'], to acknowledge data saved successfully you can output json. Here is example
On your html or php page
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#send_data").click(function(event){
var message= 'This is my message';
sendtodb(message);
});
});
function sendtodb(message){
$.post("save.php",{message:message},function(data){
alert(data.status);
},"json");
}
</script>
Now on secon file where you will save data:
<?php
$msg=$_POST['message'];
mysql_query("insert query");
json_encode(array('status'=>'data saved'));
?>
You'd probably be better to have more than one button on the layout, something like:
IN: 1 2 3 4 5 6 7 8 9 10
OUT: 1 2 3 4 5 6 7 8 9 10
It'd save on the number of requests being sent (and the need to press the same button 10 times).
Other than that, Ajax might be an idea, but you'd need some output to the user so that they know their press of the button has actually done something (as it's not refreshing the page, it's not obvious its doing anything).
But if it's taking that long to reload the page, then the bottleneck might not be because the page is reloading - it could be that the server is getting overloaded with requests (which doing my suggestion above should reduce), or could be the result of some badly written code taking a while to execute.
I think using AJAX is the way forward here, and jQuery does indeed make it really easy. Just a few extra thoughts and ideas:
Potentially a race condition could occur if a user keeps clicking before the ajax request has actually completed, particularly if the server becomes overloaded. I would do what Google search does here, and make sure you keep a record of the previous AJAX request and cancel it when a new one is launched, see this other post
With your back end PHP script, I reckon it's quite likely that this will form part of a larger PHP application. Try to make sure that any other processing that might be done for the front end site, such as building menus for example, isn't done on an AJAX request, because you don't need it and it just wastes processor time.
For more robustness, send a return value from your PHP script which maybe includes a status code, so you can detect if the call actually completed.

Adding/removing items from a list and then saving changes to MySQL

Any recommendation or better a good script to add/remove items from a list and then saving the changes to MySQL?
Here is the think, in my web page I ask my users how many languages do they speak, I have a textfield and a add button, any time the user hits add, the language written in the textfield has to appear in a list, and it also needs to be removable. When the user finish the work, he hits a send button that do a simple POST/GET action to a PHP script.
This is 90% front-end work, and I'm not a front-end developer (I'm a PHP dev). I know that using some JavaScript/jQuery this can be done, but I don't have any idea of how to handle this.
I tried for a long time, searching some tutorials on internet, but I didn't find anything good. So, if you can provide me some help/tutorial/script I will appreciate it.
You don't really need ajax for this if you are adding the languages all in one go. You can just add hidden form fields to a list when the user clicks the add button and then remove them if they click remove. This will make the interface much more responsive as well. I threw together a quick example here:
http://jsfiddle.net/wnFsE/
There really isn't much to the code to accomplish your goal.
The best way to do this would be an AJAX call to your PHP file that would actually be editing your database. I would also include some sort of visual device to indicate if the database is being changed and once the changes have been saved.
The below example assumes this is being done via JSON.
function saveChanges() {
var inputData = $('#your-input').val();
$.ajax({
type: "POST",
data: inputData,
url: '/file.php',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function ajaxSuccess(response) {
// let the user know their changes are saved
},
failure: function ajaxFailure(response) {
// let the user know something went wrong
}
});
};

Categories