Auto-Expand div if textarea has content - php

I am creating a blog using PHP / MySQL and there is an edit post function.
When clicking "Edit" the page "refreshes" (goes to the same page but the URL changes), the <div> expands and the text of the post they want to edit is now shown in the <textarea>.
With the help of another SO user I got part of this done. Only problem is that it's putting the editable text into every <texarea> box.
Here's a working example: http://thebulb.daysofthedead.net/testing.php
I have some thoughts on how to get this working but don't know how to do it since I am not good with jQuery or Ajax:
Add an ID to the <textarea> with the editable content and passing
that ID to the jQuery script.
Don't change pages, just use Ajax to
insert the text they want to edit into the <textarea>.
When they click "Edit" turn the box with the text into a <textarea> box with
submit form. I can get that part working by using an example I found
(http://jsfiddle.net/25Hay/2/) but I don't know how to submit that
to my PHP script for validation and insert into the database.
Here's the jQuery I currently use:
$(function(){
// Insert editable text into the <textarea> box
$('.blogcontainer textarea[name=postcontent]').filter(function(i) { return $.trim($(this).val()) != ""; }).closest('.postreplycontainer').slideDown("fast");
// Execute when Edit link is clicked
$(document).on('click', '.postreply', function(e) {
// Collapse all previous expanded <div>'s
$(this).closest('.blogcontainer').siblings('.blogcontainer').find('.postreplycontainer').slideUp("fast");
// Expand / Collapse <div>' when "Post Reply" is clicked
$(this).closest('.blogcontainer').find('.postreplycontainer').slideToggle("fast")
// Focus <textarea> when <div> is expanded
.find('textarea[name=postcontent]').focus();
});
});

1) Adding data-id to a textarea would be an easy approach. I see you already have post_id=5 in your URL when you want to edit a post, so I'm guessing you could use that (I can't find the script you use for updating the textareas)
2) and 3)
Ajax with jQuery is really easy to use. You can read more about it here http://api.jquery.com/jquery.ajax/
This is a JSFiddle example.
$.ajax({
url: '/echo/html/', // for JSfiddle only, here you will use the url that you normaly put in a form taget
data: {
textarea: textarea_value,
postID: post_id,
html: textarea_value // so jsFIDDLE can answer
}, // this is the data you send to that URL, in this case it's your value, in PHP you will then get them with $_POST['textarea'] or $_POST['postID']
type: 'post', // default is get, you can set it to post or head, text etc...
success: function (answer) {
// answer is what you get back from the server if the data was sent
alert(answer)
},
error: function () {
alert('something went wrong')
}
});

Related

AJAX form onsubmit: jump to div

