Jquery not sending textarea name="post_description" - php

My jQuery code is not sending a value from the textarea name="post_description"
<form id="post" method="post">
<div class="input-group">
<textarea name="post_description" class="form-control" placeholder="<?php echo $lang['description']; ?>" rows="4" ng-model="description"></textarea>
</div>
<div id="share_result"></div>
<a id="share" class="btn-custom">
<i class="fa fa-th-large"></i> <?php echo $lang['share']; ?>
</a>
</form>
$(document).ready(function() {
$("#share").click(function(e) {
e.preventDefault();
var postimg = $("#post").serialize();
$.post("posts/post_image.php", postimg).done(function(data) {
$("#share_result").html(data);
}).fail(function() {
//alert("Error submitting forms!");
})
})
})
On the backend:
$post_description = $_POST['post_description'];
It's returning as undefined index but the names do match

May be because you prevent event onclick you have to set event prevent on form submit like this :
<form id="post" method="post">
<div class="input-group">
<textarea name="post_description" class="form-control" placeholder="<?php echo $lang['description']; ?>" rows="4" ng-model="description"></textarea>
</div>
<div id="share_result"></div>
<a id="share" class="btn-custom">
<i class="fa fa-th-large"></i> <?php echo $lang['share']; ?>
</a>
<button type="submit" id="postform">Submit form</button>
</form>
When you click on submit button your form will submit and then
$("#post").submit(function (e) {
e.preventDefault();
// here is your code
});
Or if you don't want to add this button you have to change from
var postimg = $("#post").serialize();
to
var postimg = {post_description:$("textarea[name='post_description']").val()};

It was the Angular js conflict so I had to write my own jquery function to replace the angular and keep the same angular beraviour on the page, here is my jquery solution for angular replacement:
<script type="text/javascript">
$(document).ready(function(){
$("#post_description").keyup(function(){
// Getting the current value of textarea
var currentText = $(this).val();
// Setting the Div content
$("#text_output").text(currentText);
//$("#text_output").value(currentText);
$("#text_output").attr("value", currentText);
});
});
</script>

Related

How to fix ajax that loads a class on a page?

I made a comment column by putting process.php in the page header, but when I want to load a #comment-list, 1 page entered into the div.
I've tried changing ajax.url and it works, but it will affect the entire system that was created.
I want to load this part when ajax is successful
HTML
<div id="comment-list" class="widget-body">
<?php news_comment($server_conn,$id_news); ?>
</div>
FORM
<form action="<?php echo FullURL() ?>" method="post" id="newcomment">
<div class="form-group">
<label for="comment">* Comment:</label>
<textarea class="form-control" rows="3" name="text_comment" placeholder="Your Comment" required></textarea>
</div>
<button type="submit" class="btn btn-primary" id="submit-comment" name="submit-comment" value="<?php echo $row['id_news']; ?>">Post Comment</button>
</form>
AJAX
$("#submit-comment").click(function(event){
event.preventDefault();
var submit = $(this).attr('value');
var post_url = $("#newcomment").attr("action");
var request_method = $("#newcomment").attr("method");
var form_data = $("#newcomment").serialize();
$.ajax({
url : post_url,
type: request_method,
data : form_data + '&submit-comment=' + submit,
success: function(){
$("#newcomment")[0].reset();
$("#comment-list").load(post_url + "#comment-list");
}
})
});
When Ajax responds successfully, I want #comment-list loads automatically, without entering a 1-page display

Form append just VALUES not variables to URL

