Working with PHP and JQuery - php

I thought I should ask this before moving forward with my scripting project and later on realizing that I might be doing something wrong. Might as well save my own time in the first place by checking if what I'm doing is indeed correct.
I'm pretty new to PHP and JQuery and still getting the hang of them both. I recently came across a problem in which I wanted to run some PHP code after executing a certain function using JQuery, so after doing some reading online I got the idea to create a PHP file which does just what I want to do and POST to it from my JQuery function with the needed variables. That way I achieve my server-side and client-side goals on the same time. However!
It doesn't look right to me. At all. I find myself having at least ten include files for one simple page. Those files get included in my HTML code when the form loads, and after refreshing a certain DIV with my JQuery function, they get reloaded. That way I can keep my script dynamic, I doubt there's something else I could do in order to keep it that way.
However I often need to update stuff after executing a certain JQuery function, hence I call a similar file to the loading one, but this time it's a file which I transfer some parameters to (using the POST method, through JQuery), and execute the desired action in the file itself.
Now, after briefly explaining my current situation and method of work, I'd like to know if what I'm doing is correct. In case you're still wondering what the hell I am talking about, I'd like to explain in detail what I mean:
Let's say I have my index.php file which prints data from my database and some additional lines as well. Once I click one of the page buttons, I want to update my database according to the form I've got implanted in my page as well, and then reload the DIV which contains that data ONLY. I do not want to reload the entire page.
Now if I wanted to do that without JQuery that would have been easy. I would POST the data to the same form and update it if the POST parameters are indeed valid. However, there's no way to refresh that DIV without JQuery, so I came up with something similar to this:
$.post("/files/dosomething.php", { taskID: _taskID }, function(){
$("#div_tasks").fadeOut(800, function(){
$('#div_tasks').load('/files//load_div_A.php', function(){
$("#div_tasks").fadeIn(1500);
});
});
});
That's what I've been doing in my last week of learning PHP and JQuery. Now before I proceed any further than this, I'd like to know if it is indeed the right way to achieve my goal.
// EXAMPLE B:
I've got a DIV in my HTML code which prints a table of tasks, for instance. How do I print it? I include a file which echo's the table at the exact point where I want the table to be displayed. Then, in each row, there's a button called 'delete' which removes the selected row from the database. What I do is, using JQuery (due to the fact I want ONLY that DIV to be refreshed), I call another external file calling remove.php and send the index of the task I'd like to remove using POST. The file performs the server-side code and once it's done, I load the updated table into that DIV by calling the file I used to call in the first place from my main page. This time the table will be updated due to the fact it will read the updated data from the database.
Is that how I get this done? Is this the right way? It just doesn't seem right to me. I've never been codding that way and it seems a little bit messy.
Thanks in advance and sorry for the long ass question.

The problems you describe are exactly what the separation of concerns patterns (like MVC) where designed to tackle.
In your case from display instance to display instance the only thing that changes is how the response must be formatted and provided back to the user.
I would highly recommend looking at some of the more popular and well documented MVC Frameworks for your project (or if for nothing else just to play with and draw inspiration from, most of them and some pretty easy to follow starter tutorials you can run through in an hour or so).
It seems to me you are viewing the problem in a mindset compatible with these approaches and it probably feels clunky to you mainly because you are missing a lot of the structure and tooling that these frameworks provide.

If I am understanding the question correctly. I would think that it would be easier to post(using jQuery) to another script that performs the action you want to perform and only returns the result(html/json data) that you want. Right now you are making two requests to the server for something that seems to be tied together.
My suggestion would be to call one PHP script that performs the specific action that you want to perform(say an update to a news item for an example). Then return that data only in your response and then format that data how you want to in your div using jQuery.
$.post("/files/writetodatabase.php", { taskID: _taskID }, function(data){
$('#div_tasks').html(data) // this is assuming you return html, other wise you // could return JSON data and use it here
});
I tried to make that as clear as possible, difficult to explain when typing.

Related

Do php variables persist (using AJAX)?

