how to reset text area after pressing button using angular js? - php

I am working on a project where i have to perform actions like social media, i stuck on a stage where i have to comment and then i have to reset that editable div.
Editable Div code:
<div id="txtComment" contenteditable="true" class="form-control txtComment" style="height: 156px; margin-bottom: 10px;">
My button for calling comment function Code:
<input type="button" value="POST" ng-click="comment(<?php echo $itemId ?>,<?php echo $itemDesc ?> ,user_comment,0,0,mood)">
my function:
$scope.comment=function (itemid, itemdescid,user_comment,replyId,parentcomId,mood)
{
var feeling="";
//console.log(mood);
if (typeof mood !== "undefined")
{
feeling=mood;
//console.log(mood+"test");
}
var comm="";
if(replyId==0)
{
comm=$("#txtComment").html();
}else if(replyId == parentcomId)
{
comm=$("#"+parentcomId+"comment").html();
//console.log(comm);
} else
{
comm=$("#"+replyId+"comment").html();
}
console.log(comm);
//console.log(feeling);
var req = {
method:"POST",
data:{item_Id:itemid, item_desId:itemdescid, comment:comm,commentReplyId:replyId,parent_commentId:parentcomId,User_feeling:feeling,userId:$scope.id},
url:"<?php echo base_url()?>index.php/ItemImportance/Comment",
headers: {
'Content-Type': 'application/json'
},
};
$http(req).then(function (response) {
if (response.data !=null)
{
if(response.data.msg !=null)
{
alert(response.data.msg);
}
else
{
//var scopeNmae="item"+"_"+itemid+"_"+itemdescid;
// console.log(scopeNmae);
//$scope[scopeNmae]=response.data;
//console.log(response.data);
// window.location.reload();
$scope.itemcomments=response.data;
//eraseText();
}
} else
{
}
}, function (response) {
console.log(response)
});
}
what i have to do is just empty my editable div after i click on comment button!
please help me as fast as you can.

I wrote a really simple example plnkr, please have a look at it.
<body ng-controller="MainCtrl">
<textarea ng-model="comment" placeholder="comment"></textarea>
<button ng-click="comment = ''">Clear</button>
</body>
My recommendations are:
Keep it simple
Don't try to mix Angular with jQuery, unless you really have to
Use appropriate html elements
Edit:
Example plnkr with content editable div. It's a fork from the AngularJS website, I just added the clear button.

this has worked for me, here the
html code
`<textarea [(ngModel)] ="myInput"></textarea>
<button (click) = "this.deleteText();">clear</button>`
angular code
myInput: string;
deleteText(){
this.myInput = '';
}

Related

Jquery Ajax how return Errors from PHP?

I have simple, form which works with Jquery Ajax, but I don't know how can I get my Errors from php.
My Form
<form action="customer.php" method="post" class="addForm">
<input name="username" type="text" placeholder="username"> <br>
<input name="name" type="text" placeholder="name"> <br>
<button type="submit" name="btnAdd">Add New Customer</button>
</form>
My Script
<script>
$(document).ready(function() {
$("form.addForm").submit(function(e) {
e.preventDefault();
// form's url and method
var addForm_URL = $("form.addForm").attr("action");
var addForm_Method = $("form.addForm").attr("method");
var username_Val = $("input[name='username']").val();
var name_Val = $("input[name='name']").val();
var btnAdd_Val = $("button[name='btnAdd']").val();
$.ajax({
url: addForm_URL,
method: addForm_Method,
data: {
username_Post: username_Val,
name_Post: name_Val,
btnAdd_Post: btnAdd_Val
},
success: function(data) {
if (data) {
console.log(data);
$("input[name='username']").val("");
$("input[name='name']").val("");
} else {
console.log(data); // here should be my errors
}
}
});
});
});
</script>
My php
if (isset($_POST['btnAdd_Post']) && empty($_POST['username_Post'])) {
//some stuff
echo 'Error 1';
}
if (isset($_POST['btnAdd_Post']) && $_POST['name_Post'] == "my1") {
//some stuff
echo 'Error 2';
}
if (isset($_POST['btnAdd_Post']) && !empty($_POST['name_Post'])) {
//some stuff
echo 'Error 3';
}
As I use e.preventDefault(), I can't use any exit() or headers in my php.
How can I get my echo Error 1,2,3 from php put in my Ajax and priant some stuff or redirect ?
Thanks
The problem is that you dont allow the post so the you cant get the $_POST info, so ether you have to let it go through with the post and catch the errors with php or log the errors with jQuery.
As far as I'm aware the you do the ajax call to prevent to reload the page and thus not accessing the PHP, but this means you'll have to catch the errors with jQuery as well.

