CakePHP 2.2: Pre-populate AJAX "update" div? - ajax

This question is a little n00b-ish, but I haven't been able to find a satisfactory solution in the CakePHP docs or via google.
I'm trying to make a simple AJAX form that will update some information in a database, and also display that information on the page. The whole process seems straightforward enough, except I can't figure out how to pre-populate the update div.
In my view code, I have
<div id="interestingContent"></div>
<?
echo $this->Form->create();
// create form fields here
echo $this->Js->submit('Save', array('update'=>'#interestingContent');
echo $this->Form-end();
echo $this->Js->writeBuffer();
?>
This works great, and when the form is submitted, my controller correctly calls
$this->render('ajaxview','ajax')
and updates the #interestingContent div appropriately.
So, the question: What's the best way to pre-populate #interestingContent from the database? Of course I could just repeat the code from ajaxview.ctp inside #interestingContent, but it seems there must be a DRY way to do it.
My first thought was to make ajaxview.ctp an element, since I'm basically trying to embed one view inside another. That seems hackish to me, though, since my controller would then be rendering an element's view directly. I also considered the new view blocks in 2.1/2.2 but that doesn't seem right either.
I'm certain this sort of thing comes up all the time. Is there a generally accepted method of doing this?

I had the same problem. It may be hackish, but using an element wil do the job.
First, create an element for representing your bd content.
In your form view, you use the element.
And you create another view that will contain only the element. This view will be the response to your ajax request. By using an element, you prevent code duplication.

Related

Laravel - open popup/modal for each post from list

I have a page with a list of blog posts.
What would be the best way to open the post content on the same page in a modal, without redirecting to the single post page?
What I thought it's to make it in vanilla JS, to have an event on each post, have the data for all the posts in some array or each inside an attribute and when the event is triggered, fill the data for that post in the modal and show it. Maybe I can use AlpineJS for this.
Seems rudimentary to have it in vanilla, is there a better way to do it?
I also thought about Livewire, but I'm afraid it will be slow, have looked on some videos on YT, and when the button was clicked, it was visible when the data was filling in, looked slow.
Have thought also to make API calls, but I'd have to make the authentication work on that specific route, which would complicate it too much I guess, since it's going to be used just for this page.
What are your thoughts, how would you do it?
All your suggestions would work. Just depends on what you prefer and are able to implement. Also, think around opening the Post content in a modal, how much data do you want to load in the modal? Such questions will assist in you deciding the best way to design the post page.

Laravel 5.5 and VueJS, use both together correctly in a tags app

I guess this question has already been posted in different forms over time, but I still didn't find the answer I'm looking for:
I'm having trouble implementing vueJS in my Laravel app, I want to keep server and front-end very much separated but in this case it doesn't seem so easy. I have the classic blog project, where every article has some tags associated with it, so there's a classic many-to-many relationship and everything is set.
When I edit an article, I wanna have a section where all the tags are displayed and also you can add a new tag (very stackoverflow-like), what I wanna achieve is that my Javascript (and so my vue) only manages the rendering of those tags on the page, so that when I enter in the edit page I can see all associated tags, BUT, i only want to edit the input tag inside my form, I don't want to do a POST request in Vue, I want to keep it PHP, I want laravel validation, I don't want to write another one for the javascript.
I want javascript to only edit the DOM when I want to add a tag, so that I insert a new one and it immediately gets pushed inside the already existing array of tags, so in real-time the tags are updated, but when I submit the form it is my PHP that handles the server request, not vue, and this for now seems impossible because in order to update the tags correctly when adding one (or removing one), the data inside vue needs to have a list of tags, otherwise it won't work.
This means I have to create a new route (for example /tags/{article_id}) and a new controller function in order to return tags associated with that article, so this also means that I can't give to PHP the tags that I rendered (cause for example they're in a list, not an input select (due to the appearence I want to give)) isn't there a cleaner way to do this?
I'm trying to wrap my head around vuejs but sometimes it feels like stuff would be easier in jQuery (?), I don't know... I hope I explained myself correctly.

Paginating a long list of checkboxes in Magento

