click a link pass a session variable to the next page - php

I have a page where I am using a PHP while loop to echo the names and addresses of our dealers. For the email link, I want the user to be able to click the link, which would then take him to a form that emails that person.
I know that you can't mix Javascript and PHP, so how do I tell which link the user has clicked on so that I can pass that variable to the form on the next page? Here is my code:
<?php while($row = mysql_fetch_array($result)) {
if ($row['active'] == 1) {
?>
<div id="dealer">
<div id="dealername">
<h3 style="float:left;"><?php echo $row['company']; ?></h3><br/>
<p><?php echo $row['address1']; ?><br/>
<?php if($row['address2'] || $row['address3']) {
echo $row['address2'] . ' ' . $row['address3'] . '<br/>'; } ?>
<?php echo $row['city'];
if ($row['state']) {
echo ', ' . $row['state'];
}
echo ' ' . $row['zip']; ?>
<br />
<?php echo $row['country']; ?>
<br />
<br />
Phone: <strong><?php echo $row['phone1']; ?></strong><?php if ($row['phone2']) {
echo ' or ' . $row['phone2']; } ?><br/>
<?php if($row['fax']) { echo 'Fax: ' . $row['fax']; } ?><br />
</p>
</div>
<?php if ($row['email']) {
echo '<div class="dealerEmail">'. // need help here . '</div>';
} ?>
<br class="clearall" />
</div>
<?php }} ?>
The page that this code appears on is pulling data from a database using a GET statement based on a URL similar to "index.php?state=az".
I've tried making the email link use a "?email=..." format but when I go to the dealer-email.php page there are no parameters in the URL, which I don't get. That's why I'm trying to find some other way to pass some kind of variable to the next page, based on which link the user clicks on.
Hope this is clear. Thanks in advance for your help.

this should work fine:
contact dealer
and then you retrieve the data in the somepage.php page:
if(isset($_GET['email']))
$email = $_GET['email'];
else
//redirect somewherelse

I know that you can't mix Javascript
and PHP
This is not true. Javascript is a Client-Side Scripting language, and PHP is Server-Side scripting. They run at different times, on different machines, and will run just fine.
Mixing Javascript and PHP might be a mental challenge and subject to pitfalls, but it definitely can be done, and often is done.

You might skip the email form altogether and include a mailto attribute in your link.
contact dealer
This will open the user's default email client new message window with the address filled in. I understand you may want to use a custom form to prevent someone from spamming all your contacts, but if this is a restricted area for logged in users, or an intranet site, this might work.

Related

Continue Executing PHP after Ajax Call

I have this block of HTML:
<div class="box-body" id="mcontent">
<?php
if (isset($_POST["id"])){
$id = $_POST["id"];
$query=mysqli_query($con,"select complain from tbcomplains where cid = '$id';");
if (mysqli_num_rows($query) > 0){
while($row=mysqli_fetch_assoc($query)){
echo $row["complain"];
}
}
}
echo "<br /> <p />";
echo "<p> Copy this link and paste in the mail for user's responses <br />";
echo "http://" . $_SERVER['HTTP_HOST']. $_SERVER['REQUEST_URI'];
?>
</div>
Which is replaced with this Ajax call, I include the the script below:
$('a').on('click', function(e){
var rex = e.target.id; //$('#this').data('id');
$('#mcontent').load("doload.php", {id:$('#' + rex ).data("id")});
});
The above code works perfectly. Issue is, how do I force this part of HTML to execute after the Jquery has finished.
I want this part of the PHP/HTML to execute:
echo "<br /> <p />";
echo "<p> Copy this link and paste in the mail for user's responses <br />";
echo "http://" . $_SERVER['HTTP_HOST']. $_SERVER['REQUEST_URI'];
Thank you in anticipation.
Knowing the fact that Javascript is a client-side language, you won't be able to "force" PHP to wait for an AJAX response.
The only possibility to modify your existing DOM after the AJAX call would be to use javascript when the query has responded.

