AJAX .load() returns NULL - php

I'm building a website in PHP and I'm trying to implement asynchonous behaviour on some occasions, in this case to load an HTML form into an overlay and making it visible. This works as intended, however I'm now testing everything considering existing data.
So I basically created a variables.php file that sets values to the $_SESSION global and was working from there. Everything was working as expected on index.php, but as soon as I click the overlay I notice the values aren't passing through to populate the form that was added.
I already poked google for a few hours to no avail. I've added echo var_dump($_SESSION); on the index.php file and the values are all there. However on the overlay it returns NULL. I've even include_once("loginForm.php") right in the middle of index.php and that gave me the values. So there's something I'm missing in order to get the values to apply to .load() elements.
Here's some code:
variables.php
//added values to the $_SESSION global for testing purposes
$_SESSION['email'] = 'john#john.com';
$_SESSION['password'] = 'johnny';
$_SESSION['name'] = 'John';
$_SESSION['surname'] = 'Smith';
$_SESSION['country'] = 'UK';
$_SESSION['phoneOption'] = 'Mobile';
$_SESSION['phone'] = '987654321';
header-login.php
//this form accepts an email to check ifExists() and decide what's next
//the input #preLoginEmail assumes the value correctly
<form action="header-login.php" name="preLoginForm" id="preLoginForm" method="post">
<div id="login-part2">
<table id="preLoginTable">
<tr>
<td colspan="2">
<input type="text" id="preLoginEmail" title="Email" name="test-email" tabindex="1" size="10" maxlength="60" placeholder="Email" value="'. $email .'" />
</td>
</tr>
<tr>
<td><a title="forgotten password" href="header-login.php" id="preLoginForgot">forgot password?</a></td>
<td><input type="submit" class="btn1" name="preLoginRegisterButton" id="preLoginRegisterButton" tabindex="1" value="Login / Register" /></td>
</tr>
</table>
</div>
echo var_dump($_SESSION);//works
</form>
onClickEvents.js
//this call retrieves the HTML correctly although the variables dont get assigned to the input's value
$( "#preLoginForm" ).submit(function( event ) {
event.preventDefault();
var $form = $( this ),
term = $form.find( "input[name='test-email']" ).val(),
url = $form.attr( "action" );
verifiedEmail = validateEmail(term);
if(verifiedEmail){
// Put the results in a div
$('#olContainer').load("../inc/loginForm.php");
overlayOn();
}
else {
$('.session-stat').css({ "background-color": "#A60000" });
}
});
loginForm.php
//when this form is loaded there are no values in the inputs and var_dump($_SESSION) returns NULL
<form id="loginForm" name="loginForm" method="post" action="booking.php">
//some blocks are static and created in plain html
<input name="email" type="text" class="dDown12" id="agentuser" size="20" maxlength="20" value="<?php echo $email; ?>" />
//others are php variables to make the if/else statement more readable
$countryBlock ='<input name="agentuser" type="text" class="dDown12" id="agentuser" size="20" maxlength="20" value="'. $country .'" />';
echo var_dump($_SESSION); //NULL
I kinda ran out of ways to figure out what's going wrong, and I just started learning about AJAX this week. If u need anything else just let me know in comments I'll try to be quick to edit. Thanks in advance.

#Fernando - I didn't know which way you decided to go, but if you have to use $_SESSION for this, include:
session_start();
at the beginning of each file you plan to use sessions on, before any content is rendered. Also, be careful to have a means for your users to overwrite their values, ie. with a post, so that once a value gets put in session, there is a way to change it and it doesn't keep overwriting the (new) value. I usually clear out my sessions on Page one of the form. You can do a
unset($_SESSION['test-email']);
...to unset the values. You can use a foreach loop here too.
A great site to compare the speed of loops in PHP is http://www.phpbench.com/ also.
Best of luck!

Related

Saving form values with php and calling cookie using SESSION

