I have a form that has several text input fields and a drop down list. The contents of the drop down list is generated by a php script to match a database structure. What I'm trying to do is to let user choose an option from the drop down list and then according to the choice update the form view by loading some text from a database and then put it in for the user to edit (AJAX style that is). I generate the whole form again with php to add the queried content to the view.
Here is the problem: now when user has made changes to the text contents of the input fields he presses a "Commit changes"-button. Now I'd have to get the changed content of the text fields to update the row in the database. I don't know how to properly do it.
I'm trying to use the POST-method of the form to deliver the changed content to the php-script, but it fails to get any content because the AJAX-style didn't really change the HTML of the page.
Here is a short reproduction of how I'm trying to achieve this:
The page head:
<head>
<script>
function updateForm(str) {
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("divContainingForm").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","/scripts/regenerateTheForm.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("id=" + str);
}
</script>
</head>
The page body:
<form action="/scripts/changeTheOldOne.php" method="post">
<div id="form">
<fieldset>
<label for='list'>Content to edit</label>
<select id='list' name="list" onchange='updateForm(this.value)' autofocus>
<?php echo(generateListOptions()); ?> //php-function
</select>
</fieldset>
<fieldset>
<label for="header">Header</label>
<input required type="text" id="header" />
</fieldset>
<fieldset>
<label for="body">Plain text</label>
<textarea required id="body" rows="16" maxlength="1500"></textarea>
</fieldset>
</fieldset>
</div>
</form>
Function from the regenerateTheFrom.php returns the generated form which now has the text in the fields and the JavaScript writes it in the page and updates the user view. User can now see the retrieved content and edit it but when the form is submitted the changeTheOldOne.php can't get the AJAX updated and user edited values of the form from the $_POST array.
Problem Solved!
It was just a noob thing. Had forgotten name labels from the input fields and that's why PHP POST couldn't get any info. I thought that the id would be enough for php but it wasn't!
Related
I'm working with Ehsan Abbasi's Ajax Live Search (ALS)
https://github.com/iranianpep/ajax-live-search
http://ajaxlivesearch.com/
which invokes MySQL, PHP & jQuery to search and display search suggestion results as you type (similarly to popular search engines).
I'm struggling with the following:
When the user copies data and pastes it into the form, thereby rendering the live search pointless, what is the syntax to pass that data into the submitted form?
What does "onResultEnter" refer to? The user hits the enter button?
What does "onAjaxComplete" refer to? The user clicks a submit button?
Here's my relevant work to put these issues into context.
First, we initialize some variables and connect to our database via PHP:
# Live search initialization.
# --
file_exists($_SERVER['DOCUMENT_ROOT'].'/als/core/Handler.php') ? require_once $_SERVER['DOCUMENT_ROOT'].'/als/core/Handler.php' : die('Handler.php not found');
file_exists($_SERVER['DOCUMENT_ROOT'].'/als/core/Config.php') ? require_once $_SERVER['DOCUMENT_ROOT'].'/als/core/Config.php' : die('Config.php not found');
use AjaxLiveSearch\core\Config;
use AjaxLiveSearch\core\Handler;
if (session_id() == '') {
session_start();
}
$handler = new Handler();
$handler->getJavascriptAntiBot();
# Connect to database.
# --
require_once($_SERVER["DOCUMENT_ROOT"]."/connect.php");
global $dbc;
# Initialize required CSS and JavaScript files to be included.
# --
$additional_css = "<link href=\"/als/css/ajaxlivesearch.css\" rel=\"stylesheet\" type=\"text/css\" />";
$additional_js = "<script type=\"text/javascript\" src=\"/als/js/ajaxlivesearch.js\"></script>";
We next include two distinct forms to execute unrelated searches:
<!-- Model number search form -->
<form role="form" id="productsSearch" action="search-models.php" method="get" class="search-form">
<div class="input-group">
<input type="text" name="model_number" id="models" class="form-control modelSearch" placeholder="Enter your model number">
<input type="hidden" name="model_number" id="model_number">
<span class="input-group-btn">
<button type="submit" class="btn btn-default" onclick="return model_validator();">Go</button>
</span>
</div>
</form>
<!-- Part number search form -->
<form onsubmit="return part_validator();" action="search-parts.php" role="form" method="get">
<div class="input-group">
<input type="text" name="part_number" id="parts" class="form-control partSearch" placeholder="Enter your part number">
<input type="hidden" name="part_number" id="part_number">
<span class="input-group-btn">
<button type="submit" class="btn btn-default">Go</button>
</span>
</div>
</form>
Note here that the model search form involves an onclick event to validate model numbers. Similarly, the part number search form invokes an onsubmit event to validate part numbers. Both of these events were in our custom code before ALS entered the picture.
In addition, we have included a hidden field in each form to contain the value selected by the user in the ALS to be passed into the form when submitted to the action scripts.
These hidden field values are set in ALS functions associated with each of these input forms:
<!-- Model search: ALS functions -->
<script>
jQuery(document).ready(function() {
jQuery(".modelSearch").ajaxlivesearch({
onResultClick: function(e, data) {
// Get the index 0 (first column) value.
var selectedOne = jQuery(data.selected).find('td').eq('0').text();
// Set the input value.
jQuery('#models').val(selectedOne);
// Hide the result.
jQuery("#models").trigger('ajaxlivesearch:hide_result');
// Set the hidden field value.
$('input[name=model_number]').val(selectedOne);
},
onResultEnter: function(e, data) {
// What does this refer to? The user hits the enter button?
},
onAjaxComplete: function(e, data) {
// What does this refer to? The user clicks a submit button?
}
});
})
</script>
<!-- Part search: ALS functions -->
<script>
jQuery(document).ready(function() {
jQuery(".partSearch").ajaxlivesearch({
onResultClick: function(e, data) {
// Get the index 0 (first column) value.
var selectedOne = jQuery(data.selected).find('td').eq('0').text();
// Set the input value.
jQuery('#parts').val(selectedOne);
// Hide the result.
jQuery("#parts").trigger('ajaxlivesearch:hide_result');
// Set the hidden field value.
$('input[name=part_number]').val(selectedOne);
},
onResultEnter: function(e, data) {
// What does this refer to? The user hits the enter button?
},
onAjaxComplete: function(e, data) {
// What does this refer to? The user clicks a submit button?
}
});
})
</script>
I'd very much appreciate any help troubleshooting the syntax to get data that's copied by users from unknown sources & pasted into either of these forms and passed into the form action search scripts. Any light that could be shed on the onResultEnter and onAjaxComplete functions would likewise be welcomed.
If there's any additional information I can pass along to assist troubleshooting, do please let me know!
Best,
Allison
It doesn't exactly have to be a div, it can be anything, a article section a ...
I'm making a website for a university project, the website is similar to DropBox (file hosting website). NON COMMERCIAL!
I'm on the registration page at the moment and what I want to do is after the user presses the submit button I want to change the content of a div tag which is next to the field which is wrongly entered.
For example, if the user types in a password that is less than 3 characters long an "X" will appear in the div tag next to the password field and under the submit button a message will appear saying "Password must be more than 3 characters."
This is part of the code, not posting all of it because it's too long.
<form action="register.php" method="post" >
<section>
<article>Password*</article>
<input type="text" name="password" id="password" required="required"/>
<div id="right_or_wrong"></div> <!-- tick - ✓ , wrong - X -->
</section>
<input type="submit" name="register" value="Register" />
<div id="error_msg"></div>
</form>
I have tried to search on how to do this but I can't find anything and I just can't figure it out.
I know I can put the PHP code in the div tag and assess it from there but I want to put the code at the bottom of the form to make it neater.
So in register.php when you validated the form and see that the password was too short, you can set a variable like $password_error = "Password must be more than 3 characters.".
Then you can just re-render the form and
<div id="right_or_wrong"><?php echo $password_error; ?></div>
You can validate before sending the form to the server, with simple onsubmit function:
<script>
function validate(){
// here, check the password and other answers
if( /* check password here */ ){
document.getElementById("right_or_wrong_password").innerHTML="X";
document.getElementById("error_msg").innerHTML="Password must be more than 3 characters.";
return false; // prevent from submitting form
}else if( /* check field1 here */ ){
document.getElementById("right_or_wrong_field1").innerHTML="X";
document.getElementById("error_msg").innerHTML="Error in the field......";
return false; // prevent from submitting form
}else{
return true; // the form can be submitted
}
}
</script>
<form action="register.php" method="post" >
<section>
<article>Password*</article>
<input type="password" name="password" id="password" required="required"/>
<div id="right_or_wrong_password"></div> <!-- tick - ✓ , wrong - X -->
</section>
<input type="submit" name="register" value="Register" onsubmit="validate()" />
<div id="error_msg"></div>
</form>
In this way, you can verify each field of the form (answers structure only). Then a server validation is always necessary.
PHP can't do that alone. PHP is server-scripting - it can't run on user's machine and handle live events.
Instead, use Javascript's AJAX and call a php file which would return the text. And, then use Javascript to append that text to div or whatever you want.
I am fine getting the value of a form controls such as radio and select for example but with all of the additional non form based controls available for Bootstrap i haven't really seen many PHP examples how to use these.
So my main question is with pure PHP how would you retrieve the current selected item from a div and li based dropdown?
http://www.bootply.com/b4NKREUPkN
or a custom color picker plugin?
http://bootstrapformhelpers.com/colorpicker/#jquery-plugins
If you are submitting a form and handling the request using PHP, you will not be able to access the DOM in PHP (client vs server). If you can pull out the bits that you need using javascript, you can set the values on hidden form elements and submit.
<?php
// print out the value when the post is submitted
if (isset($_POST["extraInput"])) {
echo "hidden input is: " + $_POST["extraInput"];
}
?>
<html>
<head>
<script type="text/javascript">
function doSubmit () {
var extraValue = document.getElementById("extra").innerHTML;
var form = document.forms["myForm"];
form.elements["extraInput"].value = extraValue;
form.submit();
}
</script>
</head>
<div id="extra">Hello world</div>
<body>
<form id="myForm" action="" method="post">
<input type="hidden" name="extraInput" />
<input type="text" name="textInput" />
<button onclick="javascript:doSubmit()">Submit</button>
</form>
</body>
</html>
I'm working on a simple webpage for a company and the company wants to be able to edit the content themselves from time to time. However they have no programing knowledge and therefore I want to use an embedded HTML editor, I have chosen jQuery TE.
The problem is that I only know how to use this as a form, e.g.:
<form id = "wyForm" method="post" action="test.php">
<textarea class="editor"name = "testText">Hi</textarea>
<input type="submit" class="wymupdate" />
</form>
Then I would convert the textarea to an editor with jQuery:
<script> $('.editor').jqte() </script>
This makes it possible to send the result to a .php page that updates the database. However many times I don't want to use a textfield or a form, but just a simple object that I convert to an editor in the same way. But how do I save the change in that case?
Catch the form submit event and copy the content to a hidden field.
<form id = "wyForm" method="post" action="test.php">
<div class="editor" name="testText">Hi</div>
<input type="submit" class="wymupdate" />
<input type="hidden" id="editorHiddenField" />
</form>
...
$('#wyForm').submit(function() {
$('#editorHiddenField').val($('.editor').html());
});
You may need to use an API to get the content instead (I'm not familiar with the plugin), but the concept is sound.
Edit - If you don't want to use a form at all:
<div class="editor></div>
<button id="SaveButton">Save</button>
...
$(document).ready(function() {
$('#SaveButton').click(function(e) {
e.preventDefault();
$.post('savepage.php', { data: $('.editor').html() }).done(function() { alert('saved!'); });
});
});
So I have this html code
<div id="wrap">
<div id="header">
</div>
<div id="content">
<form method="POST" action="code.php">
Name:
<input type="text" name="name" size="50">
<input type=submit value="Get Code">
</form>
</div>
<div id="footer">
</div>
Is it possible to load the code.php after the user clicks submit into the #content div?
Essentially, what I want is when the user clicks the submit button, the code.php after processing is loaded onto the same #content div.
So let say in my code.php, after processing the inputted data, I come up with this lilne of code,
<?php
some processing code here;
$name = 'john';
echo $name;
?>
So then after hitting submit, user would see
<div id="content">
john
</div>
Hope I didn't complicate my question by repeating myself, please let me know if this is possible with javascript, php or whatever.
Thanks for the read!
#JohnP yes, $.load is a good solution. However, you'll need to send the form data in the request:
UPDATED [3] for sending a POST with multiple fields and checkboxes:
$('form').submit(function(){
// create an object to send as a post
var form = this,
fields = form.elements,
el,
post = {};
for (var i = fields.length; i--; ) {
el = fields[i];
if (el.name) {
switch (el.type) {
case 'checkbox':
case 'radio':
post[el.name] = (el.checked) ? el.value : '';
break;
default:
post[el.name] = el.value;
}
}
}
// send the form data in the load request...
$('#content').load(this.action, post);
return false;
});
This will send the data as a POST.
Since you've tagged jQuery, I'll use a jQuery example
$(document).ready(function(){
$('form').submit(function(){
$('#content').load('code.php');
return false;
})
})
This makes a couple of assumptions here
This assumes that code.php is in the same path that you are in now.
There is only one form in the page.
As #johnhunter points out, this example obviously won't work with post. You can send the post data along with the method. See here for usage : http://api.jquery.com/load
EDIT
Here's a fiddle example : http://jsfiddle.net/jomanlk/J4Txg/
It replaces the form area with the content from jsfiddle/net/echo/html (which is an empty string).
NOTE 2 Make sure to include the code in $(document).ready() or include it at the bottom of the page. It goes without saying you need jQuery in your page to run this.
You might want to check out jquery form plugin http://jquery.malsup.com/form/#
in simple way use
<div id="content">
if(isset($_POST['submit'] && !empty($_POST) )
{
// do your all post process
$name ='John';
echo $name;
}
else {
<form method="POST" action="$_SERVER['PHP_SELF']">
<label for="uname" >Name:</label><input type="text" name="uname" id="uname" size="50">
<input type=submit value="Get Code" name="submit">
</form>
}
</div>