Must submit form twice - php

I have the following script. It works in jsFiddle
The problem is when I fill in the title AND the text box I have to submit TWICE.
Does someone have an idea of what I'm doing wrong?!
form:
<form id="formid" class="form" method="POST" action="/">
<div>
<label class="title">Title</label>
<div id="titleError"></div>
<input type="text" id="title" name="title" value="">
</div>
<div>
<label class="title">Text</label>
<div id="textError"></div>
<textarea name="text" id="text" rows="14" cols="50"></textarea><br />
</div>
<div>
<input class="btn btn-success" type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
JS:
<script type='text/javascript'>
$(document).ready(function() {
$("#formid").submit( function(event) {
tinyMCE.triggerSave();
var title = $('#title').val();
var text = $('#text').val();
if( title.length === 0 || text.length === 0 ){
if( title.length === 0 ){
$("#titleError").html("<p>Title verplicht</p>");
event.preventDefault();
}
if( text.length === 0 ){
$("#textError").html("<p>Text verplicht</p>");
event.preventDefault();
}
$("html, body").animate({ scrollTop: 0 }, 600);
}
else{
tinyMCE.triggerSave();
/* stop form from submitting normally */
event.preventDefault();
/* Send the data using post */
var posting = $.post( 'http://domain.nl/admin/pages/create', {
title: $('#title').val(),
text: $('#text').val()
});
/* Put the results in the show-content div */
posting.done(function( data ) {
//alert(data);
$.ajax({
url: "<?php echo base_url() ?>/admin/pages",
type: 'GET',
success: function(data) {
$("#show-content").hide().html( data).fadeIn(1500);
}
,
error: function() {
alert("error");
}
});
});
}
});
});
</script>
The solution:
I add this
tinyMCE.triggerSave();
after
$("#formid").submit( function(event) {
and now it works correctly!

Related

I want the appearance of div when the conditions in the php file

Hi I want to show the div (msga) when the first condition i want the appearance of div (msgb) when the second condition
my php code
if(isset($_POST['aa'])) {
echo "a";
}
if (isset($_POST['bb']))) {
echo "b";
}
my ajax code
<script>
$('#form')
.submit( function(e) {
$.ajax({
url: 'php.php',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false,
success: function(response){
if (response == 'a') {
$('#msga').show();
}else if (response == 'b') {
$('#msgb').show();
}
}
});
});
</script>
my html code
<div id="msga" style="display: none;">aaaaaaaaaa</div>
<div id="msgb" style="display: none;">bbbbbbbbbb</div>
<form id="form" method="post" enctype="multipart/form-data">
<input name="test" type="text" value="test"/>
<input class="up" type="file" name="up" />
<button class="submit">send now</button>
</form>
First things, you have an error on your php.php
hence your code never execute as you expected.
Parse error: syntax error, unexpected ')' in
.... on line 7
this is line 7 :
if (isset($_POST['bb']))) { You have an extra ")"
and the space between the if ( will give u errors.
and also
$_POST['aa'] and $_POST['bb']
does not exist.
And when you click the submit button your page will load a little trying to submit the form by the default form action, because you did not prevent it with e.preventDefault();
This how your code should be
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div id="msga" style="display: none;">aaaaaaaaaa</div>
<div id="msgb" style="display: none;">bbbbbbbbbb</div>
<form id="form" method="post" enctype="multipart/form-data">
<input name="test" type="text" value="test"/>
<input class="up" type="file" name="up" />
<button class="submit">send now</button>
</form>
<script>
$('document').ready(function(){
$('#form').submit( function(e) {
// e.preventDefault();
$.ajax({
url: 'php.php',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false,
success: function(response){
// console.log(response);
if (response == 'a') {
// $('#msga').show();
$("#msga").css("display", "block");
}else if (response == 'b') {
$('#msgb').css("display", "block");
}
}
});
});
});
</script>
Then php.php
<?php
if(isset($_POST['test'])) {
echo "a";
}
if(isset($_POST['up'])) {
echo "b";
}
?>
Your form has no input with name="aa" or name="bb" so the response data to the ajax call is always empty.

Cannot pass textarea input to a PHP variable

To begin, I'm working with 3 languages. HTML, Javascript and PHP. I'm unable to pass user inputted textarea text to a PHP variable which would be used as a message in an email that would be sent out. What I believe to be the problem is that my textarea is actually in a modal window and for some reason I think that is what is screwing things up.
Here is my HTML Code:
<form name="rejectForm" action="">
<div class="rejectModal" title="rejectModal" id="rejectModal" style="display: none; padding:15px ">
<b> Text in the modal window</b>
<center>
<textarea id="rejectArea" name="rejectArea" value="{$rejectAreaNote}" rows="6" cols="43"/> </textarea>
</center>
<br/>
<center>
<input type="button" value="Reject" class="btn success id="submitReject"" id="btnRejectDocumentModal" name="Reject" />
<input class="btn" type="reset" value="Cancel" id="btnCancelSaveModal" />
</center><br/><br/>
</div>
</form>
</div>
JS Code:
$(function() {
$(".submitReject").click(function() {
// validate and process form here
$('.error').hide();
var rejectAreaNote = $("textarea#rejectArea").val();
var noteLength = rejectAreaNote.length;
if (rejectAreaNote == "" || noteLength < 5) {
$("label#rejectArea_error").show();
$("textarea#rejectArea").focus();
return false;
}
var dataString = rejectAreaNote;
alert (dataString);return false;
$.ajax({
type: "POST",
url: "gs_ViewDocument.php",
data: dataString,
success: function() {
$('#reject_form').html("<div id='message'></div>");
$('#message').html("Reject Form Submitted!");
}
});
return false;
});
});
What creates the Modal (JS):
$('.rejectModal').css("background", "lightblue");
$('#btnRejectDocument').bind(isTouchScreen ? "touchstart" : "click", function(){
if (!gsSelection.unselectElem()) return false;
$('.rejectModal').dialog({
modal:true,
resizable:false,
width: 400,
}).removeClass("ui-widget-content");
$(".ui-dialog-titlebar").hide();
return;
});
$('#btnRejectDocumentModal').bind(isTouchScreen ? "touchstart" : "click", function(){
$(this).parents('div.rejectModal').dialog('close');
});
$('#btnCancelSaveModal').bind(isTouchScreen ? "touchstart" : "click", function(){
$(this).parents('div.rejectModal').dialog('close');
});
PHP Code:
if(isset($_POST['Reject'])&&$_POST['Reject']=='Reject')
{
$isReject = true;
RejectAction($DocumentID, $ClientName, $ClientEmail);
$smartyvalues["isReject"] = $isReject;
$smartyvalues["RejectMsg"] = "The document invitation was successfully rejected!";
}
Any help is greatly appreciated.
Try the below is should fix it :
<textarea id="rejectArea" name="rejectArea" rows="6" cols="43"> {$rejectAreaNote}</textarea>
you were closing your textarea tag twice /> and then </textarea>
<input type="button" value="Reject" class="btn success id="submitReject"" id="btnRejectDocumentModal" name="Reject" />
The closing quotes here are wrong (Two quotes after submitReject).

Jquery - How to populate form fields in a modal form from a dynamic list in another modal?

Okay, I'll try to be as clear as I can with this.
I have a page with a team's roster that you can add and delete from. When you decide to add a player, you click the "Add Player" button which, using Jquery-UI, loads a dialog modal with a form. You can fill in the form and submit and it works great. I've also added a "Search" button that, when clicked, loads another modal that lets you search a DB of exists players. When it retrieves search results it loads them in an OL. Now this is where it gets tricky:
I would like to have a button called "Use player info" that, when clicked, closes the search modal and auto-fills the the form fields with the selected player's information.
Here is the code for the search modal:
Script (in the head):
<script type="text/javascript">
$(function() {
$(".search_button").click(function() {
var search_word = $("#search_box").val();
var dataString = 'search_word='+ search_word;
if(search_word==''){
} else {
$.ajax({
type: "GET",
url: "searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<img src="ajax-loader.gif" align="absmiddle"> Loading Results...');
},
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
}
});
}
return false;
});
});
</script>
HTML
<div id="search" align="center">
<div style="width:500px">
<div style="text-align:center; padding-top:10px" class="title">Player Search</div>
<div style="margin-top:20px; text-align:left">
<form method="get" action="">
<div style="margin:0; padding:0; float:left">
<input type="text" name="search" id="search_box" class='search_box'/>
</div>
<div style="margin:0; padding:0; float:left; padding-left:8px; font-size:16px">
<input type="submit" value="Search" class="search_button" />
</div>
</form>
</div>
<div style="width:480px; padding-left:10px; padding-right:10px;">
<div id="flash"></div>
<ol id="insert_search" class="update"> </ol>
</div>
</div>
</div>
Here is the php code for the actual search function:
<li><div id="all">
<div id="result"><div id="names"><div id="lnames"><?php echo $final_msg; ?></div><div id="fnames"> <?php echo $firstName ?></div></div><div id="dobs"><?php echo $DOB ?></div><div id="ids"><?php echo $ID ?></div>
<div id="add"><button type="button" id="add_player2" > Add Player </button></div></div>
</div></li>
And here is the code for the form modal I want he information to be put in:
<script>
$(function() {
$( "#search" ).dialog({
autoOpen: false,
width: 550,
modal: true,
resizable: false,
buttons: {
Cancel: function() {
$( this ).dialog( "close" );
}
},
close: function() {
allFields.val( "" ).removeClass( "ui-state-error" );
}
});
$(".search_button").click(function() {
var search_word = $("#search_box").val();
var dataString = 'search_word='+ search_word;
if(search_word=='')
{
}
else
{
$.ajax({
type: "GET",
url: "../../Search/searchdata.php",
data: dataString,
cache: false,
beforeSend: function(html) {
document.getElementById("insert_search").innerHTML = '';
$("#flash").show();
$("#searchword").show();
$(".searchword").html(search_word);
$("#flash").html('<img src="ajax-loader.gif" align="absmiddle"> Loading Results...');
},
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
}
});
}
return false;
});
});
</script>
<script>
$(function() {
$("#dialog-form").dialog({autoOpen:!1, height:380, width:350, modal:!0, buttons:{
"Search for Player":function() {
$( "#search" ).dialog( "open" );
},
"Add Player":function() {
$("#myForm").ajaxSubmit({success:function() {
window.location = ""
}});
$(this).dialog("close")
},
Cancel:function() {
$(this).dialog("close")
}
},
create:function () {
$(this).closest(".ui-dialog")
.find(".ui-button:contains(Search for Player)") // the first button
.addClass("green");
}});
$("#add-player").button().click(function() {
$("#dialog-form").dialog("open")
})
});
</script>
<div id="dialog-form" title="Add Player">
<form name="myForm" id="myForm" action="../../php/add_player_comp_script_test.php?id=<? echo $table ?>" method="post" enctype="multipart/form-data">
<fieldset>
<label for="last_name_add">Last Name</label>
<input type="text" name="last_name_add" id="last_name_add" class="text ui-widget-content ui-corner-all" />
<label for="first_name_add">First Name</label>
<input type="text" name="first_name_add" id="first_name_add" class="text ui-widget-content ui-corner-all" />
<label for="id_add">ID Number</label>
<input type="text" name="id_add" id="id_add" value="" class="text ui-widget-content ui-corner-all" />
<label for="jersey_add">Jersey Number</label>
<input type="text" name="jersey_add" id="jersey_add" value="" class="text ui-widget-content ui-corner-all" />
<label for="dob_add">DOB (YYYY-MM-DD)</label>
<input type="text" name="dob_add" id="dob_add" value="" class="text ui-widget-content ui-corner-all" />
</fieldset>
</form>
</div>
Thanks for any and all help!
I am assuming that this-
<li><div id="all">
<div id="result"><div id="names"><div id="lnames"><?php echo $final_msg; ?></div><div id="fnames"> <?php echo $firstName ?></div></div><div id="dobs"><?php echo $DOB ?></div><div id="ids"><?php echo $ID ?></div>
<div id="add"><button type="button" id="add_player2" > Add Player </button></div></div>
</div></li>
is the html in this success function-
success: function(html){
$("#insert_search").show();
$("#insert_search").append(html);
$("#flash").hide();
}
If so, it would be better if you returned a json encoded array json_encode(), instead of html - eg.
[{"lname":"Jones","fname":"Joe","dob":"2000-01-13","id":"6"},
{"lname":"Jones","fname":"Jim","dob":"2001-04-04","id":"19"},
{"lname":"Jones","fname":"Bob","dob":"1999-10-23","id":"32"}]
php code on ../../Search/searchdata.php would be something like -
while($row = _fetched_array_) {
$players[] = array(
'lname' => $row['lname'],
'fname' => $row['fname'],
'dob' => $row['dob'],
'id' => $row['id']
);
}
// Return JSON Encoded Array
echo json_encode($players);
Then you can create links for each one, and on selecting the player it will add it to your form fields
success: function(html){
players = $.parseJSON(html); //create json array in format above
player_links = ''; // create blank variable
for (var i = 0; i < players.length; i++){ // loop through each of the returned players
// Echo Player First & Last Name and a link to add
player_links += '<li>' + players[i].lname + ' ' + players[i].fname + ' Add Player</li>';
}
$("#insert_search").show();
$("#insert_search").append(player_links);
$("#flash").hide();
// Bind .player_details click
$('.player_details').click(function () {
var pid = $(this).data('player');
$('#last_name_add').val(players[pid].lname);
$('#first_name_add').val(players[pid].fname);
$('#id_add').val(players[pid].id);
$('#dob_add').val(players[pid].dob);
$("#search").dialog("close");
});
}
I have created a simple example of this as a jsFiddle - http://jsfiddle.net/8jcLQ/

