Append a div without refreshing jquery - php

I want to add a div without refreshing the page.
Here is my Javascript:
<input class="btnsubmit" type="button" value="+Add Trivia" id="add_triviamodal">
function add_trivia()
{
var PHOTO_TRIVIA = CKEDITOR.instances.Trivia_Photo.getData();
var TITLE_TRIVIA = $('#TRIVIA_TITLE').val();
var CAPTION_TRIVIA = CKEDITOR.instances.triviacap.getData();
$.post('insert_home.php',{TRIVIA_TITLE:TITLE_TRIVIA,TRIVIA_PHOTO:PHOTO_TRIVIA,TRIVIA_CAP:CAPTION_TRIVIA}).done(function(data){
alert ("Trivia Successfully Added");
location.reload(); \\what i do is just refresh the page
});
}
This is how i output the the data that will be added using the ajax above
echo "<div class=\"view view-sixth\">
".$Tri_IMAGE."
<div class=\"mask\">
<div class=\"divbutton\">
<input onclick='TRIVIA_EDIT($Tri_ID);' class=\"btnsubmit\" type=\"button\" value=\"Edit\" id=\"edit_trivia\">
<input onclick='TRIVIA_DELETE($Tri_ID,this);' class=\"btnsubmit\" type=\"button\" value=\"Delete\" id=\"delete_trivia\">
</div>
<h2>".$Tri_TITLE."</h2>
<p>".$Tri_CAPTION."</p>
</div>
</div>";
}