variable in header location doesnt work in iframe?

Hi guys i am doing a personal project which i want to use on my small business, i am not that rich thats why i cant afford to hire a developer to do it for me :( my problem is that variable seems not to work if its called on an iframe, ok just like i said im not a pro developer so even on terms im not sure what to use so i will just explain on whatever i can and i hope some one can catch up with me.
an iframe is called on uikit modal, url on iframe have parameters
file is called firstreminder.php and this is the code
<?php
require_once 'layout/header.php';
if(!empty($_GET['message'])){
$sms_msg = 'https://www.experttexting.com/ExptRestApi/sms/json/Message/Send?username=xpertdotmedia&password=c61iQO1E&api_key=4aw0l0noipli133&from=LocalVerify&to=63'.urlencode($_GET['mobile']).'&text=' . urlencode($_GET['message']) . '&type=text';
$msg_json = file_get_contents($sms_msg);
$msg_array = json_decode($msg_json, true);
}
$url = $_SERVER['REQUEST_URI'];
$parts = parse_url($url);
parse_str($parts['query'], $query);
$clientid = $query['userid'];
$getinvid = $query['invid'];
?>
<form action="">
<div class="uk-margin">
<textarea rows="6" cols="50" name="message" class="uk-textarea"/><?php
echo 'Greetings,
Just a friendly reminder for your upcoming due on '.$query['date'].'
Thank you
*auto msg do not reply';
?></textarea>
</div>
<div class="uk-margin">
<?php echo '<input type="text" name="mobile" class="uk-input" value="'.$query['userphone'].'" />';?>
</div>
<div class="uk-margin">
<button class="uk-button uk-button-primary" type="submit">Send</button>
</div>
<?php
if(!empty($msg_array)){
$status = $msg_array['Status'];
if($status!="1"){
header('Location: sent.php?id='.$getinvid);
}
}
?>
</form>
<?php
require_once 'layout/footer.php';
?>
so far its working good as i can fetch value of each parameters, example i can call $query['date']whenever i want and its actually working but problem lies on header location as it doesnt seem to fetch the value of the variable, header location is called whenever the script successfully sent the sms message and then it redirect to sent.php as i want to remind the user that sms was successfully sent and also update the database and this is the code of the sent.php file
<?php
require_once 'layout/header.php';
$senturl = $_SERVER['REQUEST_URI'];
$invURL = parse_url($senturl);
parse_str($invURL['query'], $smsquery);
$invoID = $smsquery['id'];
$updateSentTo = "UPDATE ffcko_invoices_invoices SET last_sent=NOW() WHERE ffcko_invoices_invoices.id=$invoID;";
if (mysqli_query($DBcon, $updateSentTo)) {
echo '<h1 class="uk-h3 uk-text-success">Message Sent <span uk-icon="icon: check; ratio: 1.5"></span></h1>';
echo '<script>window.top.location.reload();</script>';
} else {
echo "Error: " . $updateSentTo . "<br>" . mysqli_error($DBcon);
}
mysqli_close($DBcon);
require_once 'layout/footer.php';
?>
it should go to sent.php?id=(id) so that i can successfully update the database but i always end up with this error
i tried all the combinations i can, i even transfered the code from sent.php to firstreminder.php inorder for it to have a direct control of the variable but still problem occurs as if the $getinvid is being ignored
i think it has something to do with the iframe? you think so? cause if I enter the url directly to my browser
http://localhost/sms/sent.php?id=3
adding the id manually it works as it should and it updates the database so i wonder what im doing wrong?
hope you guys can help me, thank you so much and i hope i have explained it well as english is not my native language so i really really apologize.

How post form data, collect data generate and then redirect to a page?

I have a form which POST's data, I then need to collect this data which I know how to do using
$billingaddress = $post['firstname']
Then after collecting the post data I need to redirect to a set URL
header(Location: www.google.com);
I am just unsure on the setup of which files need to contain what code in terms I need to need to collect the data and simulatously redirect (it will go to sagepay)
This is how you need to use it.
//Posted data stored in $_POST global array
$billingaddress = $_POST['firstname'];
//Do what you want.
//Need to add quotes around the parameter
//Need to use full URL started with the schema (http|https).
header("Location: http://www.google.com");
//Terminate the script after redirect.
exit;
Note: Are you sure you want to collect the firstname into a variable called billingaddress? That is a bad practice. Call your variables what it includes, eg: $firstName
I'm not sure if this is what you're asking, but from one another question somewhere in the void of the internet, I managed to find a good form setup. You need 3 files: nameofform.php, nameofredirectpage.html, and a place to store the data. Here's an example from one of my sites.
The Form Page
<?php
if($_POST['formSubmit'] == "Submit")
{
$errorMessage = "";
/* This section determines the error messages if there is a blank field. */
if(empty($_POST['formSteam']))
{
$errorMessage .= "<li>You need to put your Steam ID!</li>";
}
if(empty($_POST['formName']))
{
$errorMessage .= "<li>Please put your first and/or lastname!</li>";
}
if(empty($_POST['formAge']))
{
$errorMessage .= "<li>Please tell us your age! This is just for reference.</li>";
}
if(empty($_POST['formPos']))
{
$errorMessage .= "<li>You need to give us what position you want!</li>";
}
if(empty($_POST['formApplication']))
{
$errorMessage .= "<li>Do I have to explain this? Please explain why you want to be apart of our staff!</li>";
}
/* This section just labels the variables. */
$varSteam = $_POST['formSteam'];
$varName = $_POST['formName'];
$varAge = $_POST['formAge'];
$varApplication = $_POST['formApplication'];
$varPos = $_POST['formPos'];
/* This is where the magic happens. It's saying that if there is no errors and all the fields are filled in, it will open [or create] the file mydata.csv, which then writes each variable; `$varSteam`, `$varName`, `$varAge`, and so on. Grabbing what the fields content were, it will post the data in the specified order on the [newly created] file, then close the document. Finally, it redirects the user to the selected page, in this case "success.html". */
if(empty($errorMessage))
{
$fs = fopen("mydata.csv","a");
fwrite($fs,$varSteam . ", " . $varName . ", " . $varAge . ", " . $varPos . ", " . $varApplication . "\n");
fclose($fs);
header("Location: success.html");
exit;
}
}
?>
<html>
<body>
<?php
if(!empty($errorMessage))
{
echo("<p>There was an error with your form:</p>\n");
echo("<ul>" . $errorMessage . "</ul>\n");
}
?>
/* This is the field ; change accordingly! */
<form action="application.php" method="post">
<p>
Whats your Steam ID? Find out here!<br>
<input type="text" name="formSteam" maxlength="50" value="<?=$varSteam;?>">
</p>
<p>
What is your name?<br>
<input type="text" name="formName" maxlength="50" value="<?=$varName;?>">
</p>
<p>
How old are you?<br>
<input type="text" name="formAge" maxlength="2" value="<?=$varAge;?>">
</p>
<p>
What position are you applying for?<br>
<select name="formPos" value="<?=$varPos;?>">
<option value="">Pick an Option</option>
<option value="moderator">Moderator</option>
<option value="coder">Coder</option>
<option value="admin">Administrator</option>
<option value="other">Other</option>
</select>
</p>
<p>
Why do you want to apply for PossessedGaming Staff? *NOTE: If the above option was "OTHER", please include that "OTHER" position.<br>
<textarea name="formApplication" maxlength="3000" style="width:325px;height:150px;" value="<?=$varApplication;?>"></textarea>
</p>
<input type="submit" name="formSubmit" value="Submit">
</form>
</body>
</html>
The Redirected Page
<html>
<body>
<center>
<h1>Success!</h1>
<p>Your application will be reviewed by the staff ASAP. Thanks for applying!</p>
</body>
</html>
The example I used was a staff-application form for my site; you can probably modify it accordingly. Again, not sure if this is what you wanted, but... yeah.

POST Data is not sent

I'm having some weird issues with this code block, it's a little school project, going well so far but the form at the bottom is not returning any post data. the var_dump($_POST); never shows any post data being submitted from this particular form.
I just cannot understand why, been struggling with it for so long.
Here's the code, i couldn't understand to format it on this page, adding 4 indents for every line seemed a bit tedious.
<?php session_start();
require_once'user.class.php';
require_once 'posts.class.php';
require_once'comments.class.php';
$posts = new Posts($user->getID(), $db);
$comment = new Comments($user->getID(), $db);
include_once'includes/header.php';
include_once'includes/nav.php';
?>
<h2><br></h2>
<?php
include_once'includes/intro.php';
// CONTENT
$post = $posts->showPost($_GET['id']);
$title = $post['title'];
$content = $post['content'];
$created = $post['timestamp'];
echo "<section> <article class='blogPost'> <header> " . " <h2>$title</h2> " . "<p> Posted on $created <a href ='#comments'> X comments</a></p></header>" . "<p>$content</p>" . "</article> </section>";
var_dump($_POST);
if (isset($_POST['submit_comment']) && isset($_POST['id_comment'])) {
echo "Kom seg inn i ifen";
$pid = $_GET['id'];
$comment->newComment ($db, $user->getID(), $pid, $_POST['id_comment']);
header ("location: showPost.php?id=$pid");
exit ();
}
?>
<form name='commentform' action='showPost.php?id=<?php echo $_GET['id'];?>' method='POST'>
<h3>Post a comment</h3>
<p>
<label for='id_comment'>Comment</label>
<textarea name='id_comment' id='id_comment' required></textarea>
</p>
<p><input style='width: 100%;' type='submit' name='submit_comment' value='Legg til kommentar' /></p>
</form>
<?php
include_once'includes/asidefooter.php';
?>
Thanks for all help!
It looks like if post is data present, the user is redirected. You will only see the post data at the time the form is submitted, and the redirect will cause another page load and the data won't be present anymore.
Can you see the post data if you comment out the redirect, with:
//header ("location: showPost.php?id=$pid");
//exit ();
Something is causing a redirect, which is turning the request into a GET. If you're trying to submit to a index.php then don't forget the ending slash.

I haven't been able to discover how to make a button submit a FORM ~ and ALSO, work as an <a> LINK

I have scoured W3Schools, HTMLGoodies, Tizag and a dozen or 15 other ... sites; nothing really addresses this. The closest discussion I found is the Question "How best to make a link submit a form" right here on StackOverflow, but that is a little past my grasp at the moment.
Just figured with PHP and HTML, the job would be doable. Have things advanced in the last 3 years or is it still a matter of using JavaScript or some other language, and having to get into the DOM to make it all work?
Really hate to have to use one button to get the user to the spot on the page needed, then have to click a second button to open the div with the content displaying in it. Much rather they be able to click a button View Comments and the page goes to the and the content is visible.
The last 2 times I have asked a question in here, were good; one in particular I was very grateful for. Cheers! and if anyone has an answer I'd sure appreciate their help.
I could post 100 or so lines of code; a little demo, but will hold off on that. Also, didn't wish to write out the half dozen or more things I tried which were ineffectual. :)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<?php error_reporting(E_ALL); $MeToo = mysql_connect('localhost','root','GuessHarder'); ?>
<?php if (!$MeToo) {die ('What ~ ARE you a Novice? !!! ? : ' . mysql_error());} ?>
<?php $InestimableUtility=99; ?>
<html><Head><Title>YESH Link VIEWER</Title>
<meta http-equiv="Content-Type" content="text/html; 06 charset=iso-8859-1 application/pdf text/plain text/css text/php ">
<link rel="stylesheet" type="text/css" href="YESH Tha CSS.css"/><br />
<?php
// 3 sets of catching POSTS and setting some Vars.
$LINKfetched1=$_POST["1"];
$SleightOfHandx1= substr('\$LINKfetched1 ', 13);
$LinkzFaithfulListener1=$_POST["NICExExplosions1"];
$NICExExplosions1=99;
$LINKfetched2=$_POST["2"];
$SleightOfHandx2= substr('\$LINKfetched2 ', 13);
$LinkzFaithfulListener2=$_POST["NICExExplosions2"];
$NICExExplosions2=99;
$LINKfetched3=$_POST["3"];
$SleightOfHandx3= substr('\$LINKfetched3 ', 13);
$LinkzFaithfulListener3=$_POST["NICExExplosions3"];
$NICExExplosions3=99; ?>
</Head>
<body id="Corpus">
<div id="LinkDisplayMAIN">
<div id="TopOfLinksContainDiv">
<div id="TitlePageLxDiv"><div id="LinkViewerTitleHerSELF">
The Links Viewer
</div><!-- LinkViewerTitleHerSELF --></div><!-- TitlePageLxDiv -->
</div><!-- TopOfLinksContainDiv -->
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><hr />
<pre>
<br /><br /><a name="LinkItemDisplayDiv1">Link 1</a><br /><br />
<div id="AutoGenLINKxDIV1"><br />
<div id="ParamsTOPforLink1"><br />
<div id="DbLINKdataboxy1"><div id="abcLinkNum1"><?php
echo '&nbsp'; ?>Link DB : Link # <?php echo "1"; ?></div><!-- abcLinkNum1 --></div><!-- DbLINKdataboxy1 -->
<div id="AfterLinkNumSpacer1"></div>
</div><!-- from ParamsTOPforLink1 -->
<br /><br /><br />
<?php if($LinkzFaithfulListener1==99 and $InestimableUtility==99){ ?>
<div id="YeahBabyShowThoseNotes1">
<div id="lameDivText1">
<?php echo "In the grand scheme of things, accept that um... you know, well."; ?><br />
</div><!-- lameDivText1 -->
</div><!-- YeahBabyShowThoseNotes1 --><?php } ?>
<div id="BottleFerButtonz1">
<div id="BttnOfLinkx1y1"><div id="Fake11">
<form action="<?php echo $PHP_SELF; ?>"; method="post">
<input type="hidden"name="NICExExplosions1"value="<?php echo $NICExExplosions1; ?>"/>
<button type="submit">Show Notes About This Link</button></form>
Goto Link 1
</div><!-- from Fake11 --></div><!-- from BttnOfLinkx1y1 -->
</div><!-- from BottleFerButtonz1 --><br /><br /></div><!-- from AutoGenDBdtrmndDIV1 -->
</pre><hr /><br /><br /><br />
and a few more blocks, but that is the heart of the script;
and some closing tags.
*** Following Day Edit by OP ***
So an example code block, cleaned up is simply:
<pre>
<a name="Anchored3"></a>
<div id="AutoGenLINKxDIV3">
<div id="ParamsTOPforLink3">
<div id="DbLINKdataboxy3"><div id="abcLinkNum3"><?php
echo'&nbsp'; ?>Link DB: Link #<?php echo "3";?></div></div></div>
<?php if($LinkzFaithfulListener3==99 and $InestimableUtility==99){?>
<div id="YeahBabyShowThoseNotes3">
<div id="lameDivText3">
<?php echo "$someVariableRepresentingTextorImageOrContentofsometype";?><br />
</div></div><?php }?>
<div id="BttnOfRelease3"><div id="FakeGetOuttaJail3">
<form action="<?php echo $PHP_SELF; ?>#Anchored3"method="post">
<?php $PayloadMeNow3=$DaGoodez3; ?>
<input type="hidden"name="Liberte"value="<?php echo $Liberte; ?>"/>
<input type="hidden"name="EveryDangStepNeedsAVariable3"value="
<?php echo $EveryDangStepNeedsAVariable3; ?>"/>
<button type="submit">Return To Link Viewing</button></form>
</div></div></pre>
If you trying to send POST and GET vars you can do it by passing them in form action attribut like:
<form action="mypage.php?var1=1&var2=2&etc=n" method="post">
this will send your fields data with post method and pass GET vars in request too
I misunderstood the question. The only way to submit a form without leaving the page is to submit it with ajax. So you would want to submit it via ajax, then call whatever you ware trying to do such as open the div with the content displaying in it. see here http://www.simonerodriguez.com/ajax-form-submit-example/
<form name="MyForm" action="response_normal.php" method="post" onsubmit="xmlhttpPost('response_ajax.php', 'MyForm', 'MyResult', '<img src=\'pleasewait.gif\'>'); return false; YOURFUNCTIONHERE">
You will need to use javascript to do this. Here's a possible way to make it fallback as a normal link:
Since you are talking about comments, I think an example in terms of a blog would be most suitable. Assume that your body looks like this:
<body>
<h1>My blog post!</h1>
<p>My content</p>
View Comments
<div id="comments></div>
</body>
Here's what you can do:
If the user has javascript enable, use JQuery, YUI or your favorite JS library to send a request to http://site.com/blog/my-blog-post/comments/. Your server can detect if the request is AJAX, send back an HTML fragment containing the comments and then insert it into a comments div.
If the user does not have Javascript enabled, the user will click the link to http://site.com/blog/my-blog-post/comments/. The server can identify that the comments flag is in the link, so it will render the whole page including the comments.
This way, you can have nice AJAX loading for javascript enabled users, and fallback for users without JS.
The question was how to submit a form, and link to a particular place on the same page: with the caveat that it needed to be done with a single button click. Not only stay on the same page, but more or less at the same place on the page; not find the page at the top after the click to view additional info.
My problem was that I had incorrectly thought that an Goto XYZ paired up
with the anchor Here: XYZ would be needed, and a lot of frustrating trying out various placements of those items, led me to worry I must need some other mechanisms to achieve the goal of submitting a form in order to control the opening of a div to show the user content and yet not have the page loading at the top. Also relevant was the desire to permit the user to click a close button to hide the div once the content had been viewed, and again, not have the page open at the top.
The solution was to discover through a whole lot of trial and error, this simple bit of
syntax:
<form action="<?php echo $PHP_SELF; ?>#Anchored3"method="post">
As long as this first component Anchor 3 is in place, the other statement, does not need to be in the script and my experience was that it did harm most places I tried to situate it. The anchor alone, is sufficient.
How drop~dead simple is that!
You can submit a <form> by using the forms action parameter and <input> buttons type parameter as submit and also add an <a> link with attributes such as href='#+your div id' to get it on the same page after submitting the form.
Hope this helps you.
I also had a similar requirement and the only solution I found was to use the form to POST data to the same php file which does a database INSERT, process that post data AND THEN after that utilise curl to extract POST data modify/add more POST values and send it onto another php file like so to send an email;
//send an email
//extract data from the post
$name = $_POST['fname']." ".$_POST['lname'];
$email = $_POST['email'];
$web = "";
$group_name = $_POST['group_name'];
$message = "";
$username = $_POST['username'];
$user_id = mysql_insert_id();
//point to script
$url = 'scripts/emailer.php';
//set POST variables
$fields = array(
'article_id'=>urlencode($article_id),
'name'=>urlencode($name),
'email'=>urlencode($email),
'web'=>urlencode($web),
'message'=>urlencode($message),
'username'=>urlencode($username),
'user_id'=>urlencode($user_id),
'group_name'=>urlencode($group_name),
'messagetype'=>'new_user'
);
//url-ify the data for the POST
foreach($fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
rtrim($fields_string,'&');
//open connection
$email_post = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($email_post,CURLOPT_URL,$url);
curl_setopt($email_post,CURLOPT_POST,count($fields));
curl_setopt($email_post,CURLOPT_POSTFIELDS,$fields_string);
//execute post
$result = curl_exec($email_post); //echo $result for testing
//close connection
curl_close($email_post);
// end email approvers section

Categories