Request tracker REST API: Web Interface to Create New Tickets - ajax

I previously had a custom form that users could fill out to place work orders, and once they hit submit, it would create a new ticket with all the information and add it to one of the RT queues.
We previously used Mason to do this, but now we've moved to WordPress and would like to redo this in a cleaner way using PHP.
I read through the API documentation and reviewed this thread along with many others posted on Stack Overflow. I know how to connect to RT and create new tickets via command line and cURL, but I can't seem to figure out how to do so using the web interface on submit. I would really appreciate if someone could give me some pointers on where to start.
Thanks
Edit:
Thank you for the response. Below is the form I've made which interacts with a our SQL database to pull some information and I need it to create a new ticket with all the information on submit. Should I create a new php file similar to [this][2] and include it as a form action?
<form action="<?php echo $_SELF; ?>";
method="post"
id="woForm"
name="woForm"
enctype="multipart/form-data"
>
<input type="hidden" name="session_id" value="<?php echo session_id(); ?>">
<input type="hidden" name="Queue" value="<?php echo $queue; ?>">
<input type="hidden" name="id" value="new">
<input type="hidden" name="Status" value="new">
<input type="hidden" name="Owner" value="10">
<table width="450" align="center" border="0" cellpadding="0" cellspacing="5">
<tr><td align="left" colspan="2">
<h2><?php echo $name; ?></h2>
<p>Please note that all fields except for <b>Ext:</b>, <b>CC:</b> and <b>Attachments:</b> are <span class="required">required</span>.
You cannot submit a request for assistance using this form unless all the required
fields have been completed.</p>
<h2 style="color:red;">Please enter information for the INDIVIDUAL needing assistance</h2>
</td>
</tr>
<?php
// Get all of the customFields
$query1 = "select * from CustomFields where disabled='0' and sortOrder != 0 order by sortOrder ASC;";
$result1 = mysql_query($query1) or die ("dead3: ".mysql_error());
// Go through each custom field
while($row1 = mysql_fetch_array($result1)) {
// Get the information about that field
$count = 0;
$fieldId = $row1['id'];
$name = $row1['Name'];
// $postname is in a very specific format, and will become the name of the field in the form
// where the data for this custom field is entered. In order to submit a ticket into rt, the
// name of the field MUST be in this format.
$postName = "Object-RT::Ticket--CustomField-".$fieldId."-Values";
?>
<!-- Create a row in the table for this custom field -->
<tr>
<!-- Create a column with the name of the custom field -->
<td align="right" class="requestformlabel"><label class="required"><?php echo $name; ?>:</label></td>
<!-- Create a column for the input field -->
<td class = "requestformtd">
<?php
// If the custom field is department or building, we need a pull-down menu
if($name=="Department" || $name=="Building") { ?>
<!-- start of the pull-down menu -->
<select name="<?php echo $postName; ?>">
<?php
// Get all of the possible values for the customField from the database
// Added option to exclude sort order 9999. See ticket #40665 for more info.
$query3 = "SELECT * FROM CustomFieldValues WHERE CustomField='$fieldId' AND SortOrder != '9999' ORDER BY SortOrder ASC";
$result3 = mysql_query($query3) or die ("dead4: ".mysql_error());
// Go through each possible value for the custom field
while($row3 = mysql_fetch_array($result3)) {
// Get the information on the custom field value from the database
$tmp = $row3['Name'];
$description = $row3['Description'];
// If the custom field value was already selected
if($tmp == $_POST["$postName"]) {
// Insert the option into the pull-down menu and mark it as selected in the form
echo "<option value='$tmp' selected='selected'>$description</option>";
// otherwise
} else {
// Only insert it as an option in the pull-down menu
echo "<option value='$tmp'>$description</option>";
}
}
?>
</td></tr>
<?php
// If the name of the custom field is operating system, we want radio buttons
} else if ($name == "Operating System") {
// Get all the possible values for this field form the database
$query4 = "select * from CustomFieldValues where CustomField='$fieldId' order by sortorder asc";
$result4 = mysql_query($query4) or die ("dead5: ".mysql_error());
// For each customfield value
while($row4 = mysql_fetch_array($result4)) {
// Get the description of the customfieldvalue from the database
$osName = $row4['Description'];
// If the customfieldvalue has already been selected
if ($osName == $_POST["$postName"]) {
// Put the radio button into the form and mark it as checked
echo "<input type='radio' name='$postName' value='$osName' checked='checked'>$osName";
// Otherwise
} else {
// Put the radio button into the form
echo "<input type='radio' name='$postName' value='$osName'>$osName";
}
} ?>
</td></tr>
<?php
// If the name of the custom field is ip adress, we want a disbaled text box. This is because while we want the user to see their ip adress, we do not want them to be able to change it.
} else if ($name == "IP_Address"){
?>
<input name="<?php echo $postName; ?>" size="40" value='<?php
echo $_SERVER['REMOTE_ADDR']; ?>' readonly></td></tr>
<?php
// If it's the hostname variable
} else if ($name == "Host_Name"){
?>
<input name="<?php echo $postName; ?>" size="40" value='<?php echo gethostbyaddr($_SERVER['REMOTE_ADDR']); ?>' readonly></td></tr>
<?php
// Otherwise, create a text box for the custom field.
} else {
?>
<input name="<?php echo $postName; ?>" size="40" value='<?php echo $_POST["$postName"]; ?>'></td></tr>
<?php } // end else statement
} // end while loop
?>
<tr>
<td class="requestformlabel" align="right"><label class="required">Your E-mail Address:</label></td>
<td align="left" class="requestformtd"><input name="Requestors" size=40 value="<?php echo $_POST['Requestors']; ?>"></td>
</tr>
<tr>
<td class="requestformlabel" align="right"><label class="required">Confirm Your E-mail Address:</label></td>
<td align="left" class="requestformtd"><input name="Requestors_2" size=40 value="<?php echo $_POST['Requestors_2']; ?>"></td>
</tr>
<tr>
<td class="requestformlabel" align="right"><label class="fields">Cc:</label></td>
<td align="left" class="requestformtd"><input name="Cc" size=40 value="<?php echo $_POST['Cc']; ?>"></td>
</tr>
<tr>
<td align="right"><p> <br/> </p></td>
<td align="right"><span class="ccnote">(Separate multiple email addresses with commas.)<br/> </span></td>
</tr>
<tr>
<td class="requestformlabel" align="right"><label class="required">Short Problem Summary:</label></td>
<td align="left" class="requestformtd"><input name="Subject" size=40 maxsize=100 value="<?php echo $_POST['Subject']; ?>"></td></tr>
<tr>
<td class="requestformlabel" align="right"><label class="required">Decribe the issue below:</label></td>
<td align="left" class="requestformtd"><textarea
class="messagebox" cols=35 rows=15 wrap="hard" name="Content"><?php echo $_POST['Content']; ?></textarea>
</td>
</tr>
<?php
//if session has attachments
if($_SESSION['attach'] != '') {
?>
<!-- row for existing attahcments -->
<tr>
<!-- column that states these are the current attachments, and tells the user what to do if
they wish to remove an attachment. -->
<td class="requestformlabel" align="right">Current Attachments:<br/>
<span class="ccnote">(Check box to delete)</span>
</td>
<!-- coulmn that lists the attachments -->
<td class="requestformtd" align="right">
<?php
// Go through each file in $_SESSION['attach']
while (list($key, $val) = each($_SESSION['attach'])) {
// Get the name of the file
$attName = $val['name'];
// Create a checkbox to mark the file as needing to be removed from the list
echo "<input type='checkbox' name='DeleteAttach-$attName' value='1'>$attName<br/>";
} // end while loop
?>
</td>
</tr>
<?php // end if for attachments
}
?>
<tr>
<td class="requestformlabel" align="right"><label class="fields">Attachments:</label></br>
<span class="ccnote">Max. attachment size: 50MB.</span></td>
<td align="right" colspan="2" class="requestformtd">
<input type="file" name="Attach">
<br/>
<input type="submit" name="AddMoreAttach" value="Add More Files">
</td>
</tr>
<tr>
<td align="left"><input type="submit" name="submit" value="Submit Request"></td>
<td> </td>
</tr>
</table>
</form>
Edit 2:
Thanks. Using the documentation and code from this repo I created a new file called new_ticket.php with the following content:
<?php
if($_POST['action'] == 'call_this') {
require_once 'RequestTracker.php';
$url = "www.test.com/rt/REST/1.0/";
$user = "user";
$pass = "password";
$rt = new RequestTracker($url, $user, $pass);
$content = array(
'Queue'=>'9',
'Requestor'=>'test#example.com',
'Subject'=>'Lorem Ipsum',
'Text'=>'dolor sit amet'
);
$response = $rt->createTicket($content);
print_r($response);
}
?>
I also made of copy of RequestTracker.php from the same Github repo.
In the file where the form is located, I added the following script and added create_ticket() as an action to the onclick property of submit button. But this doesn't seem to be working. I tried logging something to the console to see how far the code gets, the create_ticket() function is being called properly but anything that comes after $.ajax({ ... above will not appear to the console. I also tried putting some console logs in my new_ticket.php file but that doesn't log anything either, so what am I doing wrong?
<script>
function create_ticket() {
$.ajax({
url:"new_ticket.php", //the page containing php script
type: "POST", //request type
data:{action:'call_this'},
success:function(result){
alert(result);
}
});
}
</script>
PS: I'm using ajax because I need to run the PHP code onclick and this can't be done directly as it would in Javascript.