This is my first question on this site, so I'm going to try to be as specific as i can... By the way, excuse me for my perfect knowledge of English... which isn't perfect at all..
So what I was wondering is: do php variables persist if you change your page's content, using AJAX methods?
Let me explain: I want to code a web app which has to contain a main layer, containing a few tabs. The user has to be able to write stuff into text areas in one tab, switch the tab, and if he wants so, come back to the first tab to complete what he wrote before (also the app has to keep the php variables that it created previously right?). The app also has to put all the data, entered in all the different tabs, in one or many databases, when a summit button is clicked; so it has to access all the variables created before.
I just don't have any code at this moment, but I want to do a specification file before starting to code, because what I am about to do is kinda massive app, so i hope you will be able to explain me this point.
I still thank you for your help.
You would be best to consider the PHP script as a one-off thing. It does what it is asked to, then terminates. Nothing is preserved.
However, if you NEED to preserve something to pass back with an AJAX call, you can do it by including:
<INPUT type='hidden' id='my_variable' value='my_value'>
This can be referenced by the javascript that calls your AJAX PHP page and thus be passed back.
For what you require, as #AlexP said, you can simply change the visibility of each tab content area with:
<SPAN onclick='toggle(this.id)' id='tab_1'>Tab Name</SPAN>
or similar. Your JS function might include something like:
for(n=1;n<=numberOfTabs;n++)
{
document.getElementById("div_"+n).style.display="none";
}
document.getElementById("div_"+passedid).style.display="block";
though there are other ways of doing it.
Perhaps what you REALLY want to do is save the entered data into a database field frequently (or even continuously).

Add several specification without saving first

