Is there any possible way to initialize localStorage after a successful PHP Validation?
I have 2 separate registration pages/forms and Im using CodeIgniter's form validation library and I want to store registration data in localStorage after validating it in Controller.
What I already did is store input values in localStorage on form submit. But I want to validate the form first before I initialize localStorage.
Controller
public function register(){
if($this->input->method == 'post'){
// form_validation set_rules
if($this->form_validation->run() == TRUE){
// initialize localStorage
// then redirect to registration form 2
} else {
// display error message
// redirect to same page
}
}
}
register_view
$("#reg-form1").submit(function(){
localStorage.firstname = "<?php echo set_value('reg_first_name'); ?>";
localStorage.middlename = "<?php echo set_value('reg_middle_name'); ?>";
localStorage.lastname = "<?php echo set_value('reg_last_name'); ?>";
localStorage.gender = "<?php echo set_value('reg_gender'); ?>";
localStorage.birthdate = "<?php echo set_value('reg_birthdate'); ?>";
localStorage.address = "<?php echo set_value('reg_address'); ?>";
localStorage.email = "<?php echo set_value('reg_email'); ?>";
localStorage.mobile_number = "<?php echo set_value('reg_mobile_number'); ?>";
});
<form method="post" id="reg-form1">
<input type="text" name="reg_first_name">
// other inputs . . .
// <submit button
</form>
How should I validate the form before initializing localStorage? and what is the best practice on where the localStorage should be placed?
Thank you in advance! :)
Related
I want to stay same modal after submitting this form
generateBarcode.php:
<form action="savegenarateBarcode.php?id=<?php echo $d1; ?>" method="post">
savegenerateBarcode.php:
<?php
try {
session_start();
include('../connect.php');
$d1 = $_GET['id'];
$b = $_POST['serialnumber'];
$sqlm = "select *from product_item where serialnumber='".$b."'";
$query = $db->prepare($sqlm);
$user_array = $query ->execute();
}
How can I stay same generateBarcode.php(modal) after submitting this form?
I think you should use ajax because the form submit method reload the page.
var id = '<?php echo $d1; ?>';
$("#submit").click(function(){
$.ajax({
type: 'GET',
url: "savegenarateBarcode.php",
data:`id=${id}`
success:function(data){
alert(data);
}
});
return false;
});
It's probably super-simple, but I want to update the PHP variables by getting a new random record from the SQL server, and then pass those variables into JavaScript to use them, however the PHP function I've called only works once and then stops working. I don't know if something is wrong with the function call or with the function itself.
<?php
function getQuestion(){
$conn = mysqli_connect("localhost", "root", "pass", "projectDB");
$sql = "SELECT question, answerA, answerB, answerC, answerD,
correctAns FROM questionTable ORDER BY rand() LIMIT 3";
global $result, $row, $question, $answerA, $answerB, $answerC,
$answerD, $correctAns;
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$question = $row["question"];
$answerA = $row["answerA"];
$answerB = $row["answerB"];
$answerC = $row["answerC"];
$answerD = $row["answerD"];
$correctAns = $row["correctAns"];
mysqli_close($conn);
}
getQuestion();
?>
<script>
var answerA = "<?php echo $answerA; ?>";
var answerB = "<?php echo $answerB; ?>";
var answerC = "<?php echo $answerC; ?>";
var answerD = "<?php echo $answerD; ?>";
var question = "<?php echo $question; ?>";
var correctAnswer = "<?php echo $correctAns; ?>";
function newQuestion(){
<?php getQuestion(); ?>
question = "<?php echo $question; ?>";
answerA = "<?php echo $answerA; ?>";
answerB = "<?php echo $answerB; ?>";
answerC = "<?php echo $answerC; ?>";
answerD = "<?php echo $answerD; ?>";
correctAnswer = "<?php echo $correctAns; ?>";
}
else if (targetHit == true){
reset();
newQuestion();
tick = 0;
}
</script>
The first time the variables are defined and getQuestion() is used in the top PHP, they get correct values, and the first time newQuestion() is called they get updated with different correct values, however after that, calling newQuestion() does not change any of the values like it should.
Thanks.
Its not a correct way to write php code in javascript even we should not write php code in javascript. better to retrieve value from database and store value on javascript variable by ajax request. its give you sql result every time.
make a php file to retrieve data and another php or js file to ajax request.
here a code for
php files as wrote
function getQuestion(){
$conn = mysqli_connect("localhost", "root", "pass", "projectDB");
$sql = "SELECT question, answerA, answerB, answerC, answerD,
correctAns FROM questionTable ORDER BY rand() LIMIT 3";
global $result, $row, $question, $answerA, $answerB, $answerC,
$answerD, $correctAns;
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$question = $row["question"];
$answerA = $row["answerA"];
$answerB = $row["answerB"];
$answerC = $row["answerC"];
$answerD = $row["answerD"];
$correctAns = $row["correctAns"];
mysqli_close($conn);
return $correctAns;}
echo json_encode(getQuestion());
here ajax request to get result
$.ajax({
type: 'post',
url: 'phpfilename.php',
success: function ( data ) {
alert(JSON.parse(data));
},
error:function(error){
console.log(error);
}
});
I am trying to work on a module where there is an option to show the JavaScript alert and then it should redirect to a php $url. My script is attached below.
$url1=$_SERVER['HTTP_REFERER'];
$url = preg_replace('/\?.*/', '', $url1);
echo "<script type='text/javascript'>alert('Quote Emailed Successfully.');
url = '<?php echo $url; ?>';
window.location='url';
</script>";
It is showing the alert but it's not redirecting.
url = '<?php echo $url; ?>';
You can't nest <?php ... ?> blocks.
Just use the variable. You are in a double quoted PHP string literal, so it will be interpolated.
url = '$url';
window.location='url';
You are trying to redirect to the URL url instead of the value of the url variable.
Remove the quotes.
window.location = url;
Try this
$url1=$_SERVER['HTTP_REFERER'];
$url = preg_replace('/\?.*/', '', $url1);
echo "<script type='text/javascript'>alert('Quote Emailed Successfully.');var url = '" . $url; . "';window.location=url;</script>";
or you can also do it like
echo "<script type='text/javascript'>alert('Quote Emailed Successfully.');
window.location='" . $url; . "';</script>";
You are setting window.location to the value 'url'. Notice the quotes. You should use the declared variable url. Just remove the quotes, as shown below.
$url1=$_SERVER['HTTP_REFERER'];
$url = preg_replace('/\?.*/', '', $url1);
echo "<script type='text/javascript'>alert('Quote Emailed Successfully.');
var url = '<?php echo $url; ?>';
window.location= url;
</script>";
you should use location.href to redirect to php url e.g
alert("alert your text ");
location.href = <?php echo $url_name; ?> ;
check this
<script>
$url1=$_SERVER['HTTP_REFERER'];
$url = preg_replace('/\?.*/', '', $url1);
echo "<script type='text/javascript'>alert('Quote Emailed
Successfully.')";
url = '<?php echo $url; ?>';
window.location='url';
</script>";
If you doesn't need to confirm the redirection then using this script might help
<script>
alert('Your message');
setTimeout(locate,3000);
function locate()
{
window.location.replace('PHP URL');
}
</script>
If you need to confirm the redirection
if (confirm('Go to PHP URL'))
{
window.location.replace('PHP URL'); }
else
{
/* Do Something Else*/
}
I check if the user is logged in with, if they are then i pull their details from the database, i then want to auto fill this data into part of my form.
while(OCIFetch($stmt)) {
if(OCIResult($stmt,"PASSWORD")==$Password) {
$flag=true;
$First=OCIResult($stmt,"FIRSTNAME");
$Sur=OCIResult($stmt,"SURNAME");
$Email=OCIResult($stmt,"EMAIL");
$Phone=OCIResult($stmt,"PHONE");
$Address=OCIResult($stmt,"ADDRESS");
$City=OCIResult($stmt, "CITY");
$Post=OCIResult($stmt, "POSTCODE");
//set up session - Declare session variables and assign their corresponding values
session_start();
$_SESSION['RegUser'] = OCIResult($stmt,"USERNAME");
$_SESSION['RegFirst'] = $First;
$_SESSION['RegSur'] = $Sur;
$_SESSION['RegEmail'] = $Email;
$_SESSION['RegPhone'] = $Phone;
$_SESSION['RegAdd'] = $Address;
$_SESSION['RegCity'] = $City;
$_SESSION['RegPost'] = $Post;
}
This is the code im currently attempting to use to auto fill but the fields still appear blank
//Autofill the details if the user is logged in
window.onload = function() {
document.forms['Order']['RegFirst'].value = "<?php echo $First?>";
document.forms['Order']['RegSur'].value = "<?php echo $Sur?>";
document.forms['Order']['RegEmail'].value = "<?php echo $Email?>";
document.forms['Order']['RegPhone'].value = "<?php echo $Phone?>";
document.forms['Order']['RegAdd'].value = "<?php echo $Address?>";
document.forms['Order']['RegCity'].value = "<?php echo $City?>";
document.forms['Order']['RegPost'].value = "<?php echo $Post?>";
}
You don't need javascript for this, just echo the values into your html form fields
<input id="example" value="<?php echo $Post?>" />
Rinse and repeat for all other form fields.
Try this,
//Autofill the details if the user is logged in
window.onload = function() {
document.forms['Order']['RegFirst'].value = "<?php echo $_SESSION['RegFirst'];?>";
document.forms['Order']['RegSur'].value = "<?php echo $_SESSION['RegSur'];?>";
document.forms['Order']['RegEmail'].value = "<?php echo $_SESSION['RegPhone'];?>";
document.forms['Order']['RegPhone'].value = "<?php echo $_SESSION['RegPhone'];?>";
document.forms['Order']['RegAdd'].value = "<?php echo $_SESSION['RegAdd'];?>";
document.forms['Order']['RegCity'].value = "<?php echo$_SESSION['RegCity'];?>";
document.forms['Order']['RegPost'].value = "<?php echo $_SESSION['RegPost'];?>";
}
Im making a like system and am encorporating ajax to make it smooth. Everything works okay except it always defaults to the last post in for loop. My thinking is there is no way for the javascript to know which element of id "like" to post to.
main.js:
$(".like>a").click(function() {
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
Im passing through the post variable from the view file. I grab the postID of each post.
userprofile_view.php:
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
model_posts.php:
function likePost($post) {
$data['user_ID'] = $this->session->userdata('id');
$data['post_liked'] = $post;
$insert = $this->db->insert('user_post_likes', $data);
return $insert;
}
userprofile.php(controller):
public function like_post() {
$this->load->model('model_posts');
$post = $this->input->post('post');
$this->model_posts->likePost($post);
}
If someone couldhelp me out that would be great!
The problem is your usage of a global variable in a loop, so the variable will have only the last value of the loop.
You can use a data-* attribute like
<script type="text/javascript">
var base_url = "<?php echo base_url(); ?>";
</script>
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<div class='posts'>
<div class='posts_img'>
<img src="<?php echo base_url() . 'img/profilepictures/thumbs/' . $profilepicture?>">
</div>
<div class='posts_user'>
<strong><?php echo $prefname; ?></strong>
</div>
<div class='posts_date'>
<?php echo $this->model_posts->getPostTime($post->post); ?>
</div>
<div class='post'>
<p><?php echo $post->post ?></p>
</div>
<?php if($this->model_posts->doesUserLike($me, $postID)) { ?>
<div class='unlike'>
<?php echo anchor('userprofile/unlike_post/' . $me . '/' . $postID, 'unlike'); ?>
</div>
<?php } else { ?>
<div class='like' data-post="<?php echo $postID; ?>">
<?php echo anchor('#', 'like', array('id' => 'like')); ?>
</div>
<?php } ?>
then
$(".like>a").click(function () {
var post = $(this).parent().attr('data-post');
$.post(base_url + "index.php/userprofile/like_post/", {
post: post
}, function (data) {
alert('liked');
}, "json");
return false;
});
if you're sending same ID field with different values stop, send unique IDs with selected values OR send ID with values as post array, PHP can deal with it
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
This is your problem. You're declaring these variables in global scope. So every time your PHP foreach loop iterates, you're redefining the variable in global scope, overwriting the previous value.
Instead, set an id attribute on each <a> tag to be the $postID, and get that ID in your click handler, like so:
$(".like>a").click(function() {
var post = this.id;
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
You would have to modify the code that creates the <a> tags to include the id attribute with the $postID value assigned to it...I don't see that part included in your code samples.