it would be awesome if someone could help me with this - I've already spent more than a day on it. :(
In a phtml file in Magento, I'm displaying a long list of products with a checkbox next to each. I've already added some code to paginate this list. The problem is, when I move to say page 2, I need to 'remember' which boxes were selected in page 1, and select them when I move back to page 1. I know how to use javascript to detect if a checkbox is checked or not. I was planning to save an array of selected boxes in the magento session - adding to it when more boxes are checked and deleting when boxes are unchecked. But my session-changing code is PHP, and my checkbox-detector is javascript. I know I can't call my session-changing function from javascript - I've been told that I would need AJAX to do this. I don't know any AJAX at all. Is there any other way to do this?
I'd be happy to post relevant snippets of my code if anyone can help me. Thanks!
UPDATE:
Okay, so I decided to use AJAX after all, and I've added a lot of AJAX code already. The problem is, it's not working. Btw, I'm not using jQuery. When I write this in Magento:
xmlhttp.open("POST", 'adjust_session.php', true); xmlhttp.send(params);
exactly where do I need to put my adjust_session.php file? It's not working if I put it in the same folder as my phtml file (where I'm calling the open function).
Thanks!
How are you actually doing the pagination? If you have to make a round-trip to the server for the paginated data anyway, send a list of checked/unchecked with it and toggle in the session. Then, when rendering the new page, either check the boxes in the HTML directly, or just pass a list of currently checked boxes in as JS and parse it on the response.
Alternatively, if you are doing everything on one page (and using AJAX for pagination already), you could also hold onto an array in JS and recheck the boxes after you render them.
Hope that helps!
Thanks,
Joe

load a new page using ajax

I am new to ajax and i wanted to know if we can load a complete new page and not just a part of it using ajax. Please give a small example script for understanding if this is possible. Here i am trying to display only one url to user while i change from one page to another when he clicks on any of the links in the page.
You can of course request for a new page and load it via body.innerHTML = ajax.responseText;
I would strongly recommend against this though for reasons outlined in this post: Why not just using ajax for Page Requests to load the page content?
The whole premise really is that with
AJAX you don't need to reload the
whole page to update a small
percentage of that webpage. This saves
bandwidth and is usually much quicker
than reloading the whole page.
But if you are using AJAX to load the
whole page this is in fact
counterproductive. You have to write
customised routines to deal with the
callback of the AJAX data. Its a whole
lot of extra work for little to no
increase in performance.
General rule for where to use AJAX: If
your updating >50% of your page, just
reload, else use AJAX.
You will not only need to request for the new page, but then also take care of ensuring the old styles on the current page are removed and don't interfere with the new page. Theres all sorts of problems associated with what your trying to do. It's possible, but I recommend not to do it.
edit: actually you might be able to just do document.write(ajax.responseText) which should take care of overwriting everything in the document, including css styles etc. Though still don't recommend it.
When you're finished with processing the AJAX request simply use this JS line:
window.location.replace('<URL of the new page>');
This has exactly the effect of loading the new page via
....
When you make an AJAX request, a request goes off and brings you the contents of the URL that you have requested. Now technically you can do whatever you like with the contents (which could be HTML), you can replace any element within the DOM with it. Be careful however of replacing EVERYTHING on the page, you are more likely just going to want to replace what is within the tags.
If what you want to do is show one URL for multiple pages, AJAX is overkill. Why not just use an IFRAME?
This could be useful if your page was unsure if it was expecting back errors to be inserted onto the page or a "new" submission confirmation page. This can be used when you want to put a validation servlet (or whatever) in front of the submission servlet (or whatever). If the page always hits the validation servlet, you hide the submission servlet which actually performs the data update. In the case where the validation passes, forward to the submission servlet. The user never knows what happened in the background.
When the page gets a response back you could just look at the first portion of the response text and determine if it had a keyword set by the server, which means this is a new page. Remove the keyword from the text, and do document.write(ajax.responseText); as described previously. Otherwise insert the response text into your errorBox div and let the user retry submission.

Reload the page without submitting it back to the server