I need to send a Form with just the values append to the URL, like this:
http://thisistheurl.com/serv#search/VALUE1/VALUE2/VALUE3/VALUE4
I could send like this:
http://thisistheurl.com/serv?variable1=value&variable2=value&variable3=value&variable4=value#search/
The form is very simple.
<form id="consultatickets" name="consultatickets" role="form" method="get" class="tickets-form" action="http://thisistheurl.com/serv#search/" target="_blank">
<div class="row">
<div class="form-group col-md-12 col-sm-12">
<label for="ciudadorigen" class="tickets-imputs">Ciudad de Origen</label>
<select name="ciudadorigen" class="form-control ciudadorigen tickets-imputs" for="ciudadorigen">
<option selected disabled>1</option>
<option value="562">2</option>
<option value="582">3</option>
</select>
</div>
</div>
<!-- Here goes the rest of the form -->
<a type="submit" class="btn btn-warning waves-effect btn-block" href="javascript:{}" onclick="document.getElementById('consultatickets').submit();">Buscar <i class="fa fa-search" aria-hidden="true"></i></a>
</div>
I don't know how to extract the just the values from the variables and append to the URL.
If the order doesn't matter, you can achieve this by serializing the values of the form and appending it to the action attribute of the form to build the final url.
<form id="consultatickets" name="consultatickets" role="form" method="get" class="tickets-form" action="http://thisistheurl.com/serv#search" target="_blank">
<div class="row">
<div class="form-group col-md-12 col-sm-12">
<label for="ciudadorigen" class="tickets-imputs">Ciudad de Origen</label>
<select name="ciudadorigen" class="form-control ciudadorigen tickets-imputs" for="ciudadorigen">
<option selected disabled>1</option>
<option value="562">2</option>
<option value="582">3</option>
</select>
<label for="campo_adicional">Campo adicional</label>
<input id="campo_adicional" type="text" name="campo_adicional" />
</div>
</div>
<input type="submit" value="search"/>
</form>
$("#consultatickets").on('submit',
function(e) {
e.preventDefault();
var values = $(this).serializeArray();
var baseUrl = $(this).prop("action");
$.each(values, function(i, v) {
baseUrl += "/" + encodeURIComponent(v.value);
});
alert(baseUrl);
}
);
https://jsfiddle.net/kb3rvLjs/
Untested and I'm not sure if I got your question correctly but it seems you look for something like this:
// your form submit event handler
function formSubmit() {
var form = $('#consultatickets');
// build your url
var url = 'http://thisistheurl.com/serv#search/' +
getValues(form).join('/');
// redirect to your new location
location.href = url;
};
// function to get the values from the form elements
function getValues(form) {
// get all form fields in the form
var fields = $( "input, select", form);
var values = [];
// loop over the fields, add them to array
jQuery.each( fields, function( field ) {
values.push(encodeURI(field.val()));
});
return values;
}
In case you want to trigger the form submit with the a tag, simply change your onclick attribute to: onclick ="formSubmit();".

Print success notice in their own div depending on the form that I sent

