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

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.

Related

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.

Append a div without refreshing jquery

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);
}
});

issue sending a retrieving value using ajax

This is a cleaner code of my preview problem, the idea is to send and retrieve a value using ajax, but the value is not being sent nor ajax seems to work. I updated this code because this way it could be easily tested on any machine. First time using ajax. Here is the code:
Javascript
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
$.ajax({
url: 'request.php',
type:'POST',
data: $("#form").serialize(),
dataType: 'json',
success: function(output_string){
alert(output_string);
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
HTML:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP file, request.php
<?php
$centro = $_POST['centro'];
$output_string = ''.$centro;
echo json_encode($output_string);
?>
Try Changing Your Code A bit like Below .
Jquery part
success: function(d){
var output=d[0].data; // Will output only first record
$('#cuentas').html(output);
} // End of success function of ajax form
PHP PART
$centro = $_POST['centro'];
$output_string = array('data'=>$centro);
echo json_encode($output_string);
if still not works Check The Developer tool in chrome or firebug in firefox to monitor the Requests
Looking at your code:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
I miss an ending-tag for the div id="centro". Therefore the click-event for jQuery("#centro") will not trigger.
I suppose it should be like this: (Always set <form> and </form> inside OR outside of a div, do not mix and put <form> outside and </form> inside of a div. Some things wont work as expected when you do a mix like that.
<?php
$result = 'works';
?>
<div id="centro">
<form id="form">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
</div> ><!-- end of div centro -->
<div id="cuentas">
</div>
I solved it, now this works, plus I added a gif loader:
Javascript:
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
var result = $("input#centro").val();
$.ajax({
url: 'request.php',
type:'POST',
data: { 'dataString': result },
beforeSend: function(){
$("#loader").show();
},
success: function(output_string){
$("#loader").hide();
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
HTML
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
<div id="loader" style="display:none"><img src="ajax-loader.gif" width="20px" height="20px"></div>
Click here
<br>
<input type="hidden" name="centro" id="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP
<?php
$data = $_POST['dataString'];
$output_string = '';
$output_string = '<h3>'.$data.' '.'testing'.'</h3>';
echo $output_string;
?>
Output: "works testing"

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>";

How to get value from multiple input fields on different class?

I have form like this:
<div class="satu">
<input type='text' size='1' maxlength='1' name='score[1][]' id='score[1][]'>
</div>
<div class="dua">
<input type='text' size='1' maxlength='3' name='weight[1][]' id='weight[1][]'> %
</div>
<div class="tiga">
<input type='text' size='5' name='weightscore[1][]' id='weightscore[1][]' disabled>
</div>
<div class="satu">
<input type='text' size='1' maxlength='1' name='score[2][]' id='score[2][]'>
</div>
<div class="dua">
<input type='text' size='1' maxlength='3' name='weight[2][]' id='weight[2][]'> %
</div>
<div class="tiga">
<input type='text' size='5' name='weightscore[2][]' id='weightscore[2][]' disabled>
</div>
this is the jquery script:
$('[id^="score"]').keyup(function()
{
var score=$('[id^="score"]').val();
var weight=$('[id^="weight"]').val();
$.ajax({
url: "cekweightscore.php",
data: "score="+score+"&weight="+weight,
success:
function(data)
{
$('[id^="weightscore"]').val(data);
}//success
});//ajax
});
this is the php code:
<?php
include "connection.php";
$score = $_GET['score'];
$weight = $_GET['weight'];
$totalweightscore=(($weight * $score )/ 100);
echo"$totalweightscore";
?>
When i keyup on score[1][], the value of weight[1][] is not coming out. PLease Help me, How to get value from multiple input fields on different class ??
Your code works for me for the first group of input elements. It would not work for the second set of elements because with .val you get "the current value of the first element in the set of matched elements". So when you keyup on score[2] the JS code actually sends the values of score[1] and weight[1], which may be empty.
To fix that one easy way is to wrap an element around each group of items so that you can easily target the "associated" weight element when keyup is triggered, like this:
<div class="group">
<div class="satu"><input type='text' name='score[1][]' id='score[1][]'></div>
<div class="dua"><input type='text' name='weight[1][]' id='weight[1][]'> %</div>
<div class="tiga"><input type='text' name='weightscore[1][]' id='weightscore[1][]' disabled></div>
</div>
<div class="group">
<div class="satu"><input type='text' name='score[2][]' id='score[2][]'></div>
<div class="dua"><input type='text' name='weight[2][]' id='weight[2][]'> %</div>
<div class="tiga"><input type='text' name='weightscore[2][]' id='weightscore[2][]' disabled></div>
</div>
And the code would look like
<script type="text/javascript">
$('.satu input').keyup(function () {
var $satuInput = $(this);
var score = $satuInput.val();
var weight = $satuInput.closest(".group").find('.dua input').val();
$.ajax({
url: "cekweightscore.php",
data: "score=" + score + "&weight=" + weight,
success: function (data) {
$satuInput.closest(".group").find('.tiga input').val(data);
} //success
}); //ajax
});
</script>
I also changed the jQuery selectors to work with the classes in your HTML rather than the element ids; while the code should work either way, this style feels better to me.
you can get value with this
score.each (function () {
console.log(this.value);
});

Categories