You can use append() in jQuery to append elements to the DOM. If the div is returned by your PHP. Then append it to a DOM element by using i.e. $('#trivias').append(data);
EDIT (using the question authors code as an example):
I've replaced the location.reload() part with the code to append the returning div.
$.post('insert_home.php',{TRIVIA_TITLE:TITLE_TRIVIA,TRIVIA_PHOTO:PHOTO_TRIVIA,TRIVIA_CAP:CAPTION_TRIVIA}).done(function(data){
$('#trivias').append(data);
}
Here I assume you've got a element with the trivias id. For example <div id="trivias">...</div> somewhere in your code already.

just put your response data into whatever you want it in
$.post('insert_home.php',{TRIVIA_TITLE:TITLE_TRIVIA,TRIVIA_PHOTO:PHOTO_TRIVIA,TRIVIA_CAP:CAPTION_TRIVIA}).done(function(data){
alert ("Trivia Successfully Added");
$('#idOfTheDivYouwantToPutResponseIn').html(data);
});

Change your $.post() callback to also append the HTML response from insert_home.php into the DIV.
$.post('insert_home.php',{
TRIVIA_TITLE: TITLE_TRIVIA,
TRIVIA_PHOTO: PHOTO_TRIVIA,
TRIVIA_CAP: CAPTION_TRIVIA
}).done(function(data){
alert ("Trivia Successfully Added");
$('#trivias').html(data);
});

in PHP use json_encode
$str = "<div class=\"view view-sixth\">
".$Tri_IMAGE."
<div class=\"mask\">
<div class=\"divbutton\">
<input onclick='TRIVIA_EDIT($Tri_ID);' class=\"btnsubmit\" type=\"button\" value=\"Edit\" id=\"edit_trivia\">
<input onclick='TRIVIA_DELETE($Tri_ID,this);' class=\"btnsubmit\" type=\"button\" value=\"Delete\" id=\"delete_trivia\">
</div>
<h2>".$Tri_TITLE."</h2>
<p>".$Tri_CAPTION."</p>
</div>
</div>";
echo json_encode($str);
then use he post request like this
$.ajax({
type: "POST",
url: 'insert_home.php',
data: {TRIVIA_TITLE:TITLE_TRIVIA,TRIVIA_PHOTO:PHOTO_TRIVIA,TRIVIA_CAP:CAPTION_TRIVIA},
dataType:'json',
success: function (data) {
$('#your_id').html(data);
}
});

Related

How to add/append PHP + HTML code in JQuery .append()

I'm trying to append PHP code in Jquery. I'm getting confused in the quotation marks and not getting correct result.
below code.
<script>
$(document).ready(function(){
$("#add").click(function(event){
event.preventDefault();
//var text_box = "<br>Fee type: <input type='text' name='f1[]'>amount : <input type='text' name='f2[]'><br>";
var text_box = "<?php
#Fee type textbox
if(form_error('feetype'))
echo "<div class='form-group has-error' >";
else
echo "<div class='form-group' >";
?>
<label for='feetype' class='col-sm-2 control-label'>
<?=$this->lang->line('invoice_feetype')?>
</label>
<div class='col-sm-6'>
<input type='text' class='form-control' id='feetype' name='feetype[]' value='<?=set_value('feetype')?>' >
</div>
<span class='col-sm-4 control-label'>
<?php echo form_error('feetype'); ?>
</span>
</div>";
$("#info").append(text_box);
});
<script>
You can use an AJAX call to execute a PHP script on the server. So, for your if statements, just send the variables with conditions to be tested to a php script via ajax and php will return the html code of the div which you can then append to an element.
As an example for your first div;
You can set up an ajax call like;
<script>
$(document).ready(function(){
$("#add").click(function(event){
event.preventDefault();
var part;
var test = 'feetype';
$.ajax({
type: 'POST',
url: "get_div.php",
data: {test:test},
success: function(result){
part = result;
}
})
var text_box = part + "<label for='feetype' class='col-sm-2 control-label'>"
/***
all other code here
***/
</script>
Then in your php script
<?php
#Fee type textbox
if(form_error($_POST['test']))
echo "<div class='form-group has-error' >";
else
echo "<div class='form-group' >";
Let me know if it helps or if you find a problem.

Processing forms with jQuery

I have some PHP code that generates out a bunch of store items from my database. Each item has a quantity text box and an add to cart submit button and a hidden value with the special ID.
Here is basically how my form is generated:
<form class='form-inline' id='addtocart_form' action='
additem.php?iid=$SaleItem_Id&u=".$_SESSION['id']." ' method='post' role='form'>
<div class='form-group'>
<div class='input-group'>
<input type='text' class='form-control' style= 'float: left; width:50%;' id='quantity'
name='quantity' value='0'></input>
<button type='submit' name='add_to_cart' id='add' class='btn btn-success'>Add to
Cart</button>
</div>
<input type='text' name='$SaleItem_Id' style='display: none;' id='$SaleItem_Id'
value='$SaleItem_Id'>
</form>
My cart works perfectly, except it refreshes and puts you back up to the top of the screen. So then I decided to implement jQuery. All of these generated forms have the same id: addtocart_form.
$(function() {
$("#addtocart_form").on('submit' , function(e) {
e.preventDefault();
var thisForm = $(this);
var quantity = $("#quantity").val();
var dataString = $("#addtocart_form").serialize();
$.ajax({
type: "POST",
url: thisForm.attr('action'),
data: dataString,
});
$("#quantity").val("0");
return false;
});
});
The first item that is displayed on the screen works perfectly. It adds the item to the cart without refreshing the screen.
All of the other forms on the page are being submitted without the jQuery. They add the item, but redirect to the URL of my action.
How can I fix this without rewriting my entire store? I assume it has something with which form is being told to submit.
The id attribute should be unique in same document so try to replace the id addtocart_form by class, and all the other id's by classes to avoid duplicated id.
HTML :
<form class='form-inline addtocart_form' action=...
JS :
$("body").on('submit', '.addtocart_form', function(e) {
e.preventDefault();
var quantity = $(this).find(".quantity").val();
var dataString = $(this).serialize();
var action = $(this).attr('action')
$.ajax({
type: "POST",
url: action,
data: dataString,
});
$(this).find(".quantity").val("0");
return false;
});
Hope this helps.
You should not have more than one element with the same id on a page. If all of your forms use the same id, that's a problem.
Since you are using JQuery with AJAX, there's really no need to use a form at all. Just use a regular button (type="button") and tie a click event to it. Find the parent div of the button and get the values of the inputs within that div.
If your markup looks like this:
<div class='form-group'>
<input type='text' class='form-control quantity' style='float: left; width:50%;' value='0'>
<button type='button' class='btn btn-success add'>Add to Cart</button>
<input type='text' style='display: none;' class='saleItem_Id'>
</div>
<div class='form-group'>
<input type='text' class='form-control quantity' style='float: left; width:50%;' value='0'>
<button type='button' class='btn btn-success add'>Add to Cart</button>
<input type='text' style='display: none;' class='saleItem_Id'>
</div>
You can iterate over the inputs within the div like so:
$(".add").on('click', function() {
var parentDiv = $(this).closest("div");
//in this example, you only have one element, but this is how you would iterate over multiple elements
parentDiv.children('input').each(function() {
console.log($(this).prop('class'));
console.log($(this).val());
});
//do your ajax stuff
});
JS Fiddle demo

jquery popup div on click an element in a form

i have a form with four elements. i need to open a jquery popup when click on image that i set as fourth element in my form. popup window contains another form and a submit button. herepopup not coming. what wil i do.
this is my form
echo "<div class=\"addform\">
<form method='GET' action=\"update_events.php\">\n";
echo " <input type=\"hidden\" name=\"column1\" value=\"".$row['event_id']."\"/>\n";
echo " <input type=\"text\" name=\"column2\" value=\"".$row['event_name']."\"/>\n";
echo " <input type=\"text\" name=\"column3\" value=\"".$row['description']."\"/>\n";
echo " <input type=\"image\" src=\"images/update.png\" id=\"update_event\" alt=\"Update Row\" class=\"topopup\" onClick=\"callPopup(".$row['event_id'].")\"; title=\"Update Row\">\n";
}
echo "</table></form><br />\n";
this is my jquery
<script type="text/javascript">
function callPopup(id) {
console.log(id);
var datastring = "&event_id="+id;
$.ajax({
url: 'event_edit_popup.php', //enter needed url here
data: datastring,
type: 'get', //here u can set type as get or post
success: function(data) {
$('.popupContent').html(data);
console.log(data);
$('.loader1').hide();
$("#popup_content").after(data);
// u can see returned data in console log.
// here, after ajax call,u can show popup.
}
});
};
</script>
and this is my popup div
<div id="toPopup">
<div class="close"></div>
<span class="ecs_tooltip">Press Esc to close <span class="arrow"></span></span>
<div id="popup_content"> <!--your content start-->
<p align="center">edit company</p>
</div> <!--your content end-->
</div> <!--toPopup end-->
<div class="loader"></div>
<div id="backgroundPopup"></div>
You just need to give the image an id.. say id="clickme"
and in the jquery script:-
$('document').ready(function(){
$('#clickme').click(function(){ $('#topopup').show(220);}); });
Again u can add in transitions in the css of the topopup to give it various effects.
Also to hide the pop up:-
$('document').ready(function(){
$('#backgroundPopup').click(function(){ $('#topopup,#backgroundPopup').hide(220);}); });
//This is assuming that you want the popup to be closed when u click on the background
First mistake in your form is not complete and second is there is no input type='image' if you want to display image than you use image tag.
Please follow the code I hope it will be helpful to you:
<div class='addform'>
<form method='GET' action='update_events.php'>
<input type='hidden' name='column1' value="123"/>
<input type='text' name='column2' value="456"/>
<input type='text' name='column3' value="789"/>
<img src='images/update.png' id='update_event' alt='Update Row' class='topopup' onClick='callPopup("1")' title='Update Row'/>
</form>
</div>
Now jQuery code:
$("#update_event").click(function() { alert('sdf'); });
Now instead of alert you can use your ajax call for pop up.

Ajax form submission

I am trying to post the a form using ajax but the form never submits. Debugging using firebug doesn't show any errors. any help is appreciated. i am new to PHP and coding.
Taskload.php - Pushes data to the main page:
<?php
include_once 'dbconnect.php';
$varacctname = $_REQUEST['acct'];
$varViewtasks = mysql_query("SELECT * FROM tasks WHERE taskresource = '$varacctname' AND taskstatus='Active'");
while ($rows = mysql_fetch_array($varViewtasks)) {
$accttask = $rows['tasktitle'];
$acctTaskStatus = $rows['taskstatus'];
$taskOwner = $rows['taskOwnerFullName'];
$taskid = $rows['taskid'];
echo "<div class=\"timeline-messages\">
<div class=\"msg-time-chat\">
<img class=\"avatar\" src=\"img/chat-avatar.jpg\" alt=\"\">
<div class=\"message-body msg-in\">
<span class=\"arrow\"></span>
<div class=\"text\">
<p class=\"attribution\">$taskOwner</p>
<p> $accttask</p>
</div>
<form id=\"completetaskform\" method=\"post\" >
<input type=\"hidden\" name=\"taskid\" value=\"$taskid\" />
<input type=\"hidden\" name=\"acct\" value=\"$varacctname\" />
<input type=\"submit\" id=\"completetaskbtn\" class=\"btn btn-success\" />
</form>
</div>
</div>
</div>";
}
?>
Tasks.js - where the script lives
$("#completetaskform").submit(function(){
$.ajax ({
type:"POST",
url:"functions//completeTask.php",
data: $('form#completetaskform').serialize(),
success: function(msg){
notifyTaskCompleted();
location.reload();
},
});
return false;
});
completeTask.php Where the php code runs to mark task as completed.
<?php
include 'dbconnect.php';
$acct = $_POST['acct'];
$taskid = $_POST['taskid'];
$complete = 'completed';
mysql_query("UPDATE tasks SET taskstatus='$complete' WHERE taskresource='$acct' AND taskid='$taskid' ");
?>
--On the main page , i have tasks.js included in - Hope this may describe the issue better.
try SerializeArray
$("#completetaskform").submit(function(){
$.ajax ({
type:"POST",
url:"functions//completeTask.php",
data: $('form#completetaskform').serialize(),
success: function(msg){
notifyTaskCompleted();
location.reload();
},
});
return false;
});
or even $.post
$.post('functions/completeTrask.php',$('form#completetaskform').serialize(),function(){
notifyTaskCompleted();
location.reload();
});
1.Change
$("#completetaskform").submit(function(){
to
$("#completetaskform").on('click',function(){
Because jquery event is ".on()", not ".submit()"
2.Change
<input type=\"submit\" id=\"#completetaskbtn\" class=\"btn btn-success\"> Complete </a>
to
<button id="completetaskbtn"> Complete </button>
Bacause you don't need real submit button.
3.I'm not sure that your url is correct but this will submit your form to php.
after many trials, i found that changing the the form data section to $(this).serialize worked instead of $('form#completetaskform').serialize(). Not sure why but this worked. Thank you.
$("form#completetaskform").submit(function(){
$.ajax ({
type:"POST",
url:"Functions/completeTask.php",
data: $(this).serialize(),
success: function(msg){
notifyTaskCompleted();
location.reload();
},
});
return false;
});
I would use a generic button and click handler instead of a submit button and the submit event. Try this:
<button type=\"button\" id=\"#completetaskbtn\" class=\"btn btn-success\"> Complete </button>
Then attach a click event to it
$("#completetaskbtn").on('click', function () {
// the rest of the code you have
});

Ajax/Javascript User Status update

What I need to do is prepend the users latest status update with not only the newmsg and the users id but I need to also add my comment toggle link, my divider-postid div my users picture and name, my delete button, and my like and dislike button. So what I'd have is something like what Twitter and facebook do. ->Send the form data into ajax and print everything out into the feed. My profile.php has everything I use that needs to be included.
So is there a way I can call these blocks of html and display them in the prepended div after the Ajax success? Its really hard to explain as I don't know what I'm doing, but hopefully you get the idea. I'm just not up on all this.
PROFILE.PHP
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var content = $("#toid").val();
var newmsg = $("#newmsg").val();
$.ajax({
type: "POST",
cache: false,
url: "insert.php",
data: "toid=" + content + "&newmsg=" + newmsg,
success: function(){
$("#myThing").prepend("<div class='userinfo'>"+newmsg+" </div>");
}
});
});
});
</script>
<div class="userinfo"><div id="divider">
<div class="form">
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo $user1_id; ?>">
<input class="input" name="newmsg" id="newmsg" placeholder="Say something" autocomplete="off">
<div id="button_block">
<input type="submit" id="button" value="Feed">
</div>
</form>
</div></div></div></body>
<p id="myThing"></p>
COMMENT LINK
echo "<div class='stream_option'><a style='cursor:pointer;' id='commenttoggle_".$streamitem_data['streamitem_id']."' onclick=\"toggle_comments('comment_holder_".$streamitem_data['streamitem_id']."');clearTimeout(streamloop);swapcommentlabel(this.id);\"> Write a comment...</a></div>";
}else{
echo "<div class='stream_option'><a style='cursor:pointer;' id='commenttoggle_".$streamitem_data['streamitem_id']."' onclick=\"toggle_comments('comment_holder_".$streamitem_data['streamitem_id']."');clearTimeout(streamloop);swapcommentlabel(this.id);\"> Show Comments (".$num2.")</a></div>";
LIKE LINK
cho "<div class='stream_option'><a id='likecontext_".$streamitem_data['streamitem_id']."' style='cursor:pointer;' onClick=\"likestatus(".$streamitem_data['streamitem_id'].",this.id);\">";
DISLIKE LINK
echo "<div class='stream_option'><a id='dislikecontext_".$streamitem_data['streamitem_id']."' style='cursor:pointer;' onClick=\"dislikestatus(".$streamitem_data['streamitem_id'].",this.id);\">";
DELETE LINK
<? if($streamitem_data['streamitem_creator']==$_SESSION['id']){
echo "<div style='cursor:pointer;position:relative;top:-70px;float:right;padding-right:5px;' onclick=\"delete_('".$streamitem_data['streamitem_id']."');\">X</div>";}
I guess here:
success: function(){
$("#myThing").prepend("<div class='userinfo'>"+newmsg+" </div>");
}
Is where you're inserting the HTML? If that's the case, and if insert.php returns HTML, try this:
success: function(r){
$("#myThing").prepend("<div class='userinfo'>"+newmsg+r.responseText+" </div>");
}
To get the ID:
I guess the insertion is done with mysql, so after the new message is inserted you'd do:
$new_id = mysql_insert_id();
and then output the HTML:
echo "<div class='stream_option'><a id='likecontext_".$new_id."' style='cursor:pointer;' onClick=\"likestatus(".$new_id.",this.id);\">";
echo "<div class='stream_option'><a id='dislikecontext_".$new_id."' style='cursor:pointer;' onClick=\"dislikestatus(".$new_id.",this.id);\">";
if ($new_id == $_SESSION['id'])
echo "<div style='cursor:pointer;position:relative;top:-70px;float:right;padding-right:5px;' onclick=\"delete_('".$new_id."');\">X</div>";

Categories