I have this script that allows me to send data to the database without reloading the page. The form data is sent to file process.php.
At the end of the process, inside the div box of the form is printed a notice that everything went ok
<script type="text/javascript">
$(document).ready(function(){
$(document).on('submit', '.formValidation', function(){
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'submit.php',
data : data,
success : function(data){
$(".formValidation").fadeOut(500).hide(function(){
$(".result").fadeIn(500).show(function(){
$(".result").html(data);
});
});
}
});
return false;
});
});
</script>
Page success.php:
foreach( $_POST as $key => $value ) {
$sql = "INSERT INTO tbl_".$key."(nome_".$key.") VALUES ('$value')";
$result = dbQuery($sql);
}
print "ok";
And the div box for the notice <div class="result"></div>
The problem: I have many div box with a form and when I print the notice of success, it happen into all the <div>, because the call notification is always .result
success: function(data){
$(".formValidation").fadeOut(500).hide(function(){
$(".result").fadeIn(500).show(function(){
$(".result").html(data);
});
});
}
What I want: Print the success notice in its own div depending on the form that I sent.
Thanks
EDIT: The html interested
<form id="myform2" class="formValidation" name="myform2" action="" method="post"></form> <!-- this is the form for the <div> in html5 -->
<div class="widget-body">
<div class="widget-main">
<div>
<label for="form-field-select-1">Comune</label>
<select name="comune" class="form-control" id="form-field-select-1" form="myform2">
<option value="">Seleziona...</option>
<?php
$comune = "SELECT * FROM tbl_comune ORDER BY nome_comune ASC";
$result_comune = dbQuery($comune);
if (dbNumRows($result_comune) > 0) {
while($row_comune = dbFetchAssoc($result_comune)) {
extract($row_comune);
?>
<option value="<?php echo $id_comune; ?>"><?php echo $nome_comune; ?></option>
<?php
}
} else {
?>
<option value="">Non ci sono dati</option>
<?php
}
?>
</select>
</div>
<hr>
<div class="widget-body">
<div class="widget-main">
<div>
<input type="text" name="comune" id="comune" value="" placeholder="Aggiungi Comune" form="myform2">
<input type="submit" name="submit" value="Submit" class="btn btn-sm btn-success" form="myform2">
<div class="result"></div>
</div>
</div>
</div>
</div>
</div>
If the form is in a div and the result is next to the form, you can do sibling:
$form.next(".result").html(data);
or elsewhere in the same parent:
$form.parent().find(".result").html(data);
or in your case
$form.find(".result").html(data);
Like this - note I have removed all the unnecessary hiding.
$(function() {
$(document).on('submit', '.formValidation', function(e) {
e.preventDefault();
var data = $(this).serialize();
$form = $(this); // save a pointer to THIS form
$result = $form.find(".result");
$.ajax({
type: 'POST',
url: 'submit.php',
data: data,
success: function(data) {
$result.html(data);
$form.fadeOut(500, function() {
$result.fadeIn(500)
});
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="myform2" class="formValidation" name="myform2" action="" method="post"></form>
<!-- this is the form for the <div> in html5 -->
<div class="widget-body">
<div class="widget-main">
<div>
<label for="form-field-select-1">Comune</label>
<select name="comune" class="form-control" id="form-field-select-1" form="myform2">
<option value="">Seleziona...</option>
</select>
</div>
<hr>
<div class="widget-body">
<div class="widget-main">
<div>
<input type="text" name="comune" id="comune" value="" placeholder="Aggiungi Comune" form="myform2">
<input type="submit" name="submit" value="Submit" class="btn btn-sm btn-success" form="myform2">
<div class="result"></div>
</div>
</div>
</div>
</div>
</div>

Passing variable data between jQuery and PHP using AJAX shorthand

I'm trying to create a search feature that searches a database based on the criteria a user has entered. Right now, I'm just trying to get the jQuery variable data into PHP. I've decided to use the shorthand AJAX $.post method because this is just a demo project. I know there are numerous similar questions like mine, but I have yet to find an answer to any of them that I can use.
So what I'm trying to do is, the user will click on a drop down menu and select an option. AJAX then sends the selected value to the PHP file and the PHP will eventually perform a database search based on what was selected. The issue is, in PHP, I'm getting a string of "Search" when the data is parsed and I echo it but when I do a console log on the variable that was sent, I'm getting the correct text. Can anyone tell me where I'm going wrong?
Here's what I have so far.
AJAX
$("#search_form").on("submit", function(ev){
ev.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
console.log(data);
})
})
PHP
ob_start();
require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo $criteria;
HTML
<form id="search_form" method="post">
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search" id="search" />
<input type="submit" class="button" value="Search_Now" />
</fieldset>
As Requested
Here is a fiddle of the drop down menu to show how it works.
http://jsfiddle.net/xvmxc0zo/
Your form is being submitted via default form submission; the ajax call is misplaced, it should be within the submit handler, which should prevent default form submission.
Note that I have removed both name and id attributes from the submit button; you do not need them. Just let the submit button do it's job and listen for the submit event on the form where you would then use event.preventDefault(); to make sure the form does not submit, then you can make your ajax call.
$("#searchBy").on("click", ".option", function(){
$('#search').val( $(this).text() );
});
$('form').on('submit', function(e) {
e.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
//jsonData = window.JSON.parse(data);
console.log( data);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="hidden" name="search" id="search" />
<input type="text" name="search_text" id="search_text" />
<input type="submit" class="button" value="Search" />
</fieldset>
</form>
In your PHP use echo $criteria; instead of echo json_encode($criteria);.
I'd suggest to use the way of jQuery documentation to check changes in your drop down.
$( "select" ).change(function () {
$( "select option:selected" ).each(function() {
$.post("../php/test.php", {search: $(this).text()}, function(data){
jsonData = window.JSON.parse(data);
});
});
})
You are getting "Search" on the PHP side because that is the value of your submit button.
You want the post to occur when you click on an option? Try adjusting your selector as follows:
$("#searchBy .option").on("click", function () {
var search = $(this).text().trim();
$.post("../php/test.php", { search: search }, function (data) {
jsonData = window.JSON.parse(data);
})
});
I think your header.php is provoking the error. I created a test file myself with your code and that works perfectly fine:
<?php
if($_POST)
{
ob_start();
//require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo json_encode($criteria);
exit;
}
?>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search_text" id="search_text" />
<input type="submit" name="search" id="search" class="button" value="Search" />
</fieldset>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$("#searchBy").on("click", ".option", function(){
var search = $(this).text();
$.post("<?=$_SERVER['PHP_SELF']?>", {search: search}, function(data){
jsonData = window.JSON.parse(data);
console.log(jsonData); //Prints the correct string
})
});
</script>

Javascript Automated Click?

I have the following function for a jquery login form and want to run it when php detects that the user is not logged in by echoing a javascript function that clicks the login button automatically
jq Code:
<script type="text/javascript">
$(document).ready(function() {
$('a.login-window, a.log').click(function() {
//Getting the variable's value from a link
var loginBox = $(this).attr('href');
//Fade in the Popup
$(loginBox).fadeIn(300);
//Set the center alignment padding + border see css style
var popMargTop = ($(loginBox).height() + 24) / 2;
var popMargLeft = ($(loginBox).width() + 24) / 2;
$(loginBox).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
// Add the mask to body
$('body').append('<div id="mask"></div>');
$('#mask').fadeIn(300);
return false;
});
// When clicking on the button close or the mask layer the popup closed
$('a.close, #mask').live('click', function() {
$('#mask , .login-popup').fadeOut(300 , function() {
$('#mask').remove();
});
return false;
});
});
</script>
HTML
<div id="login-box" class="login-popup">
<img src="close_pop.png" class="btn_close" title="Close Window" alt="Close" />
<form method="post" method="post" name="f" id="f" class="signin" action="login.php">
<fieldset class="textbox">
<label class="username">
<span>Username or email</span>
<input id="username" name="username" value="" type="text" autocomplete="on" placeholder="Username">
</label>
<label class="password">
<span>Password</span>
<input id="password" name="password" value="" type="password" placeholder="Password">
</label>
<button class="submit button" type="submit" name="Submit" value="<?php echo $lang['LOGIN'];" style="background:none;">Sign in</button>
<p>
<a class="forgot" href="#">Forgot your password?</a>
</p>
</fieldset>
</form>
</div>
if you want to auto click a button, you are looking for .trigger
$('#some-id').trigger('click');
.trigger( 'event' ) explanation:
Execute all handlers and behaviors attached to the matched elements
for the given event type.
(as you are already using jQuery, hence)
<?php
if (!$lang['LOGIN']) {
echo '<script type="text/javascript">';
echo '$(function() {';
echo '$("a.login-window, a.log").trigger("click")';
echo '});';
echo '</script>';
}
?>
var loggedIn = isUserLoggedIn(); // check login status
if(!loggedIn){
$('a.login-window, a.log').trigger('click');
}
.trigger Docs

Categories