I'm working on a editing tool (type of a simple CMS) in PHP/MySQL for a product catalog. I have search the Internet for a solution but I don't even know what to search for. So now my hope is on you guys.
I have a form where you can put all kinds of data like part.no, description an so on. All of this data is saved into a MySql table (items). I also have a table with predefined specifications.
What I want to do, and that I can't find a solution for, is to have a dropdown meny (or similar) and a add button to add a row for each related specifications without saving the whole form each time. I want to save first when all specifications is selected.
So, can I use PHP for this or do I need jQuery/Javascript or similar? I know it's possible, have seen it in OpenCart :-)
I hope someone understands my question. It's hard to explane i a language I'm not fully manage.
Regards
Client-side vs Server-side
Javascript: This sits in the user's browser. So anything you want to move in the user's browser will be done with JavaScript. This is "client-side"
PHP: This site on the server, so takes inpute from the user's browser and gives back a response (generally HTML, but can also be JSON or XML which is read by Javascript.). This is "server-side".
Libraries
jQuery: This is a set of functions written for Javascript to make it easier. So it runs in the user's browser and makes it easier for you to write bits that move on the screen.
You get similar libraries that help you write PHP (commonly called "frameworks") and there are many others for javascript as well.
Where to start
Write your HTML page as you want it to look. Keep it simple for the first time.
Then write some javascript (possibly using jQuery) to move the menu. Google "jquery menu dropdown" or similar and you'll find a solution you cna customise.
Then write some PHP that gives you the HTML you wrote in '1'.
Then decide what's going to happen when you click on a link in the HTML, and repeat the process (write HTML, incorporate Javascript to make it move, write PHP to give HTML)
Then work out which bits of the HTML are common or structured and should come from a database.
Without writing it for you (in which case you'll never learn) best to start one bit at a time and build as your knowledge grows. Bucket loads of examples on the web when youreach a particular problem you need to solve.
After comment "[how to] make it possible to select and add single/multiple specifications (from another table) without saving the whole form each time a specs is added":
Growing with AJAX
What you are asking is AJAX - this is where you get Javascript to talk to the server, and for javascript to move bits on the page based on the results. jQuery is probably the easiest (and probably has best documentation / examples for the ajax, as well as moving the DOM).
Basically: you have an "event" that you trap in JavaScript, example
/// Using jQuery to trap a button click
$().ready( function() {
$("#ButtonID").click( function(e) {
e.preventDefault();
alert('Button Clicked');
});
});
Then you build in an AJAX call inside that event (also check out get or post as the syntax is easier, you just get less control). The AJAX wil send a request to your PHP server, and you can get PHP to return HTML which you can replace/insert using the DOM manipulation functions linked below (e.g. before, html etc) or, when you get more advanced, you'll send back JSON which is a data structure you cna more easily manipulate in JavaScript to stipulate what actions are required.
As above, without actually writing it for you, the best place to start is to read the docs and have a go. Google "jquery AJAX PHP table example" or similar and you'll find an example somewhere.

AJAX vs PHP Directly into JS

I have a little bit of a conundrum. Basically I'm developing a WYSIWYG Editor plugin for jQuery specifically for my web application. One of the features will be inserting an inline image tooltip based on the images a user has uploaded. For example:
Hello there my name is [i="profile_pic.png"]A. Username[/i]
The part that I'm having an issue with is, when defining which images are available to a user, whether I should insert the PHP array directly into the Javascript like so:
var available_images = "<?=json_encode($User->Profile->images)?>";
or to go for an Ajax GET that returns an encoded array of the image sources? I think the inline php makes more sense since it removes the need for an unnecessary ajax call but I didn't think that inserting inline php into javascript is terribly good form?
Any suggestions?
There's nothing wrong with inserting data collected by PHP into JS, how else would JS get the data? The only reason you should consider the AJAX call would be, if users could upload new images while they are editing. This would mean the information needs to be updated, which would make the AJAX call more appealing than the static JSON on page load.
Unless the array changes in any way over the life time of the page, then I'd spit out the array exactly as you suggest in your code snippet. There isn't any real benefit to having an extra ajax call because the size of the array I'm guessing won't be so huge as to impact the initial page load time.
If you look around the Stack Overflow pages and do view-source, they do this sort of thing all the time.
If the amount of data is huge and maybe adds a seven or more seconds to the page load time then I'd consider an ajax call. At least the page is rendered and the user has something to look at, meanwhile you can have a throbber image with a status message saying loading or whatever.
I'd also say that I see a lot of unnecessary ajax goings on just for the sake of it. It's like premature optimisation, people adding complexity to solve a problem they don't have. Start off simple as you're doing, if you're having response time issues down the road with the said page, then consider what benefits ajax will bring to the table.
Do you always get the array of images, or only sometimes (e.g. in response to a user's action)? If the former, I'd say do it inline. Otherwise do it as AJAX. i.e. only do it by AJAX if it'll reduce your traffic etc. But if you have to always do it, I don't see any advantage. I don't see any problem with mixing inline php and javascript, other than it means you have to do your javascript inline too instead of in external .js files that can be cached (or at least the part where you populate your array).

JQuery AJAX Autocomplete issue with PHP and MySQL

I'm having a problem with my autocomplete. It works on another one of my pages, but on this one, it doesn't work. It's returning the correct number of entries, but they are all "blank" (or at least black so I can't see it), and selecting one does not put it into the text field either.
I'm using this: http://papermashup.com/jquery-php-ajax-autosuggest/
My page right now looks like
Any suggestions?
Thanks!
I'd post my code, but it's pretty much exactly what's on the site linked above, with some variables changed, and embedded into a PHP. Let me know if you want to see it (I don't want to paste it here and make the page huge and fugly).
Oh and this is taking it from a column in a MySQL database.
I think this link is quite useful to understand the technique. After you got the AJAX technique, you may simply change your php files which can run sql queries etc. You may show the results in that way with a simple div, very trivial css implementation would be enough. I think the hardest part is solved here:
http://www.w3schools.com/ajax/ajax_aspphp.asp
maybe your problem lies within encoding, jquery needs utf8 in the default settings, but without any code, I can only speculate...
try utf8_encode($output) instead of only returning the output...
also maybe your ajax request awaits a specific datastructure (json/xml/ etc)

Kohana 2 jQtouch Jquery

Trying to load some data from mysql into the next screen using jQtouch. What is the correct way of doing this. Right now I just have a jquery click event on the tag for the next page which really is just a div on the same page. The jquery looks like this.
$.post("/mobile/getCities", {}, function(data){ loadURL($(this).attr('href'), "#findyourhome"); });
this call hits a controller and pulls the data. Once I have the data I am setting it to a view-variable inside the controller. I think the issue was the fact that the index function gets hit again this way so the view variable never properly gets set.
Although not really an answer?
Are you just starting out?
In that case might I suggest taking a look at jQuery Mobile...
http://jquerymobile.com/
Seems like jQuery Mobile is making a strong start.
http://www.google.com/trends?q=jquery+mobile%2C+jqtouch&ctab=0&geo=all&date=all&sort=0
However if your work is tied to jQtouch... I have no clue...
You could also maybe try sencha tocuh. They tried selling it but now it's more or less free I think.
http://www.sencha.com/products/touch/
Not to sound pessimistic, I just don't see too much momentum from the jQtouch community lately.

Categories