Form when submitted to display a result (Firstname) on the thank you page

Stuck on a thing with PHP, i know it is something simple but am not sure of the correct way of doing it, either by jquery or php.
I have a contact form which when it submits its form, i want the results of some of the fields to display on the results thank you paeg saying:
Thank you for entering YOURNAME. Blah blah blah
Is this acheivable with a simple line of php or does it need to called through jquery.
Thanks, only new to php so somethings are still bit confusing
<?php
define('is_freetrial-celebrity', 1);
include_once('includes/header.inc.php');
?>
<div role="main" id="main">
<article id="mainFreetrial" class="greyBlock twoColumnsLayout">
<header>
<h1>Get Started</h1>
</header>
<div>
<form method="get" action="/forms_validation/freetrial.php" class="trialForm ajaxForm">
<div class="column">
<p>
<label for="firstNameTrial">First name<sup class="red">*</sup></label><input type="text" id="firstNameTrial" name="firstNameTrial" value="" required/>
</p>
<p>
<label for="lastNameTrial">Last name<sup class="red">*</sup></label><input type="text" id="lastNameTrial" name="lastNameTrial" value="" required/>
</p>
<p>
<label for="ageTrial">Age</label><input type="text" id="ageTrial" name="ageTrial" value=""/>
</p>
<p>
<label for="celebrityTrial" style="display: block; width: auto; margin-bottom: 5px;">Name the celebrity you would most like to meet, and why?<sup class="red">*</sup></label>
<textarea id="celebrityTrial" name="celebrityWhyTrial" style="width: 430px; height: 3em;" required></textarea>
</p>
<p class="ajaxFormBeforeValid">
<input type="submit" value="Submit now" class="redButton"/><span class="ajaxFormWait"></span><span class="ajaxFormError error"></span>
</p>
<div class="ajaxFormValid">
<p>
Thank you! Your local consultant will contact you soon. 'Like' us while you wait for all the latest VIP offers and promotions!
</p>
</div>
<p>
<small>
<sup class="red">*</sup>These are mandatory fields.
</small>
</p>
</div>
</form>
</div>
</article>
</div>
<?php include_once('includes/footer.inc.php'); ?>
Heres the jquery part
/*************************
plugin to manage ajax forms
*************************/
(function( $ ){
var methods = {
init : function( options ) {
return this.each(function(){
var $this = $(this),
data = $this.data('ajaxForm'),
ajaxForm = $('<div />', {
text : $this.attr('title')
});
// If the plugin hasn't been initialized yet
if ( ! data ) {
$(this).data('ajaxForm', {
target : $this,
ajaxForm : ajaxForm
});
//get the spinner, the valid box and the error box
var mySpinner = $this.find('.ajaxFormWait');
var myValid = $this.find('.ajaxFormValid');
var myError = $this.find('.ajaxFormError');
var myBeforeValid = $this.find('.ajaxFormBeforeValid');
myError.hide();
mySpinner.hide();
//add an event to send the form via AJAX
$this.submit(function(){
// get all the inputs into an array.
var $inputs = $this.find(':input:not([type="submit"], [type="button"])');
// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
if (this.type == "radio" || this.type == "checkbox"){
if($(this).is(':checked')){
if(typeof(values[this.name]) === 'undefined'){
values[this.name] = $(this).val();
}else{
values[this.name] += ', '+($(this).val());
}
}
} else
values[this.name] = $(this).val();
});
function defineTheInvalidsFields(fieldsList){
for(var i in fieldsList){
if(fieldsList[i] == 'closestStudio'){
$this.find('[name="'+fieldsList[i]+'"]').parent().addClass('invalid');
}else{
$this.find('[name="'+fieldsList[i]+'"]').addClass('invalid');
}
}
}
//send an AJAX request
$.ajax({
url: $this.attr('action'),
dataType: 'json',
data: values,
beforeSend: function(){
mySpinner.show();
},
success: function(result){
mySpinner.hide();
$this.find('.invalid').removeClass('invalid');
//error management
if(typeof(result.valid) === 'undefined'){
if(result.multipleSend){ //if multiple send
myError.html('Your request is already sent.');
}else if(result.required){ //if fields are required
defineTheInvalidsFields(result.required);
myError.html('The fields in red are required.');
}else if(result.format){ //if the forma is incorrect
defineTheInvalidsFields(result.format);
myError.html('The fields in red have invalid content.');
}else if(result.loginInvalid){
myError.html(result.loginInvalid);
}else{
myError.html('An unknown error occured.');
}
myValid.slideUp(300);
myError.slideDown(300);
}else if(typeof(result.loginUrl) !== 'undefined'){
window.location.href = result.loginUrl;
}else{
if(result.valid || result.valid == 'true'){
if($('#inputFreetrialFitnessFirst').length){
myBeforeValid.slideUp(300);
myError.slideUp(300);
myValid.slideDown(300);
}else{
window.location = '/free-trial-thank-you/';
}
}else{
myError.html('There was an error sending your details. Please try again.');
myValid.slideUp(300);
myError.slideDown(300);
}
}
}
});
return false;
});
//special case for the heardAbout
$('#heardAbout').change(function(){
if($(this).find('option:selected').attr('value') == 'Other'){
$('#otherHeardAbout').slideDown(300);
}else{
$('#otherHeardAbout').slideUp(300);
}
});
}
});
},
destroy : function(){
return this.each(function(){
var $this = $(this),
data = $this.data('ajaxForm');
// Namespacing FTW
$(window).unbind('.ajaxForm');
data.ajaxForm.remove();
$this.removeData('ajaxForm');
})
}
};
$.fn.ajaxForm = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.ajaxForm' );
}
};
})( jQuery );
The form gets sent to the other page, is there a way to target a specific div and add the custom message with the name.
if(result.valid || result.valid == 'true'){
if($('#inputFreetrialFitnessFirst').length){
myBeforeValid.slideUp(300);
myError.slideUp(300);
myValid.slideDown(300);
}else{
window.location = '/free-trial-thank-you/';
}
}else{
myError.html('There was an error sending your details. Please try again.');
myValid.slideUp(300);
myError.slideDown(300);
}
if You wand to fetch specific element div via ajax call You can do like this:
$.ajax({
url: 'page.html',
success: function(data) {
item=$(data).filter('#specific_element');
$(selector).html(item);
}
});
If You wand to redirect to other page using
window.location = '/free-trial-thank-you/';
and then show data on a different page You should pass needet parameters like
window.location = '/free-trial-thank-you/page.php?name1=Daniel&name2=Pablo;
and on different site show parameters using _GET or _POST for example:
echo $_GET['name1'] or echo $_POST['name1'] if You use PSOT method in Your Ajax request
One way that I can think of is using session to store the information.
At freetrial.php store the form information in session like this:
session_start();
$_SESSION['firtNameTrial'] = $_GET['firstNameTrial'];
On ajax success, redirect the page to the thank you page using javascript windows.location.replace:
// similar behavior as an HTTP redirect
window.location.replace("http://yourwebpageaddress.com/thankyou.php");
Get the session on the thank you page. If you don't know, you may look at this example: Click here for session example

