Validating Ajax loaded form - php

I've tried searching everywhere(the past 2 hours), and I've tried all these different solutions and nothing has worked for me thus far. So I thought I would come here and ask the geniuses that be. Since my Jquery isn't very good. I know it has something to do with id's and such not loaded when the script is up, but I don't know how to go about fixing this.
The code I'm about to show I'm certain isn't the best. I've only been doing this for a few months. So please be patient with me.
Below is the main.php file:
echo "<div class=\"main_menu_buttons\">";
echo "<table id=\"nav\">";
echo "<tr><td>";
echo "<ul id=\"nav\">";
echo "<li><button class=\"pm_button\" onclick=\"masspm('new', 'menu')\">New</button></li>";
echo "<li><button class=\"pm_button\" onclick=\"masspm('edit', 'menu')\">Edit</button></li>";
echo "<li><button class=\"pm_button\" onclick=\"masspm('view', 'menu')\">View</button></li>";
echo "</ul>";
echo "</td></tr>";
echo "</table>";
echo "</div>";
echo "<span id=\"wait_1\" style=\"display: none;\">";
echo "<img alt=\"Please Wait\" src=\"/opserv/regimental/ajax-loader.gif\"/>";
echo "</span>";
echo "<span id=\"result_1\">";
// This is the default load screen. This will change every time we click a button.
echo "<div class=\"editor\">";
echo "<br><span class=\"header\">List of your PM groups:</span><br>";
$resultVB = $mysqliVB->query("my query");
if ($resultVB->num_rows > 0){
while ($rowVB = $resultVB->fetch_assoc()){
echo " - ".$rowVB['name']."<br>";
}
}else{
echo " - You have no groups.<br>";
}
echo "</div>";
// End of Default Load screen
echo "</span>";
-------
//Here is the script for loading ajax
<script type="text/javascript">
function masspm(type, arg, global) {
$('#wait_1').hide();
$('#wait_1').show();
$('#result_1').hide();
$.get("/forum/opserv/ajaxselect.php", {
func: type,
drop_var: arg
}, function(response){
$('#result_1').fadeOut();
setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400);
});
return false;
}
function finishAjax(id, response) {
$('#wait_1').hide();
$('#result_1').show();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
</script>
I used to have the validation file in this file. But was told not to put it in this file and use it in my ajax called file which is ajaxselect.php
Now here is the ajaxselect.php
echo "<div class=\"editor\">";
echo "<br><span class=\"header\">Create New PM Group:</span><br>";
echo "<form name=\"new\" action=\"/forum/opserv/addon_pmgroup.php?op=addpmgroup\" method=\"post\" onSubmit=\"return validate();\">";
echo "Group Name: <input type=\"text\" name=\"name\"><br><br>";
echo "<table border=1 class=\"pmTable\"><tbody><tr>";
$i = 0;
while ($rowVB = $resultVB->fetch_assoc()){
if ($i > $rows){
echo "</td><td>";
$i = 0;
}elseif ($i == 0){
echo "<td>";
}
echo "<input type=\"checkbox\" id=\"member".$rowVB['userid']."\" name=\"members[]\" class=\"aar-checkbox\" value=\"".$rowVB['userid']."\"/><label for=\"member".$rowVB['userid']."\" class=\"aar-label\"></label> ".$rowVB['username']."<br>";
$i++;
}
echo "</tbody></table>";
echo "<br><input type=\"submit\" name=\"submit\" id=\"submit\" value=\"Submit\"/>";
echo "</form>";
echo "</div>";
And then here I have the validation script which is also in the ajaxselect.php
<script type="text/javascript">
function validate(){
msg = ""
if(document.new.name.value.length < 3){
msg += "Please enter a valid name\n";
}
if ($("#new input:checkbox:checked").length == 0) {
msg += "Please select a member\n";
}
if ($("#new input:checkbox:checked").length > 30 ) {
msg += "You many only have 30 members per group\n";
}
if(msg != ""){
alert(msg);
return false;
}else{
return true;
}
}
</script>
I'm pretty sure its possible, but I'm lost as to how to make it actually validate the info.
If someone would be so kind, I would appreciate any help.

Related

How to update HTML DIV from PHP conditional

I am trying to update a HTML DIV dynamically while updating some information in a MySQL database, without reloading the page. How do I get this HTML DIV to update?
echo "<td id=\"trade_refs_update\">".(($results[$k]["trade_references_supplied"] == "Yes") ? "<img src=\"images/checkmark.png\" width=\"20\" height=\"20\" />" : "")."</td>";
Here's the PHP code:
if(isset($_REQUEST["edit_app"]))
{
$columnname=$_REQUEST["column"];
$value=$_REQUEST["editval"];
if ($set_trade_references == 'Yes') {
$sql_update=('UPDATE apps_data set `'.$columnname.'` = "'.$value.'", "trade_refs" = "Yes" WHERE app_id='.$app_id.';');
echo "<script>$('#\"trade_refs_update\"').html('\"<img src=\"images/checkmark.png\" width=\"20\" height=\"20\" />\"');</script>";
} else {
$sql_update=('UPDATE apps_data set `'.$columnname.'` = "'.$value.'" WHERE app_id='.$app_id.';');
echo "<script>$('#\"trade_refs_update\"').html('\"<img src=\"images/error.png\" width=\"20\" height=\"20\" />\"');</script>";
}
$results = $db_handle->executeQuery($sql_update);
if ($DEBUG =='On'){
echo "columnname: ".$columnname."<BR>";
echo "value: ".$value."<BR>";
echo "sql_update: ".$sql_update."<BR>";
}
}
I think you're searching for Ajax! :)

How To Parts Of Speech Only One Time In PHP

I want to show only one time the heading of parts of speeches for example when user enter the word "Spell" all the parts of speeches and its meaning come every time .
The headings are repeating multiple times . i want to print only one time
There should be a heading Of Noun,Verb,Adjective etc..
like this
Noun.
Verb.
adjective.
this is my code
while($row=mysql_fetch_array($sql)){
echo "<div id='wordid' style='display:none'>".$row["wordid"]."</div>";
echo $count++." : ".$row['definition']. " ";
if($row['pos']=="n"){
echo "(Noun) <br/>";
}
if($row['pos']=="s"){
echo "(Subject) <br/>";
}
if($row['pos']=="p"){
echo "(Proverb) <br/>";
}
if($row['pos']=="a"){
echo "(Adjective) <br/>";
}
if($row['pos']=="v"){
echo "(Verb) <br/>";
}
}
You can keep track of what the last wordid was and only echo the header if it changed.
// initialize to avoid notices
$lastWordId = '';
while($row=mysql_fetch_array($sql)){
if ($lastWordId != $row['wordid']) {
echo "<div id='wordid' style='display:none'>".
$row["wordid"].
"</div>";
$lastWordId = $row['wordid'];
}
echo $count++." : ".$row['definition']. " ";
if($row['pos']=="n"){
echo "(Noun) <br/>";
}
if($row['pos']=="s"){
echo "(Subject) <br/>";
}
if($row['pos']=="p"){
echo "(Proverb) <br/>";
}
if($row['pos']=="a"){
echo "(Adjective) <br/>";
}
if($row['pos']=="v"){
echo "(Verb) <br/>";
}
}

Validate form so End Date can not be before Start Date. - PHP

I have this part of a form where it shows end start and end date. I have validated it so that if no date is entered then an error message will show asking the use to enter a date, however, I need it to also check that the end date is not before the start date and echo an error asking the user to make sure the end date is after the start date if this happens. It's probably something very simple but I just can't figure out the correct code. Thanks.
// event start date
echo "<li class='cf'>";
echo "<label for='startdate'>Start date</label>";
echo "<div class='input'>";
echo "<input name='startdate' class='eventdate' placeholder='DD/MM/YYYY' type='date' value='";
if (!is_null($postedData['startdate'])) { echo $postedData['startdate']; };
echo "' />";
if($failedData['startdate']) { echo "<p class='error'>Please enter the date of your event.</p>"; }
echo "</div>";
echo "</li>";
echo $postedData['startdate'];
// event end date
echo "<li class='cf'>";
echo "<label for='enddate'>End date</label>";
echo "<div class='input'>";
echo "<input name='enddate' class='eventdate' placeholder='DD/MM/YYYY' type='date' value='";
if (!is_null($postedData['date'])) { echo $postedData['date']; };
echo "' />";
if($failedData['enddate']) { echo "<p class='error'>Please enter the date of your event.</p>"; }
echo "</div>";
echo "</li>";
echo $postedData['enddate'];
echo "<li class='cf'>";
echo "<label for='timestart'>Event time</label>";
echo "<div class='input inputs'>";
You can get a simple idea
$a = "2014-01-01";
$b = "2014-02-01";
$date1 = strtotime($a);
$date2 = strtotime($b);
if($date1 > $date2){
// Date one is >
}
else{
// Date 2 is >
}
Date can be formatted in php

Form submission adds a <br> in front of the beginning text in the form

Ok, I am using a PHP editing form (previous person built) that submits data into an MSSQL database this works fine however when the information is submitted into the database and later retrieved the the form page (for editing) there is a <br> at the beginning of the text. If the fields start with a <ul> that <br> is not inserted. I have been trying to figure out how to stop this. One thing I tried ends up removing all <br> in the text which makes the formatting disappear, How can I keep it from inserting the <br> at the top but keeping the <br> everywhere else? here is the code I have: ( I am giving you everything up to the first field where I have the issue appear)
function fromhtml ($x) {
$x = preg_replace("/<p>/i","\n\n",$x);
//$x = preg_replace("/<br>/i","\n",$x);
$x = preg_replace("/<li>/i","\n<li>",$x);
return $x;
}
$PHP_SELF = $_SERVER['PHP_SELF'];
$course_id = #$_GET["course"];
if ($course_id == "") {
$sqlquery = "SELECT id, title, goals, outline, reference, deliverymode, updated2 = CONVERT(VARCHAR(19), updated, 120)
FROM courses WHERE division_id = '$division_id' ORDER by id";
$result = mssql_query($sqlquery);
$number = mssql_num_rows($result);
print "<table border=1 id=\"content_table\"><tr><th>ID</th><th>Title</th><th>Status</th><th>Last modified</th></tr>\n";
$i = 0;
while ($number > $i) {
$course_id = mssql_result($result,$i,"id");
$reference = mssql_result($result,$i,"reference");
$updated = mssql_result($result,$i,"updated2");
print "<tr><td>";
if ($reference == "") {
print "<a href=$PHP_SELF?division=$division_id&course=$course_id>$course_id</a>";
} else {
print "$course_id";
}
print "</td><td>";
print mssql_result($result,$i,"title");
print "</td><td>";
if ($reference == "") {
if ( (mssql_result($result,$i,"goals")=="") and (mssql_result($result,$i,"outline")=="") ) {
print "<b>No syllabus, or incomplete</b></td>";
}
} else {
print "Based on $reference";
}
print "</td><td>$updated</td>\n";
print "</tr>\n";
$i++;
}
print "</table>";
exit;
}
$sqlquery = "SELECT * FROM courses WHERE id = '$course_id'";
$result = mssql_query($sqlquery);
$number = mssql_num_rows($result);
if ($number == 0) {
print "<html><body>";
print "No course with the ID \"$course_id\" exists in the course database.";
print "</body></html>";
exit;
}
$i = 0;
$description = fromhtml(mssql_result($result,$i,"description"));
print "<html><head><title>DACC Course Syllabus - $course_id</title>";
print "<script language=\"JavaScript\" type=\"text/javascript\" src=\"/rte/richtext2.js\"></script>";
?>
<script language="JavaScript" type="text/javascript">
<!--
initRTE("/rte/images/", "/rte/", "");
//-->
function submitForm() {
updateRTEs();
document.edit-course.submit();
return false;
}
</script>
<?php
print "</head><body>\n";
//Begin Form
print "<form name=\"edit-course\" id=\"edit-form\" method=\"post\" action=\"write.php?course=$course_id\" onSubmit=\"return submitForm()\">\n";
print "<fieldset>";
print "<label for=\"description\">Course Description</label>";
$description=addslashes(preg_replace('`[\r\n]`','',$description));
?>
<script language="JavaScript" type="text/javascript">
<!--
writeRichText('description', '<?php print $description; ?>', 200, 300, true, false);
//-->
</script>
<?php
print "</fieldset>";
It that BR is at very very beginning of string then use this
$x = preg_replace("/^<br(\/|)>/i","\n",$x);
instead of that commented line
preg_replace has a fourth parameter, $limit. Setting this to 1 would limit the preg_replace to the first occurence. Alternatively you could use the regular expression ^<br>. This would only replace <br> when it is at the beginning of the string.
Edit: Sorry, I misunderstood your problem. Use $variable=preg_replace("/^<br>/i", "", $variable); to strip the first <br>.

Is there a way to apply the button() jquery ui function to a button when it's loaded?

Basically. I have a javascript loop that posts to a php script. To append on the response to a DIV in a log. The response has a button inside it. The problem is, when a new response is made and appended, the jquery button function makes all the previous appended buttons larger. (Probably because it's calling the jquery button() function again on the same DIV elements.)
Is there a way to apply the button() jquery ui function to a button when it's loaded? (Instead of applying it to every element with the same name?)
This php is quite similar to the following (but this is shortened.) Just to give you an idea of what the php script does.
<?php
echo "<script type='text/javascript'>
function addButton(x) {
x = this;
$(x).button({
icons: {
primary: 'ui-icon-alert'
}
});
}
</script><div id='chat_wrap' class='message".$id."' hidden='true'>";
if ($query_run = mysql_query($finalchatq)) {
if (mysql_num_rows(mysql_query($finalchatq)) > 0) {
$counter = 0;
$amount = array();
while ($query_rows = mysql_fetch_assoc($query_run)) {
$time1 = $query_rows['time'];
$time2 = substr_replace($time1, " : ", 10, 1);
$time = str_ireplace('.', '/', $time2);
$text = str_ireplace('removem', '', $query_rows['text']);
$id = $query_rows['id'];
if($query_rows['type']=='notice') {
echo "<div selectable='false'><div id='date'><div id='notice'>NOTICE:</div>Sent At: ".$time."</div><div id='Nchat_message'><div id='chat_text'>".$text."</div><img id='charhead' src='camperhead.php?id=".$query_rows['who']."' id='charhead'></img></div>";
echo "<div id='controls'>";
if(userIsA('admin')||userIsA('mod')) {
echo "<input hidden='hidden' name='idtodel' value='".$id."'></input><input type='button' value='DELETE' id='delete_button'></input>";
} else {
}
echo "</div></div></div><br/><br/>";
}
if($query_rows['type']=='normal'){
echo "<div selectable='false'><div id='date'><div id='by'>".getUserFieldById($query_rows['who'], 'camper_name').":</div>Sent At: ".$time."</div><div id='chat_message'><div id='chat_text'>".$text."</div><img id='charhead' src='camperhead.php?id=".$query_rows['who']."' id='charhead'></img>";
echo "<div id='controls'>";
if(userIsA('admn')||userIsA('md')) {
echo "<button id='delete_button' class='dpp2' onclick='delCom(".$id.")'>Delete</button>";
} else {
echo "<button id='report_button' onload='addButton(this)' onclick='reportCom(".$id.")'>REPORT</button>";
}
echo "</div></div></div></div></div><br/><br/>";
}
}
echo "</div>";
}
}
}
?>
I hope I've made my question clear enough, if you have any concerns please post a comment and I'll reply as soon as I can.
Try using the .on() function in jQuery to define it when created http://api.jquery.com/on/

Categories