I am making a form in html. When a person clicks on submit, it checks if certain fields are filled correctly, so pretty simple form so far.
However, i want to save the text which is typed into the fields, if a person refreshes the page. So if the page is refreshed, the text is still in the fields.
I am trying to achieve this using php and a cookie.
// Cookie
$saved_info = array();
$saved_infos = isset($_COOKIE['offer_saved_info']) ? explode('][',
$_COOKIE['offer_saved_info']) : array();
foreach($saved_infos as $info)
{
$info_ = trim($info, '[]');
$parts = explode('|', $info_);
$saved_info[$parts[0]] = $parts[1];
}
if(isset($_SESSION['webhipster_ask']['headline']))
$saved_info['headline'] = $_SESSION['webhipster_ask']['headline'];
// End Cookie
and now for the form input field:
<div id="headlineinput"><input type="text" id="headline"
value="<?php echo isset($_SESSION['webhipster_ask']['headline']) ?
$_SESSION['webhipster_ask'] ['headline'] : ''; ?>"
tabindex="1" size="20" name="headline" /></div>
I am new at using SESSION within php, so my quesiton is:
Is there a simpler way of achieving this without using a cookie like above?
Or what have i done wrong in the above mentioned code?
First thing is I'm pretty sure you're echo should have round brackets around it like:
echo (isset($_SESSION['webhipster_ask']['headline']) ? value : value)
That's not really the only question your asking though I think.
If you're submitting the data via a form, why not validate using the form values, and use the form values in your html input value. I would only store them to my session once I had validated the data and moved on.
For example:
<?php
session_start();
$errors=array();
if($_POST['doSubmit']=='yes')
{
//validate all $_POST values
if(!empty($_POST['headline']))
{
$errors[]="Your headline is empty";
}
if(!empty($_POST['something_else']))
{
$errors[]="Your other field is empty";
}
if(empty($errors))
{
//everything is validated
$_SESSION['form_values']=$_POST; //put your entire validated post array into a session, you could do this another way, just for simplicity sake here
header("Location: wherever.php");
}
}
if(!empty($errors))
{
foreach($errors as $val)
{
echo "<div style='color: red;'>".$val."</div>";
}
}
?>
<!-- This form submits to its own page //-->
<form name="whatever" id="whatever" method="post">
<input type="hidden" name="doSubmit" id="doSubmit" value="yes" />
<div id="headlineinput">
<input type="text" id="headline" value="<?php echo $_POST['headline'];?>" tabindex="1" size="20" name="headline" />
<!-- the line above does not need an isset, because if it is not set, it will simply not have anything in it //-->
</div>
<input type="submit" value="submit" />
</form>

Initialise a html input text field from a php variable

I'm a beginner to web programming and need help with html input field initialisation from a php variable. I have one php file with a table with input fields and buttons etc. javascript and jquery is used to handle the processing. Now I want to get data from a server which will be stored in php variables. This is a code extract:
<body>
<php?
$voltage = "012";
// $_POST['voltage']; // tried this
?>
<table>
<td><input name="GETVOLTS_textfield" type="text" id="GETVOLTS_textfield" value="<?php echo $_POST['voltage'];?>" size="3" maxlength="3" />
%</td>
</table>
</body>
I get a message Undefined index : voltage
At this stage I am working with XAMPP localhost and don't have any database, I need to be able to handle the variables locally before worrying about the DB.
Any help would be much appreciated.
Try isset()
<input name="GETVOLTS_textfield" type="text" id="GETVOLTS_textfield" value="<?php echo isset($_POST['voltage'])?$_POST['voltage']:'';?>" size="3" maxlength="3" />
if you want to use the variable $voltage your code should look like this:
<input name="GETVOLTS_textfield" type="text" id="GETVOLTS_textfield" value="<?php echo $voltage; ?>" size="3" maxlength="3" />
you can set $voltage with a specific posted var
$voltage = $_POST['voltage'];
but you should test if your variable $_POST['voltage'] is set, because you will get your mentioned error if nothing or just this variable is not posted
you can do this with isset
if(isset($_POST['voltage'])
{
$voltage = $_POST['voltage'];
}
else
{
$voltage = '';
}
I get a message Undefined index : voltage
Was there a voltage value posted in the form? There's an order of events taking place here. First your server-side code executes, then the page renders, then the user posts the form value to server-side code. So if in the first step you're looking for a form value:
$_POST['voltage'];
That value isn't going to be there because the user hasn't posted it yet. You can test for the value before trying to use it:
if (isset($_POST['voltage'])) {
// the value exists
}
This is commonly used when the same page (and, thus, the same server-side code) is used for both creating the form and handling the posted form. If that's the case for you then you'll need to include such conditionals because the server-side code can't use form values that aren't posted yet.
Just use $voltage. The $_POST array will only have values in it if a form submitted values to your script.
<td><input name="GETVOLTS_textfield" type="text" id="GETVOLTS_textfield" value="<?php echo $voltage;?>" size="3" maxlength="3" />
1) May-be you should consider doing : (despite it's not recommanded, that's what you're trying to do)
$voltage = "012";
$_POST['voltage'] = $voltage;
2) You don't need $_POST variables. Just echo $voltage !