Probably the easiest approach is to look at the PHP examples in the REST documentation on the Request Tracker wiki. You don't mention the version of RT you are using, but the REST interface has been stable so this should work with most versions.

Related

Adding a Logon message to pages

I'm looking to create a log in feature every time users go to various members only pages, which returns them to the original page after logging in. I've seen various answers to this question but none of them seem to include a check feature followed by a return to the original page. At the moment the code I have created doesn't seem to recognize that I have logged in and keeps returning me to the log in form. Any answers will be greatly appreciated. I realize I am using deprecated code but that is the only version my host provider's servers recognize.
Here's the code I am putting at the top of each members page
<?php
session_start();
if($_SESSION['login'] != "yes" )
{
header("Location: main_login.php");
exit();
}
?>
This then opens the main_login.php page
<table width="300" border="0" align="center" cellpadding="0" cellspacing="1" bgcolor="#CCCCCC">
<tr>
<form name="form1" method="post" action="checklogin.php">
<td>
<table width="100%" border="0" cellpadding="3" cellspacing="1" bgcolor="#FFFFFF">
<tr>
<td colspan="3"><strong>Member Login </strong></td>
</tr>
<tr>
<td width="78">Username</td>
<td width="6">:</td>
<td width="294"><input name="myusername" type="text" id="myusername"></td>
</tr>
<tr>
<td>Password</td>
<td>:</td>
<td><input name="mypassword" type="password" id="mypassword"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td><input type="submit" name="Submit" value="Login"></td>
</tr>
</table>
</td>
</form>
</tr>
</table>
On clicking the login button the following code in checklogin.php checks the entries
<?php
$host='.....'; // Host name
$username='.....'; // Mysql username
$password='........'; // Mysql password
$db_name='....'; // Database name
$tbl_name='......'; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_start();
$_SESSION['myusername'];
$_SESSION['mypassword'];
header("location:entry_form_european_languages.php");
}
else {
echo "Wrong Username or Password";
}
?>
The last header location refers to the page I would like to return to, which seems to the repeat the process of opening up the login and check in files- as if to indicate that the return page doesn't recognize that the log in was successful.
I would need to add something that was relative to each page, but since I don't know where I am going wrong with the fixed page return, I can't move on to that stage of coding.
I did have an alternative header address which took it to the following page login_success.php which gave the impression that username entries had been accepted, but this doesn't allow me to return to the original page
<?php
session_start();
if(isset($_SESSION[$myusername])){
header("Location:entry_form_european_languages.php");
}
?>
<?php
include '........';//Formatting for the page
?>
<html>
<body>
Login Successful
</body>
</html>
Thanks in advance.
There are a few extra things I needed to add to make the session details work, as follows. This code needs to go ahead of any other code on the page including any html code that relates to character formatting. Although I have coded it out the error reporting line is handy for indicating which line is not being read by the php server, should you have continued problems.
<?php
//error_reporting(E_ALL); ini_set('display_errors', 'On');
session_start();
ob_start();
if(!isset($_SESSION['myusername'])){
header('Location:main_login.php');
}
else if (isset($_SESSION['myusername'])){
}
$myusername=$_SESSION['myusername'];
$Page_Title ='Members Profile';
?>