Ajax call - Append the structure of the php echo

I am confused a little bit and I have no clues what am I looking for.
Although I will post here important parts so you may figureout and help me.
A part of PHP file:
if (empty($vid) || empty($entry)) {
$broken = TRUE;
}
if(!$broken) {
$video = parseVideoEntry($entry);
echo "
<div class=\"video_wrap\">
<div class=\"video_thumbnail\">
<a href=\"{$video->watchURL}\">
<img src=\"$video->thumbnailURL\">
</a>
</div>
</div>
<!-- More of structure parts here -->
";
}
A part of HTML structure:
<form action="" method="GET" style="margin: 5% 0;" id="youtube_fetch">
<input type="text" name="id" value="https://www.youtube.com/watch?v=VIDEO_ID_HERE" id="videoID_input" />
<input type="submit" id="fetch_submit" />
</form>
A part of jQuery / Ajax call:
$('#fetch_submit').on('click', function (e) {
var videoID = $('#videoID_input').val();
$.ajax({
url: 'inc/YouTube_API_Fetch_ID.php',
type: 'GET',
data: { id: videoID },
success: function (state) {
var newState = $.trim(state);
if (newState == '')
alert('Return an Error later!');
else
console.log(state);
}
});
e.preventDefault();
});
Ok so when I put valid youtube ID into the input field, it will return the else from ajax call (echo the html structure in console log).
The part that I don't know how to deal with is: "How to get that echoed HTML content/structure and append it into the <div id="youtube_content"></div> for example or directly to the body.
Use the .html() method:
$('#youtube_content').html(state);
References:
.html() - jQuery API Documentation
If I understand your question correctly:
$('#fetch_submit').on('click', function (e) {
var videoID = $('#videoID_input').val();
$.ajax({
url: 'inc/YouTube_API_Fetch_ID.php',
type: 'GET',
data: { id: videoID },
success: function (state) {
var newState = $.trim(state);
if (newState == '')
alert('Return an Error later!');
else {
$('<div />', {
id: 'youtube_content'
}).appendTo('body');
$('#youtube_content').html(state);
}
}
});
e.preventDefault();
});