We currently search through a form for contacts, and AJAX is used to display the results from a PHP file below the form (on the same page). The form's onsubmit attribute includes a return:false value to allow the AJAX code to complete.
The results appear 'below the fold' and I'd like the focus to jump down to an ID (#peopleResults) but can't manage this; instead, it stays at the top of the parent page.
Should I be trying something in the actual PHP file or in the AJAX call (to the PHP file) to achieve this?
I already tried <script>window.location.hash = "peopleResults";</script> in the PHP file and referencing results.php#peopleResults in the AJAX call, but neither worked.
Is this possible? I guess I am trying to do the equivalent of appending #peopleResults to the URL upon pressing Submit (without the URL necessary changing)...
I already tried <script>window.location.hash = "peopleResults";</script>
location.hash includes the # – both when reading from it, as well when you set a new value.
So
window.location.hash = "#peopleResults"
would be the correct way to tell the browser to jump to an element with the ID (or anchor name) peopleResults.
I think you want to achieve this please check the fiddle.
This is done without using hash. As you just want to view the result after Ajax.
By this you don't need to change the URL.
Based on the reply to my comment, it would seem you're a little foggy on the AJAX portion too. From the documentation:
$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
beforeSend: function( xhr ) {
xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
}
})
.done(function( data ) {
if ( console && console.log ) {
//this is where you need to add your data to the div
//after the data is in the div, scroll to it.
console.log( "Sample of data:", data.slice( 0, 100 ) );
}
});
You can see, the function where I added the comments is where you need to do the scrolling. After you populate the div (how ever you're doing that), then just use the suggestion Learner Student or phpisuber01 made of scrolling to it:
$("html, body").animate({ scrollTop: $("#peopleResults").scrollTop() }, 1000);
jQuery AJAX documentation: https://api.jquery.com/jQuery.ajax/
jQuery scrollTop documentation: https://api.jquery.com/scrollTop/

load part of html using php/jQuery

I'm trying to figure out a way to load 1 single tab(tabs by jQuery) without reloading all the others.
The issue is that I have a submit button and a dropdown that will create a new form, and when on this new form 'OK' or 'CANCEL' is clicked, it has to get the original form back.
The code to load a part of the page that I found is this:
$("#tab-X").load("manageTab.php #tab-X");
But now I would like to know how to use this in combination with the $_POST variable and the submit-button
Clarification:
I have a .php(manageTab.php) which contains the several tabs and their contents
I have in each of these tabs a dropdown containing database-stored information(code for these dropdowns is stored in other pages)
for each of these dropdowns, there exists a submit button to get aditional information out of the DB based on the selection, and put these informations in a new form for editing
this new form would ideally be able to be submitted without reloading everything except the owning tab.
Greetings
<script>
$(document).ready(function() {
$("#form1").submit(function(){
event.preventDefault();
$.post('data.php',{data : 'dummy text'},function(result){
$("#tab-X").html(result);
});
});
});
</script>
<form id="form1">
<input id="btn" type="submit">
</form>
I am not totally understand your question, but as per my understanding you can't load one tab with form submit. Its normally load whole page.
What you can do is, use ajax form submit and load the html content as per the given sample code.
$.ajax({
url: url, // action url
type:'POST', // method
data: {data:data}, // data you need to post
success: function(data) {
$("#tab_content_area").html(data); // load the response data
}
});
You can pass the html content from the php function (just need to echo the content).
AJAX is what you are looking for.
jQuery Ajax POST example with PHP
Also find more examples about ajax on google.
Example: Let me assume you have a select menu to be loaded in the tab.
You will need to send a request to your .php file using jquery, and your php file should echo your select menu.
In your jQuery,
<script>
$.post(url, { variable1:variable1, variable2:variable2 }, function(data){
$("#tab-X").html(data);
//data is whatever php file returned.
});
});
$("#form_id").submit(function(){
return false;
});
</script>
I mean whatever your options are, you will need to do the following in your .php file,
Echo that html code in your PHP script.
echo "<select name='".$selector."'>
<option value='".$option1."'>Option1</option>
<option value='".$option2."'>Option2</option>
<option value='".$option3."'>Option3</option>
</select>";
This would be returned to jQuery, which you may then append wherever you want.

Can a variable go to a hidden PHP page using jQuery?