Get the textbox Text using ajax on button click

I want a code for get textbox value when submit button is clicked. It must be Ajax.Here is the code I tried so far.But I culdent get to work....
<form action="" method="post">
<p>Route No :
<input type="text" name="route_no" required="required" />
<input type="submit" value="Search" name="search" />
</form>
Ajax Code
<script type="text/javascript">
$(document).ready(function() {
$("#sub").click(function() {
var textboxvalue = $('name or id of textfield').val();
$.ajax({
type: "POST",
url: 'ajaxPage.php',
data: {txt1: textboxvalue},
success: function(result) {
$("div").html(result);
}
});
});
});​
</script>
PHP code
$txt = null;
if((isset($_POST)) && (isset($_POST['txt1'])))
{
echo $txt = $_POST['txt1'];
}
HTML:
<label for="route_no">Route No:</label><input type="text" id="route_no" name="route_no" required="required" />
<input type="button" value="Search" id="search" />
<div id="result"></div>
JavaScript:
$(document).ready(function()
{
$("#search").click(function()
{
var textboxvalue = $('input[name="route_no"]').val();
$.ajax(
{
type: "POST",
url: 'ajaxPage.php',
data: {txt1: textboxvalue},
success: function(result)
{
$("#result").html(result);
}
});
});
});​
ajaxPage.php:
if(isset($_POST) && isset($_POST['txt1']))
{
echo $_POST['txt1'];
}
You have problem here
$("#sub").click(function() {
you are using id ="sub" for submit button but you are not assigning id to that button so give id to submit button as id="sub".
To get the value of the textbox you can use:
$('#elementid').val()

Ajax not being fired?

I'm using the jquery validator plugin, and I'm trying to make my first attempt with AJAX to it.
Right now, I have the following HTML code:
<div class="grid_12" id="info">
</div>
<div class="grid_12">
<div class="block-border">
<div class="block-header">
<h1>Inserir nova página</h1><span></span>
</div>
<form id="formulario" class="block-content form" action="<?=$_SERVER['PHP_SELF'];?>" method="post">
<div class="_100">
<p><label for="textfield">Nome da página</label><input id="page_name" name="textfield" class="required text" type="text" value="" /></p>
</div>
<div class="_100">
<p><label for="textarea">Conteúdo da página</label><textarea id="page_content" name="textarea" class="required uniform" rows="5" cols="40"></textarea></p>
</div>
<div class="block-actions">
<ul class="actions-left">
<li><a class="button red" id="reset-validate-form" href="javascript:void(0);">Limpar</a></li>
</ul>
<ul class="actions-right">
<li><input type="submit" class="button" name="send" value="Inserir"></li>
</ul>
</div>
And my JS code:
<script type="text/javascript">
$().ready(function() {
/*
* Form Validation
*/
$.validator.setDefaults({
submitHandler: function(e) {
$.jGrowl("Ação executada com sucesso.", { theme: 'success' });
$(e).parent().parent().fadeOut();
/*
* Ajax
*/
var mypostrequest=new ajaxRequest();
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("info").innerHTML=mypostrequest.responseText;
}
else{
alert("An error has occured making the request")
}
}
}
var page_name=encodeURIComponent(document.getElementById("page_name").value);
var page_content=encodeURIComponent(document.getElementById("page_content").value);
var parameters="page_name="+page_name+"&page_content="+page_content;
mypostrequest.open("POST", "ajax/inserir_utilizador.php", true);
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
mypostrequest.send(parameters);
v.resetForm();
v2.resetForm();
v3.resetForm();
return false;
}
});
var v = $("#create-user-form").validate();
jQuery("#reset").click(function() { v.resetForm(); $.jGrowl("User was not created!", { theme: 'error' }); });
var v2 = $("#write-message-form").validate();
jQuery("#reset2").click(function() { v2.resetForm(); $.jGrowl("Message was not sent.", { theme: 'error' }); });
var v3 = $("#create-folder-form").validate();
jQuery("#reset3").click(function() { v3.resetForm(); $.jGrowl("Folder was not created!", { theme: 'error' }); });
var formulario = $("#formulario").validate();
jQuery("#reset-validate-form").click(function() { formulario.resetForm(); $.jGrowl("O formulário foi limpo!", { theme: 'information' }); });
});
I have a div #info without anything in it that I'm trying to put there the result of the ajax.
My ajax file is just trying to echo the POST values:
<?php
$page_name=$_POST["page_name"];
$page_content=$_POST["page_content"];
echo $page_name."<br />";
echo $page_content;
?>
But it really doesn't work. It really doesn't do anything, or if it does, it refreshes the page.
What am I missing?
Regards and thanks!
I recommend you to use $.ajax() or $.post().
It's much easier and your headache will surely go away.
$.ajax({
type: 'POST',
url: 'url to post',
data: data,
success: function(data, status) {
//callback for success
},
error: error, //callback for failure
dataType: "json" //or "html" etc
});
many examples here:
http://api.jquery.com/jQuery.post/
http://api.jquery.com/jQuery.ajax/

Categories