the problem I have is that I have two sets of values in a drop down list. If type 'A' is selected I want a text box to be populated with a value from the database and be read only. If Type 'B' is selected the box is to be empty and editable.
My original code is written in jsp/struts and I have sort of achieved this by using
onchange="javascript:submit()" to reload the page, but this has the obvious drawback of saving any changes you have made which means you can't really cancel.
I also have other problems with the serverside validation due to this method.
Is there a way of making a jsp page reload on change, that way I could write javascript to change the way the page looks according to the values held in the session. That way the save/submit function will only be called when the page has properly been filled out and the server side validation will work as designed.
I know that this is something that AJAX is good at doing but I am trying to avoid it if possible.
AJAX is your only other option my friend, unless on the original page load you load all the other possible values of the Text Box so you don't need to go back to the database. Well, you could try putting the text box in an IFRAME, but you will probably run into more problems with that approach than just going with AJAX.
Without AJAX what you are asking is going to be difficult. Another option (which is ugly) is to write out all possible values for the second list box into a data structure like an array or dictionary.
Then write some javascript to get the values from the data structure when the user selects from the first list box. The amount of javascript you will have to write to get this done and to do it correctly in a cross browser way will be much more difficult than simply using AJAX.
Not sure why you'd try to avoid AJAX in today's world, the JS libraries out there today make it so simple it's crazy not to try it out.
I just had to replace a page that was written as Vincent pointed out. I assume at the time it made sense for the app, given the relative size of the data 4 years ago. Now that the app has scaled though, the page was taking upwards of 30 seconds to parse the data structures repeatedly (poorly written JS? maybe).
I replaced all the logic with a very simple AJAX call to a servlet that simply returns a JSON response of values for the 2nd drop down based on what was passed to it and the response is basically instant.
Good luck to ya.
One way is to change the form's action so that you submit the form to a different url than the "save" url. This lets you reload certain aspects of the form and return to the form itself, instead of committing the data.
<script>
function reload() {
document.forms[0].action="reloadFormData.jsp";
document.forms[0].submit();
}
</script>
<form action="saveData.jsp" method="post">
<select id="A" name="B" onchange="reload()"><!-- blah --></select>
<select id="B" name="B"><!-- blah B --></select>
<input type="submit">
</form>
If I understand you correctly, that you want either a dropdown (<select>) or a textfield (<input type="text">) depending on a choice (typically a checkbox or radiobuttons) somewhere above in a form?
I that case you may need to handle the two types of input differently on the server anyway, so why not have both the selectbox and textfield in the area of the form with different names and id and one of them hidden (display = none). Then toggle visibility when the choice changes. On the server you pick eiter the selectbox or textarea input (wich will both be present unless you disable (disabled="disabled") them too, wich I think is uneccesary) depending on the choice input.
Of course if you expect that the user usually just need the text-input, and a few times only, needing a massive list; it would be better to use ajax to retrieve the list. But if it's the other way around (you need the text-field only occationally), as I assumed above, it will be faster to have both present in the initial form.
If the drop down only contain easily generateable data, like years from now to houndreds of years back it could even be much faster (requiring less bandwidth on the server) to generate the data client side using a for loop in Javascript.
I know a taglib that can fit to your problem:
AjaxTags.
I use this taglib in my J2EE projects and it is very simple to integrate it into web applications.
This taglib give you several tags designed to execute AJAX request in your jsp files.
Here is the description of each tags: http://ajaxtags.sourceforge.net/usage.html
The tag which will help you is the ajax:select tag. It allows you to populate a select tag which depends on an other field without reloading the entire jsp page.
If you more informations about it, ask me and i'll try to answer quicky.
Along the lines of what Strindhaug said, but if you need dynamic data:
Could you have the backend write JS into the page, and then the JS would change the form as required? The backend could propagate some variables for descriptions and such, and then the JS could change/update the form accordingly. If you aren't familiar with this, libs like jQuery make things like this easier and more cross-browser than rolling-your-own (at least in my experience).
Aside:
If you're not using AJAX because it was hard to code (as I didn't for a while because my first experience was from scratch and wasn't pretty), as others have said, libs like MooTools and such make it really easy now. Also, there is not shame in using AJAX properly. It has a bad rap because people do stupid things with it, but if you can't simply write premade values into the form or you have to do live look ups, this is one of AJAX's proper uses.

Resources