How to generate an ID for Contact Form? - javascript

I'm using PHP for a simple Contact Form. I'm trying to generate an unique ID for each form submitted. For example, the first email is #001, the second #002, 3th #003 etc.
I'll use the ID in the autoreply (or autoresponse?) e-mail: "You are the #016 person to make contact.", for example.
Can be with PHP or JavaScript (can it be with JS? I don't know! But I prefer PHP!). But I have no idea about how I can do this.
I'm not using a database.

Since you're (probably) going to store received information in a kind of database, you generate id on insertion into database. Autoincrement ID field should do the trick.
edit: It also sounds reasonable to reuse google forms

You can use php's uniqid() function to generate unique id each time.
Update 1:
It's a very useful function. The probability of generating same id is really minimum. For more information please visit the link
Update 2:
You can use simple text file/csv to store one line at a time to keep track of it. When the user submit the form you generate unique id each time and reply to client and at the same time you store it to a normal text file if you like. Hope this will help.

There are several ways to do this. The most simple of those is to create a file which will store the number of form filled and you can increase its value for each form filled.
Here is the example copied from: Read and write to a file while keeping lock
//Open the File Stream
$handle = fopen("file.txt","r+");
//Lock File, error if unable to lock
if(flock($handle, LOCK_EX)) {
$count = fread($handle, filesize("file.txt")); //Get Current Hit Count
$count = $count + 1; //Increment Hit Count by 1
ftruncate($handle, 0); //Truncate the file to 0
fwrite($handle, $count); //Write the new Hit Count
flock($handle, LOCK_UN); //Unlock File
} else {
echo "Could not Lock File!";
}
//Close Stream
fclose($handle);

Related

How to implement custom logic in WordPress?

I'm working on my website and I want to add two things.
A link when a user clicks on it then his/her user id and the current post id get and inserted in the database and the counter increases.
Let's suppose user logs in and opens the post and the link is like this: I am Interested (0) here 0 is the count value of the total number of unique logged in people who have clicked on this link. The second link will be like: I want to work (0) same logic applies here.**
And finally need to show the no of interested and working people for a specific post(custom post type: job).
There is a table in which each row has the title of the post (job) I can get the value of the post by WordPress native functions and then compare that with the post id in the database and then retrieving it status (noofinterested and noofworking) and then inject via AJAX using jQuery.
I have created the table for this purpose but I'm having difficulty:
Getting POST ID and USER ID via jquery as for some reasons I cant modify the current custom post template as I'm using wp job manager for custom job posts.
All I need is to find a way to get unique people to count on the specific posts
So far I thought of a way to append the two links via jQuery and the add click function to the link via jQuery and in that add ajax to get data and input to the PHP file which I have coded and in that PHP file it will insert into the table via the post values and then return response. And in the second page where I want to insert the status in the table row, I will use jQuery for this.
This is currently I'm having on hand.
PHP
<?php
global wpdb;
if(isset($_POST['if_intested'])&&isset($_POST['if_working'])&&isset($_POST['user_id'])&&isset($_POST['post_id'])){
if($wpdb->insert('wp_custom_jobmanager', array ( "post_id" => $_POST['post_id'], "user_id" => $_POST['user_id'], "if_interested" => $_POST['if_interested'] , "if_working" => $_POST['if_working']))){
return "Thanks your feedback has been saved";
}else {
return "Sorry something went wrong Please Try Logging in again and try again.";
}
}
?>
jQuery
jQuery("#link").click(function(){
if(jQuery("body").hasClass("single")){
jQuery('<p id="stauts-interested">interested 24</p><br><p id="status-work">Working 43</p>').appendTo(".job-manager-single-alert-link");
}
});
Now the number of interested and working should be fetch from database and also get incremented for unique logged in users on click.
Why don't you just add a custom field to your Custom Post Type instead of using a custom table? This is almost a prime example of when it's appropriate to use it. Just add the current user id to an array using get_post_meta and update_post_meta on the WP Ajax hooks.
add_action( 'wp_ajax_increment_cpt_interests' );
add_action( 'wp_ajax_nopriv_increment_cpt_interests' );
function increment_cpt_interests(){
extract( $_POST );
// Get current interested people
$interested_people = get_post_meta( $post_id, 'interested', true );
$interested_user = get_current_user_id();
// If current user isn't already "interested"
if( !in_array( $interested_user, $interested_people ){
// Add them to the array of interested people
update_post_meta( $post_id, 'interested_people', $interested_people[$interested_user] );
}
}
Just pass the post ID, Ajax URL (and current user id if you want) using wp_localize_script (Read more here) to the button you want clicked on.

Check if a $_SESSION variable is set from Javascript

I'm building a message system to learn how it works, and I've already got
pretty much everything. I can log in and make a post on a board, but now I would like to be able to edit it. The back-end is ready, it receives a POST request
Basically what I need to do is check if the currently logged in user is the author of a certain post from Javascript to show or hide the edit button. I know how to tell if the user is logged in from PHP so that it blocks requests if you aren't the author, but I can't hide or show the buttons as the posts are dinamically generated from a <template> using JS.
Login snippet:
$_SESSION["userid"] = $userid;
Edit check PHP snippet (kinda pseudo-code):
if ($_POST["action"] == "modifypost" && isset($_POST["postid"]) && isset($_POST["content"]))
{
$post = get_post($_POST["postid"]);
if ($post.userid != $_SESSION["userid"])
{
die("you are not allowed");
}
//MySQL queries
}
Post dynamic generation (abbreviated):
function add_post(post) {
var t = document.querySelector('#historypost');
t.content.querySelector(".content").innerHTML = post.content;
var clone = document.importNode(t.content, true);
document.body.appendChild(clone);
}
I had originally thought of setting a variable with the user ID from HTML with <script> and <?php ?>, but then the user would be able to manually set that variable from the console and show the buttons.
I had originally thought of setting a variable with the user ID from HTML with <script> and <?php ?>
Yes, this is one correct approach. Basically, use PHP to tell JavaScript which posts actually belong to the current user.
but then the user would be able to manually set that variable from the console and show the buttons
True. There is no way to secure information from user-meddling once you've sent it to the browser. This is because the user is in control of what gets executed in the browser. Instead of thinking of the button visibility as a security feature, think of it as a convenience -- something to make the user experience more pleasing.
Application security is really enforced on the server. Just make sure that one user is not allowed to edit another user's posts, and do not trust what comes from the browser. Verify inputs.
Ideally, I would prefer to put the post rendering logic inside the server-side.
But as your solution is focused in javascript, an option makes PHP render a javascript variable that tells if the user is the post author.
Example:
Inside your PHP file, in the HTML render part you can do this:
<script>var isAuthor = '<?php echo ($post.userid == $_SESSION["userid"])'; ?></script>
Doing this you will have javascript script variable called isAuthor, that will have value "1" is the user is the author.
-
But as I said, this doesn't look like a good approach to solve the problem. It's something that PHP can handle better, without expose your logic to the client.

Multiple choice list to PHP request

I have this datatable which gets its data from a server. The problem now is that the database contains a bit more data than i first imagined it would. So for keeping the browser from loading all entries i've created a multiple select list that I will use for only pulling out the essential information.
The input from this list is then matched with what's in the database. The result of that is then stored in $results as can be seen below.
The problem here is that i have no idea how to get the input data, especially if its multiple choice, to go in to the last mysql query which then go into $results.
Later on I use $results for pushing out data to a table. Though as i said it gets a bit crowded in the table when i load all my data into $results.
Everything else is working properly and I get my scopeIDs in my multiple select list.
So, how do I get my selected option/s to go in to
<?php
$results = mysql_query("SELECT * FROM tableID LIKE (/*some cool way of putting the input here*/)";
?>
Complete Code for the task:
///Connection parameters above///
$multiplechoice = mysql_query("SELECT scopeId FROM tableID");
$storeArray = array();
print"<select multiple name=\"scopeValues\" id=\"scopeIdchoice\">";
while ($rowchoice = mysql_fetch_array($multiplechoice, MYSQL_ASSOC)) {
$storeArray = $rowchoice['scopeId'];
print"<option id='".strtolower($storeArray)."'>";
print $storeArray;
print"</option>";
}
<?php
$results = mysql_query("SELECT * FROM tableID LIKE (/*some cool way of putting the input here*/)";
?>
Change the name of the select to scopeValues[].
From the select you will get an array of values in the $_POST array. You might pass that as a list of values to the SQL query like below. You need to adopt the xx_thefield_xxto the proper column name and of course need to do checks against SQL-injection, which are missing for better reading over here.
<?php
$scopeVals = $_POST['scopeValues[]'];
// … remember to sanitize $scopeVals before the next step
$results = mysql_query("SELECT * FROM tableID where xx_thefield_xx in ('" .
implode("','", $scopeVals) . "');";
?>
Because there is more than one value associated with a input now you need to tell the server to store all values in a array (notice the brackets):
name=\"scopeValues[]\"
Then you implode the array and run the SQL. I'll assume that you're POSTing the form data:
$scopeValues = implode(',', $_POST['scopeValues']);
// … remember to sanitize $scopeValues before the query
$results = mysql_query("SELECT * FROM tableID WHERE scopeId IN ($scopeValues) )";
Make sure to sanitize all the values in $scopeValues before interpolating them into the query to protect against SQL Injection. A more secure way would be not to use ext/mysql (it's deprecated anyway) and use PDO or ext/mysqli and use prepared statements.
(Are the IDs strings?)
I don't know if you knew this, but PHP is executed on the server. Requesting your pages goes as follows:
A browser sends a request to your server;
The server executes the PHP;
The server sends the output to the browser;
The browser renders the HTML.
This poses a problem: if you change your selection (which happens in the browser), the PHP has already been executed. It can't magically change its output that got sent to the browser. So to refresh the result, you should make a form and POST the input to the same page, which would check if data had been posted, if it had, output only the selected data, if it hadn't, show everything. If you want to make it a bit more complicated (but more usable too), you could use AJAX to retrieve the results of the select query.
The other answers covered the form already, the AJAX way would be like this:
Have a separate page which SELECTs the data using the POSTed input to filter.
Make an AJAX request (on the page that displays the data) every time the <select> changes.
(Maybe this answer is totally useless to you because you already knew PHP is server-side.)

Not able to copy data from one table to another

I have two tables: trade and user_pokemon_db
I want to copy a specific rows from user_pokemon_db, when an event occurs.
Html code:
echo "<a href='tradecenter.php' onClick='document.write(".trade($db_id).")' >Put in Trade</a>";
When the user clicks on the link, the php function is called which consists on sql query to copy the row.
$sql = " INSERT INTO trade (trade_id, user_id, pkmn_id, level, exp, health, attack1, attack2, attack3)
SELECT (id, user_id, pkmn_id, level, exp, health, attack1, attack2, attack3)
FROM user_pokemon_db WHERE user_id = '".$id."' AND id = '".$db_id."' ";
Problem maybe due to improper writting of the query.. or maybe due to improper formatting of the href!??
What should I do?
I don't know the content of your php function trade() but it seems that you are confusing javascript and PHP.
Keep in mind that in most of case, once the web page is sent to the user browser, the PHP execution is finished. If you want to do a SQL request after a link click, you need to load a new page or to use something like Ajax to run some PHP code again.
The simplest way to do what you want is to pass the pokemon id as a GET variable (= in the URL)
and check this variable on another page and generate the good SQL query :
echo '<a href="trade.php?pokemon_id='.$id.'" >Trade </a>' ;
And the trade.php would do something like that :
$id = $_GET['pokemon_id'] ; // Be Aware of SQL Injections !!
trade($id);
Have a look at this page for more information about forms : http://www.w3schools.com/php/php_forms.asp
( And if you are using GET or POST variables in your SQL query, be aware of SQL Injections )
If you want to run your PHP function without reloading the page, you should use AJAX. Check this page to understand how it works. A very easy way to use it is to use jQuery

check out form that would match zipcode to an email

I need to create a check out form that would automatically select a zip code from the billing address on the form and match the zip code with an assigned email. Each email will have multiple zip codes assigned to them. The form that I currently have is in cgi and I am not sure if it can implement this since it doesn't actually run off a data base.
I am looking for any opinion on how to accomplish this with out creating a database.
I am familiar with java script, php and html (cgi), is there anyway to do this with out creating a database using java script?
If I cant come up with anything, I may have to re-do everything and use a SQL DB for it.
Thank you.
you can have a JSON object in the Form which will hold all the zip code and email. something like this -
<script type='text/javascript'>
var emails = [{zip:12345,email:'test#email.com'},{zip:12312,email:'test#email.com'},{zip:12123,email:'email#test.com'}];
</script>
then you can get the email address by iterating through the object array using javascript. if you use jquery then you would to something like this to iterate
$.each(emails,function(i,item){
if(item.zip == zip_code_in_address)
variable_to_hold_email = item.email;
});
check the JSFiddle here

Categories

Resources