jquery cant get value of text box

i am building one form with fancy box, form work fine but i could not get value from text box.
my java script is
$(function () {
$("#button").click(function () {
var yourName = $("input#yourName").val();
alert(yourName);
if (yourName == "") {
$('input#yourName').css({
backgroundColor: "#F90"
});
$("input#yourName").focus();
return false;
}
$.ajax({
type: "POST",
url: "bin/form1.php",
data: $("#login_form").serialize(),
context: document.body,
success: function (res) {
var success = '<?php echo sprintf(_m('Success name % s '), "" ); ?>';
success = success.replace(/^\s*|\s*$/g, "");
var RegularExpression = new RegExp(success);
if (RegularExpression.test(res)) {
alert('Message Sent');
$.fancybox.close();
} else {
alert('Error While processing');
}
},
});
return false;
});
});
now my html is
<div style="display:none; height:450px">
<form id="login_form" action="">
<p id="login_error">
Please, enter data
</p>
<input type="hidden" name="action" value="send_friend_post" />
<label for="yourName" style="margin-right:110px;">
<?php _e( 'Your name', 'newcorp') ; ?>
</label>
<input id="yourName" type="text" name="yourName" value="" class="text_new " />
<br/>
<input type="submit" value="Submit" id="button" class="text_new" style="background:#930; color:#FFF; width:250px; margin-left:170px" />
</form>
</div>
i am opening this fancy box popup from
<a id="tip5" title="" href="#login_form"><?php echo "Login" ; ?></a>
every thing work fine but i can't get value of yourName even alert is showing blank.
Thanks
instead of this
var yourName = $("input#yourName").val();
try
var yourName = $("input[name='yourName']:text").val();
this will make ur function read the value of text box .
Firstly, with your form, it should be better to use
$(document).on('submit', 'form', function () { ... })
instead of
$(document).on('click', '#myButton', function () { ... })
Secondly, you should encapsulate your code into $(document).ready(function () { .. });
Here is a working example ;) http://jsfiddle.net/aANmv/1/
Check that the ID of Your input is not changed by fancybox at the time of opening the popup.
Instead of directly catching up the click event try to live the event if using jQuery 1.7 > or on when using jQuery 1.7 <.
live:
$("#button").live('click', function() { ... });
on:
$("#button").on('click', function() { ... });
Also try to load the javascript after the DOM is loaded:
$(document).ready(function(){
$("#button").live('click', function() { ... });
...
});
Instead of that
$(function() {
try
$(document).ready() {
this way you are sure that code is executed only after the document has loaded completely. Oh, and you could use #yourName instead of input#yourName, if i'm not wrong it should be faster.

Submit form (jquery) and show results in colorbox

I have a form that I wish to submit which is posting to a php script to deal with the form data.
What I need to do is after hitting submit have a colorbox popup with the php results in it.
Can this be done?
This is what i've been trying:
$("#buildForm").click(function () { // #buildForm is button ID
var data = $('#test-buildForm'); // #test-buildForm is form ID
$("#buildForm").colorbox({
href:"build_action.php",
iframe:true,
innerWidth:640,
innerHeight:360,
data: data
});
return false;
});
UPDATE: This would need to be returned in an iframe as the
build_action.php has specific included css and js for those results.
This is simple, untested code but it'll give you a good jumping off point so you can elaborate however much you please:
<form action="/path/to/script.php" id="formID" method="post">
<!-- form stuff goes here -->
<input type="submit" name="do" value="Submit" />
</form>
<script type="text/javascript">
$(function() {
$("#formID").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(data) {
$.colorbox({html:data});
},
'html');
return false;
});
});
</script>
this article will help you with the problem
http://www.php4every1.com/tutorials/jquery-ajax-tutorial/
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(500);
$('#demoForm').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#demoForm').show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
return false;
});
});
< ?php
sleep(3);
if (empty($_POST['email'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter you email.';
}
else {
$return['error'] = false;
$return['msg'] = 'You\'ve entered: ' . $_POST['email'] . '.';
}
echo json_encode($return);
You will need to see the exact way to use your colorbox jQuery plugin. But here is a basic (untested) code example that I've just written to hopefully get you on your way.
If you wish to submit a form using jQuery, assuming you have the following form and div to hold dialog data:
<form id="myForm">
<input type="text" name="num1" />
<input type="text" name="num2" />
<input type="submit" name="formSubmit" />
</form>
<div style="display: hidden" id="dialogData"></div>
You can have a PHP code (doAddition.php), which might do the addition of the two numbers
<?php
// Do the addition
$addition = $_POST['num1'] + $_POST['num2'];
$result = array("result" => $addition);
// Output as json
echo json_encode($result);
?>
You can use jQuery to detect the submitting of the code, then send the data to the PHP page and get the result back as JSON:
$('form#myForm').submit( function() {
// Form has been submitted, send data from form and get result
// Get data from form
var formData = $('form#myForm').serialize();
$.getJSON( 'doAddition.php', formData, function(resultJSON) {
// Put the result inside the dialog case
$("#dialogData").html(resultJSON.result);
// Show the dialog
$("#dialogData").dialog();
});
});
This is how I ended up getting it to work:
<div id="formwrapper">
<form method="post" action="http://wherever" target="response">
# form stuff
</form>
<iframe id="response" name="response" style="display: none;"></iframe>
</div>
<script>
function hideresponseiframe() {
$('#formwrapper #response').hide();
}
$('form').submit(
function (event) {
$('#formwrapper #response').show();
$.colorbox(
{
inline: true,
href: "#response",
open: true,
onComplete: function() {
hideresponseiframe()
},
onClosed: function() {
hideresponseiframe()
}
}
);
return true;
}
);
</script>

Categories