Password failing using Bcrypt

So far bcrypt has had no problems until now. For some reason the following password won't work. UIO78349%^&(]\\';= This is the first time I've had a password not work and I hope somebody has an explanation. I hunted the net and read about the character limit but this is well below that. Not sure if it makes any difference but the user input for password is going through mysqli_real_escape_string.
First batch of code where the login form is located:
<?php
session_start();
?>
<html>
<body>
<form method="post" action="sidebar-signin-block.php">
<table width="90%" border="0" align="center" bgcolor="white">
<tr>
<td bgcolor="ffffff" colspan="2" align="center"><h2>User Login</h2></td>
</tr>
<tr>
<td align="right">Email:</td>
<td><input type="text" name="email"></td>
</tr>
<tr>
<td align="right">Password:</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="login" value="Login"></td>
</tr>
<tr>
<td colspan="2" align="center"><h3 style="margin-top:7px;">Forgot Password?</h3></td>
</tr>
<tr>
<td bgcolor="#ffffff" colspan="2" align="center"><div style="padding-top:5px;"><span style="font-size:20px;">Don't have an account?<br />Sign Up is <em>quick</em> and <em>easy</em>!</span></div></td>
</table>
</form>
<?php
// Connecting to the database and making the Bcrypt functions available
include("admin/includes/connect.php");
include ("lib/password.php");
// Gathering and sanitizing user login input
if(isset($_POST['login'])){
$email = trim(((isset($conn) && is_object($conn)) ? mysqli_real_escape_string($conn, $_POST['email']) :((trigger_error ("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")));
$pass = trim(((isset($conn) && is_object($conn)) ? mysqli_real_escape_string($conn, $_POST['password']) : ((trigger_error ("[MySQLConverterToo] Fix the mysql_escape_string() call! This code does not work.", E_USER_ERROR)) ? "" : "")));
// Checking the database records for the user login input
$hash_query = "select nonadmin_user_pass from nonadmin_user_login where email='$email'";{
$run_query = mysqli_query($conn, $hash_query);}
while ($row = mysqli_fetch_assoc($run_query)) {
$fetch_pass = $row['nonadmin_user_pass'];
}
// If the user email and password matches we start a session
if ((password_verify($pass, $fetch_pass)) == 1){
// Verifying user login success with splash page then sending user back to the home page
$_SESSION['email']=$email;
echo "<script>window.open('login-success.php','_self')</script>";}
// When the user login fails an alert is given to inform them
else {
echo "<script>alert('Email or password is incorrect please try again')</script>";
echo "<script>window.open('index.php','_self')</script>";}
}
?>
</body>
</html>
Here the js.
<script>$(document).ready(function(){
$("#login").click(function(){
var email = $("#email").val();
var password = $("#password").val();
// Checking for blank fields.
if( email =='' || password ==''){
$('input[type="text"],input[type="password"]');
$('input[type="text"],input[type="password"]');
alert("Please fill all fields.");
}else {
$.post("log-me-in.php",{ email1: email, password1:password},
function(data) {
if(data=='Invalid Email.......') {
$('input[type="text"]');
$('input[type="password"]');
alert(data);
}else if(data=='Email or Password is wrong please try again.'){
$('input[type="text"],input[type="password"]');
alert(data);
} else if(data=='Successfully Logged in.'){
window.location.reload();
$("form")[0].reset();
$('input[type="text"],input[type="password"]');
alert(data);
} else{
alert(data);
}
});
}
});
});</script>
Here's the php being called:
<?php
session_start();
// Connecting to the database and making the Bcrypt functions available
include("admin/includes/connect.php");
include ("lib/password.php");
$email=$_POST['email1']; // Fetching Values from URL.
$password= ($_POST['password1']);
// check if e-mail address syntax is valid or not
//$email = filter_var($email, FILTER_SANITIZE_EMAIL); // sanitizing email(Remove unexpected symbol like <,>,?,#,!, etc.)
//if (!filter_var($email, FILTER_VALIDATE_EMAIL)){
//echo "Invalid Email.......";
//}else{
// Matching user input email and password with stored email and password in database.
$result = mysqli_query($conn, "SELECT * FROM nonadmin_user_login WHERE email='$email'");
$data = mysqli_fetch_array($result);
$bcrypt_pass = $data['nonadmin_user_pass'];
$email_match = $data['email'];
if (password_verify ($password, $bcrypt_pass) == 1 AND $email == $email_match) {
$_SESSION['email']=$email;
echo "Successfully Logged in.";
}
else{
echo "Email or Password is wrong please try again";
}
//}
?>
Here is the user registration code where the password initially gets entered before mail verification:
<html>
<head>
<title>Register at Recycling Kansas City</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" type="text/css" href="/styles/register-user.css" media="all">
<!-- ie compatibility -->
<!--[if IE]>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<![endif]-->
<!--[if lt IE 9]>
<script src="Site/javascript/bootstrap/html5shiv.js"></script>
<![endif]-->
<meta content="recycling kansas city, recycling centers, recycling locations" name="keywords">
<meta content="Recycling Kansas City is an efficient resource to help you quickly find a recycle center that is nearby. Use our map to find locations and accepted items." name="description">
</head>
<h1 class="center">Why register at Recycling Kansas City?</h1>
<p>By registering here you will gain access to additional features. Once registered you can create your own custom profile, submit and comment on blog articles, advertise your products or services and have the choice to opt in for email announcements.</p>
<p>All of your information will be securely stored in our database and you can delete your account at any time. Also, rest assured that we will never share any of your submitted details with anyone ever.</p>
<form method="post" action="register-user.php">
<table width="520" border="10" align="center" bgcolor="white">
<tr>
<td bgcolor="ffffff" colspan="2" align="center"><h1>Registration</h1></td>
</tr>
<tr>
<td align="right">Email</td>
<td><input type="text" name="email" size="53"></td>
</tr>
<tr>
<td align="right">Password:</td>
<td><input type="password" name="pwd" size="53"></td>
</tr>
<tr>
<td align="right">User Name:</td>
<td><input type="text" name="name" size="53"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" name="register" value="Register"></td>
</tr>
</table>
</form>
</html>
<?php
include ("../admin/includes/connect.php");
include ("../lib/password.php");
$con = new mysqli("localhost", "$username", "$password", "$database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(isset($_POST['register'])){
$email = trim(mysql_escape_string($_POST['email']));
$nonadmin_user_pass = trim(mysql_escape_string($_POST['pwd']));
$password = password_hash($nonadmin_user_pass, PASSWORD_BCRYPT);
$nonadmin_user_name = trim(mysql_escape_string($_POST['name']));
$query_verify_email = "SELECT * FROM nonadmin_user_login WHERE email ='$email' and verified = 1";
$verified_email = mysqli_query($con,$query_verify_email);
if (!$verified_email) {
echo ' System Error';
}
if (mysqli_num_rows($verified_email) == 0) {
// Generate a unique code:
$hash = md5(uniqid(rand(), true));
$query_create_user = "INSERT INTO `nonadmin_user_login` (`email`, `nonadmin_user_pass`, `nonadmin_user_name`, `hash`) VALUES ('$email', '$password', '$nonadmin_user_name', '$hash')";
$created_user = mysqli_query($con,$query_create_user);
if (!$created_user) {
echo 'Query Failed ';
}
if (mysqli_affected_rows($con) == 1) { //If the Insert Query was successfull.
$subject = 'Activate Your Email';
$headers = "From: admin#recyclingkansascity.com \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$url= 'http://recyclingkansascity.com/includes/register-verify.php?email=' . urlencode($email) . "&key=$hash";
$message ='<p>To activate your account please click on Activate buttton</p>';
$message.='<table cellspacing="0" cellpadding="0"> <tr>';
$message .= '<td align="center" width="300" height="40" bgcolor="#000091" style="-webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px;
color: #ffffff; display: block;">';
$message .= '<a href="'.$url.'" style="color: #ffffff; font-size:16px; font-weight: bold; font-family: Helvetica, Arial, sans-serif; text-decoration: none;
line-height:40px; width:100%; display:inline-block">Click to Activate</a>';
$message .= '</td> </tr> </table>';
mail($email, $subject, $message, $headers);
echo '<p class="center">A confirmation email
has been sent to <b>'. $email.' </b></p><p class="center">Please <strong>click</strong> on the <strong><em>Activate</em> Button</strong> to Activate your account.</p> ';
} else { // If it did not run OK.
echo '<div>You could not be registered due to a system
error. We apologize for any
inconvenience.</div>';
}
}
else{
echo '<div>Email already registered</div>';}
}
?>
So far never a hiccup on any password until the password at the top of the post? Weird if you ask me.
Remove all calls to mysqli_real_escape_string() for password input, the functions password_hash() and password_verify() accept even binary input and are not prone to SQL-injection. I assume this already solves your problem. Escaping should be done as late as possible and only for the given target system, so the function mysqli_real_escape_string() should only be called to build an SQL query.
Then the function password_verify() already returns a boolean, no need to compare it with == 1.
if (password_verify($pass, $fetch_pass))
{
...
}
If this doesn't solve your problem, i would make sure that every page uses UTF-8 as file format and defined it in the header.

Joomla - pagination bar not showing up

I'm trying to get pagination working in my joompla component admin page (table of records from database).
I'm using the standard method found on the net, so in my view class I have:
function display($tmpl=NULL)
{
$this->tabela = $this->get('Items');
$this->pagination = $this->get('Pagination');
$this->state = $this->get('State');
...
and then in my default template for this view:
<tfoot>
<tr>
<td colspan="7" >
<?php echo $this->pagination->getListFooter(); ?>
</td>
</tr>
but the pagination is not showing up. In the place where it should occur I can only see this (in website's HTML):
<div class="pagination pagination-toolbar">
<input type="hidden" name="limitstart" value="0">
</div>
How can I get this pagination work?

Adding a 'add another' option in Wordpress custom meta box using jquery $.post

I'm creating a wordpress plugin, with a custom post type and in that post type a custom meta box.
Inside the meta box, I have a form that let's the user input: Date, Media, Title.
The form looks like this:
$mc_date = get_post_meta($_GET['post'],'mc_date',true);
$mc_media = get_post_meta($_GET['post'],'mc_media',true);
$mc_title = get_post_meta($_GET['post'],'mc_title',true);
echo '<form id="add_media_form">';
echo '<table>';
echo '<tr>';
echo '<td>Date</td><td>Media</td><td>Title</td>';
echo '</tr>';
echo '<tr>';
echo '<td><input type="text" name="mc_date" value="'.$mc_date.'" class="datepicker"/></td>';
echo '<td><input type="text" name="mc_media" value="'.$mc_media.'" /></td>';
echo '<td><input type="text" name="mc_title" value="'.$mc_title.'" /></td>';
echo '<td><img src="'.WP_PLUGIN_URL.'/mc/plus.png" /></td>';
echo '</tr>';
echo '</table>';
echo '</form>';
echo '<div class="addmedianotify"></div>';
jquery:
jQuery('.add_new_media').click(function(e){
var plug = jQuery(this).attr('rel');
e.preventDefault();
jQuery.post(plug + '/ajax_add_media.php',jQuery('#add_media_form').serialize(),function(data){
jQuery('.addmedianotify').html('<span>'+data+'</span>');
});
});
What I want to do, is that when the user click the 'add_new_media' link/image a new set of textboxes for date, media and title will appear.
My main concern is that, what's the trick to name those inputs which is dynamic. and to save and retrieves the custom data in it.
Because the page will still update when the user clicks 'Update' you would need to be able to save your fields on save_post and in your ajax. Using ajax for this might not be the best method as you're making more work for yourself by needing to save that data twice. I would ditch the ajax and simply use an html array so you can add on fields and make one submission when the user clicks 'Update'. To add new rows as the user needs, I would simply clone your tr and append it to the table in your click event. Something like...
The PHP & HTML
<img src="'.WP_PLUGIN_URL.'/mc/plus.png" />
<table>
<tr>
<td>Date</td>
<td>Media</td>
<td>Title</td>
<td></td>
</tr>
<?php
//$mcs will be a multi-dimensional array with this method
$mcs = get_post_meta($post->ID,'mcs',true);
//Loop through each set of saved mc data (date, media, and title per item) and output inputs so the saved values can be edited and resaved.
foreach ($mcs as $mc) : ?>
<tr>
<td><input type="text" name="mc[][date]" value="<?php echo $mc['date'] ?>" class="datepicker"/></td>
<td><input type="text" name="mc[][media]" value="<?php echo $mc['media'] ?>" /></td>
<td><input type="text" name="mc[][title]" value="<?php echo $mc['title'] ?>" /></td>
<td>Remove</td>
</tr>
<?php endforeach ?>
</table>
The Javascript
<script>
(function($){
//Grab the first
$('.add_new_media').click(function(e) {
//Use the first tr as a cookiecutter and add another cookie to the bowl :)
$('table tr:first-child')
.clone()
.appendTo($('table'))
.find('input')
.val('')
}
$('.remove').click(function(){
$(this).parent().parent().remove()
})
})(jQuery)
</script>
The PHP upon form submission
<?php
if ($_POST) :
//$_POST['mc'] is a multi-dimensional array of all the date/media/title input rows
print_r($_POST['mc']);
/*
..would look something like
Array (
[0] => Array (
'date' => 'some value',
'media' => 'some value',
'title' => 'some value'
),
[1] => Array ( ... ),
[2] => Array ( ... ) ... and so on
)
*/
//RUN INPUT VALIDATION!!
//Update the list
update_post_meta($post->ID, 'mcs', $_POST['mc']);
endif;
?>

Waiting message on slow redirection

I have the following code:
<?PHP
if (isset($_POST['submit'])) {
header("Location: http://mysite.com");
}
?>
<form name="form1" action="" method="post">
Name: <input name="name" type="text">
<input type="submit" value="submit" name="submit">
</form>
The problem is that when I submit the form the redirection to mysite.com takes too long time, 5-10s.
I would like to display a messege "Loading... Please wait" och show an animated image so that I know that something is happening.
How do I do in javascript och ajax?
I don't know if it's possible (but I don't think so) but you could add exit(); after setting the header so the rest of the script isn't executed and sent to the browser. That could reduce the time a bit.
What you could try is to do the redirection with javascript instead of a http header.
<?php if (isset($_POST['submit'])): ?>
<script>
alert('Loading... Please wait');
document.location.href = 'http://mysite.com';
</script>
<?php endif; ?>
5-10 secs to submit the page. First of all try to figure out why it is taking that much time.
ANyways, If you just want to see some message when you press submit button, then simply you can add any div ( with initially hidden ). And on click of submit button you can show this div.
See the sample code:
<?PHP
if (isset($_POST['submit'])) {
header("Location: http://mysite.com");
}
?>
<div id='loadingDIV' style='display: none;'></div>
<form name="form1" action="" method="post">
Name: <input name="name" type="text">
<input type="submit" value="submit" name="submit" onclick='showLoadingAndSubmit();'>
</form>
function showLoadingAndSubmit(){
document.getElementById ('loadingDIV').innerHTML = 'Form submitting. Please wait...';
document.getElementById ('loadingDIV').style.display = 'block';
return true;
}
you should have something like this
the loading has image GIF moving until the ajax request end and then the loading become hidden
where result has the database result grid search on screen
<tr valign="top">
<td id="results" colspan="8" align="center" width="100%" height="250px">
</td>
</tr>
<tr valign="top" id="loading" style="display:none;">
<td colspan="8" width="100%" align="center">
<img name="loading_image" src="images/loading.gif" border="0" width="214" height="200">
</td>
</tr>
function search(tableEvent){
try
{
document.getElementById('loading').style.display="";
var params = 'formAction=' + document.mainForm.formAction.value;
params += '&tableEvent=' + tableEvent;
params += '&txtActionDivisionDesc=' + document.mainForm.txtActionDivisionDesc.value;
createXmlHttpObject();
sendRequestPost(http_request,'Controller',false,params);
ValidationResult();
}
catch(e)
{
alert(e.message);
}
}
function ValidationResult()
{
try
{
if (http_request.readyState == 4)
{
var errors = http_request.responseText;
errors = errors.replace(/[\n]/g, '');
if (window.ActiveXObject)
{// code for IE
xmlRecords=new ActiveXObject("Microsoft.XMLDOM");
xmlRecords.loadXML(errors);
}
else
{
xmlRecords=document.implementation.createDocument("","",null);
parser=new DOMParser();
xmlRecords=parser.parseFromString(errors,"text/xml");
}
document.getElementById('loading').style.display="none";
document.getElementById('results').innerHTML = errors;
http_request = false;
}
}//end try
catch(e)
{
document.getElementById('results').innerHTML = errors;
return;
}
}

Resources