What is right method to repopulate field values after submit.?

I am using sessions to repopulate values in form,Its look something like this
My form have some fields and I want to populate user entered values after sever side validattions.Below is the form:
<html>
<form>
Name: <input type="text" id="name" name="name" value="<?php if(isset($_SESSION['NAME'])) echo $_SESSION['NAME'];?>" >
Address:<input type="text" id="address" name="address" value=<?php if(isset($_SESSION['ADDRESS'])) echo $_SESSION['ADDRESS']; ?>>
</form>
</html>
I am storing the values in action page like this:
<?php
$_SESSION['NAME'] = $strname ;
$_SESSION['ADDRESS'] = $straddress;
?>
want to know whether this is the right way to do it,to populate user entered values after server side validation.Although it works fine.
There is no need to store it in session variables if you need it to use just after you have posted the form. You can either use $_POST or $_GET depending upon the form submission method you use.
Also you can use extract function on $_POST or $_GET to get the posted values using it's field name.

Create a page with PHP and redirect to it

I have a form and the form method is set to post. It is connected with a second file which creates a session.
I would like to create a page with a unique url from that second file automatically with PHP and redirect to that page.
If possible insert some code to the created page.
This is the form code:
<form action="file_upload.php" method="post"
enctype="multipart/form-data">
Title: <input type="text" name="file_title" maxlength="55" required><br>
Description: <input type="text" name="file_description" maxlength="80" required><br>
<input type="submit" value="Title Magic">
</form>
This is the 2nd file code:
$title = substr($_POST['file_title'],0,55);
$description = substr($_POST['file_description'],0,80);
if(isset($_POST['file_title']))
$_SESSION['ses_file_title'] = $_POST['file_title'];
if(isset($_POST['file_description']))
$_SESSION['ses_file_description'] = $_POST['file_description'];
What I would like it to do is redirect to a page with a unique url and echo out these statements.
you have to get a value in hidden field after that forward it in $abc variable with if(isset()) condition,
after that for redirection use<script>window.location="filename.php?edt=<?php echo $abc ?>"</script> you'll get id with session on next page and use MySql to retrieve data for automatically created page... hope this will help
You can add yourcode in hidden field or use file_upload.php?code=yourcode and you can access it by request and use below php code for redirection.
header('Location: unique url ');

After first visit, auto populate a form with previous user input using PHP cookies?

Basically I want to create a cookie in PHP that remembers what a user has entered into a form (that directs to a separate page), so that anytime they come back to the page, the form is already prepopulated with whatever information they put into it the first time around.
I've looked everywhere and can't really find a good answer for how to do this. This is how my code is configured right now (which isn't working).
PHP:
$fname = $_POST['fname'];
$lname = $_POST['lname'];
setcookie( "fname", $fname, time() + 36000 );
setcookie( "lname", $lname, time() + 36000 );
HTML:
<form method="post" action="hidden.php">
<p>
First Name: <input type="text" maxlength="40" name="fname" id="fname" value="
<?php
if(isset($_COOKIE['fname']))
{
echo $_COOKIE['fname'];
}
else
{
echo "";
}
?>"/>
</p>
<p>
Last Name: <input type="text" maxlength="40" name="lname" id="lname" value="
<?php
if(isset($_COOKIE['lname']))
{
echo $_COOKIE['lname'];
}
else
{
echo "";
}
?>"/>
</p>
Any mind telling me what I'm doing wrong and how I can fix it? Thank you!
You're close, however $fname in your HTML is empty (presuming you've submitted all relevant code). You need to either set $fname to the value of $_COOKIE['fname'], or just echo the cookie value directly. For instance:
echo $_COOKIE['fname']; // Be sure to sanitize this!

Categories