My PHP page
<ul id="upvote-the-image">
<li>Upvote<img src="image.png" /></li>
</ul>​
is currently successfully sending variable to javascript
$("#upvote").each(function(index) {
var upthis = $(this).attr("rel");
var plusone = upthis;
$.post("upvote.php", {
'plusone': plusone
});
alert(plusone);
});​
(The alert in the code is for testing)
I have multiple images using the rel tag. I would like for each to be able to be upvoted and shown that they are upvoted on the page without loading a new page.
My question, and problem: what is my next step? I would just like to know how to send a value to upvote.php. I know how touse mysql to add an upvote, just not how to send a value to upvote.php, or even if my javascript code opens the page correctly.
thanks
I think you need something like this:
<ul id="upvote-the-image">
<li><span rel="50" id="upvote">Upvote</span><img src="image.png" /></li>
</ul>​
<span id="result"></span>
$("#upvote").click(function(index) {
var upthis = $(this).attr("rel");
var oOptions = {
url: upvote.php, //the receiving data page
data: upthis, //the data to the server
complete: function() { $('#result').text('Thanks!') } //the result on the page
};
$.ajax(oOptions);
}
You dont need an anchor, I changed it for a span, you can test asyc connection using F12 in your browser
Your javascript never opens the php page, it just sends data to it, and receives an http header with a response. Your php script should be watching for $_POST['plusone'] and handle database processing accordingly. Your next step would be to write a callback within your $.post function, which I recommend changing to the full ajax function while learning, as it's easier to understand and see all the pieces of what's happening.
$.ajax({
type: 'POST',
url: "upvote.php",
data: {'plusone': plusone},
success: function(IDofSelectedImg){
//function to increment the rel value in the image that was clicked
$(IDofSelectedImg).attr("rel")= upthis +1;
},
});
You'd need some unique identifier for each img element in order to select it, and send it's id to the php script. add a class instead of id for upvote and make the id a uniquely identifiable number that you could target with jquery when you need to increment the rel value. (From the looks of it, It looks like you're putting the value from the rel attribute into the database in the place of the old value.)
A good programming tip here for JQuery, Don't do:
<a href="javascript:return false;"
Instead do something like:
$(function(){
$('#upvote').on('click', function(event){
event.preventDefault();
$.post('upvote.php', {'plusone': $(this).attr('rel')}, function(data){
alert('done and upvoted');
});
});
});
That is a much better way to handle links on your DOM document.
Here are some Doc pages for you to read about that coding I use:
http://api.jquery.com/on/
http://api.jquery.com/jQuery.post/
Those will explain my code to you.
Hope it helps,

php javascript partial page reload

I have a page set-up, with several divs.
For now all we need is
<div id="main">...</div> & <div id="sidebar">...</div>
Each div has code such as:
<?php include("page.php") ?>
The main div does all the work, and includes a JavaScript function. E.g. at the moment the user can click a button to remember an item displayed in a table.
Am I able to only reload the sidebar instead of the whole page when the user calls this function?
I am posting the function here, and all I need now is to be able to refresh the sidepanel and its included php files if that is possible? I assume something along the lines of this could do the job? or am I wrong? load("#sidebar")
function saveToFavorites(code)
{
$.ajax({
async:false,
type: "POST",
url: 'formPostsUser.php?reqtype=addToFavorite',
data:'coursecode='+ code,
success: function(data)
{
$('.result').html(data);
if(data != "")
{
alert(data);
load("#sidebar")
}
}
});
}
Kind regards
Alex
Happy about any and every reply and hint ;)
First thing
<div="sidebar">..</div>
The above markup is wrong HTML. You should give the sidebar as the value of your properties such as id or class
<div id="sidebar">..</div>
Loading the Sidebar content
You can use jQuery ajax to load content of this div using jQuery load method like this
$(function(){
$("#sidebar").load("yourPHPPageToReturnSideBarContent.php");
});
Assuming yourPHPPageToReturnSideBarContent.php is the PHP page which renders the HTML Markkup for the sidebar. Note that this will load the content on the document ready event.
Loading the side bar content on an event
If you want to load it on a purticular event like a button click you can do it like this
$(function(){
$(document).on("click","yourButtonId",function(){
$("#sidebar").load("yourPHPPageToReturnSideBarContent.php");
});
});
The above script will load the side bar content on a button click. The button's id is e "yourButtonId" in this example.
Note that i used jQuery on here to bind the function because it will take care of current element and future element in case if you want to load the markup which contains the button dynamically.

how to refresh the data being loaded on the form after showing it off?

I have a a div, wherein, it displays the data, and beside it, is an edit button..if one clicks the edit button, it hides the div and shows a different div with input forms which allows the user to update the data..the problem now is, when the user submits the form, my script updates the data and hides this input forms and shows again the former div of data display, the data shown is not updated....my question now is,, how to show the updated data after the script show() it again ?
here's my jquery ajax code
$(function(){
$('#profileinfoedit').click(function(){
$('#profileinfomain').hide();
$('#profileinfoajax').show();
$('form#pdetails').submit(function(){
var cvid = $('#cvid').val();
var resumetitle = $('#resumetitle').val();
var name = $('#name').val();
var dob = $('#dob').val();
var gender = $('input[name=gender]:checked').val();
$.ajax({
type: "POST",
url: 'classes/ajax.personalupdate.php',
data: $("form#pdetails").serialize(),
success: function(data){
alert(data);
$('#profileinfoajax').hide();
$('#profileinfomain').show();
}
});
return false;
});
});
});
$('#datepicker').datepicker();
So location.reload is just refreshing the page, which as you have discovered is a quick and dirty fix.
If you want to do it without a page refresh, you would have to regenerate the html for just the 'profileinfomain' element from data received back from ajax.personalupdate.php. I would assume you would only want to do this on "success".
One approach would be to have the success data contain the html needed to regenerate the 'profileinfomain' element html. So perhaps have php return back data.profileinfomain_html, and then:
$('#profileinfomain').html(data.profileinfomain_html);
which will replace the inner content of the profileinfomain element.
If you are working in a framework of some sort, have the profileinfomain inner html content be a partial template included in so you only have to maintain its html in one place.
was able to sort it out via
$('#profileinfomain').show('normal',function(){
location.reload();
});
but, isn't there any better way to do this?

Categories