loading same page in php on basis of query - php

I am trying to do nothing if search field is left blank, and load another page if something entered.
so, How to load same php page when input textbox value is blank, and a different php page when input text value is not blank...?
for e.g.
<input id="srch" type="text" name="query" >
if value of this textbox is "", then same php page should get loaded
else, other page....
is there any way in php or javascript..?

You could use a simple onsubmit function for your form:
<form method="post" action="<?php $_SERVER['PHP_SELF']?>" onSubmit="return validate()" id="searchForm">
<input id="srch" type="text" name="query" >
<input type="submit" value="Submit">
</form>
<script type="text/javascript">
function validate(){
if(document.getElementById('srch').value != ''){
document.getElementById('searchForm').action = 'YOUR_OTHER_PAGE';
}
}
</script>
In the above example, then the form is submitted, it goes to a validate() function in javascript. This function quickly checks to see if the #srch is empty. If it's not then it changes the action of the form to the page that you designate. I set that value to YOUR_OTHER_PAGE, and you would have to change it to the appropriate page. If the value of #srch is empty then it keeps the action which I set as PHP_SELF.

In PHP, in the script that checks the contents of the query, you can do this:
if( isset($_GET['query']) && $_GET['query'] != '' ) {
header('Location: someotherpage.php?query=' . urlencode($_GET['query']));
exit();
}
This qill instruct the browser to go to someotherpage.php

In PHP - after submiting the form - let's say to a script called decide.php
it's content:
if (!isset($_GET['query']) || $_GET['query']=='' )
include "emptysearchlanding.php";
else
include "somethingelse.php";

Here is the code that I use you can decide what to do by using inputString.length == 0 for blank input and just do if statement to execute your second function.
the code that I included in my answer is used to post the input automatically to the php file.
javascript :
<script type="text/javascript">
function lookup(inputString) {
if(inputString.length == 0)
{
$('#suggestions').hide();
}
else
{
$.post("http://www.example.com/suggest.php", {queryString: ""+inputString+""}, function(data){
if(data.length > 0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
}
function fill(thisValue) {
$('#inputString').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
function outoffocus() {
setTimeout("$('#suggestions').hide();", 200);
}
</script>
HTML :
<form id="search" action="/search.php" method="get">
<input type="text" name="search" id="inputString" onkeyup="lookup(this.value);" onblur="outoffocus()" onfocus="lookup(this.value);"/>
<input type="submit" value=" " />
<div class="suggestionsBox" id="suggestions" >
<div class="suggestionList" id="autoSuggestionsList">
</div>
</div>
</form>

Related

Multiple fileds : remember input values after submit

I have a multiple field input and I want to remember the input values after submitting it , how can I do that using php or maybe another language if it is possible?
I have this input:
<input type="text" name="passport[]" class="form-control" aria-describedby="basic-addon1"required/>
I have tried something like this :
value="<?php if(isset($_POST['passport'])) { echo $_POST['passport'][$i]; } ?>"
but nothing works.
You can use browser local storage to keep the value after form submission.
<form method="post" action="" onSubmit="return saveElement();">
<input type="text" name="passport[]" id="password"/>
<input type="submit" name="submit" value="save"/>
</form>
<script type="text/javascript">
document.getElementById("password").value = localStorage.getItem("password");
function saveElement() {
var passValue = document.getElementById("password").value;
if (passValue == "") {
alert("Please enter a password first!");
return false;
}
localStorage.setItem("password", passValue);
location.reload();
return false;
}
</script>

Submit form using ajax: Was working, now not working?

I have the following HTML form in signup.php:
<form id="signup" action="" method="POST" autocomplete="off" autocomplete="false">
<div class="signup_row action">
<input type="text" placeholder="What's your Name?" name="name" id="name" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<input type="text" placeholder="Got an Email?" name="email" id="email" class="signup" autocomplete="new-password" autocomplete="off" autocomplete="false" required />
<div class="g-recaptcha" style="margin-top:30px;" data-sitekey="6LeCkZkUAAAAAOeokX86JWQxuS6E7jWHEC61tS9T"></div>
<input type="submit" class="signup_bt" name="submit" id="submt" value="Create My Account">
</div>
</form>
I am trying to submit the form using ajax, without page refresh:
<!-- include files -->
<?php include 'assets/config.php';?>
<?php if(isset($_SESSION["CUSTOMER_ID"])){
header('Location: myaccount.php'); } ?>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'do_signup_check.php',
data:{"name":name,"email":email},
success: function () {
if(result == 0){
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('do_signup.php',function(){}).hide().fadeIn(500);
});
}else{
$('.signup_side').fadeOut(500).promise().done(function() {
$('.signup_side').load('assets/login.php',function(){}).hide().fadeIn(500);
}
});
});
});
</script>
I am posting the form to do_signup_check.php and running a query to see if the user is already registered. echo 1 for a positive result and 0 for a negative result:
Do_Signup_Check.php:
<?php
session_start();
require 'assets/connect.php';
$myName=$_POST["name"];
$myEmail=$_POST["email"];
$check = mysqli_query($conn, "SELECT * FROM user_verification WHERE email='".$myEmail."'");
if (!$check) {
die('Error: ' . mysqli_error($conn)); }
if(mysqli_num_rows($check) > 0){
echo '1';
}else{
echo '0';
}
?>
If the result is 0 then the ajax should load my page do_signup.php.
But alas it is not getting this far. It was working and then i switched off the computer and came back to it and now it won't work.
Please can someone show me where I've gone wrong?
if(result == 0){ here result is not using in success function:
you must need to pass resultant variable here:
success: function () {
as:
success: function (result) {
Now, you can use your condition if(result == 0){
Second, i suggest you to pass dataType: 'html' in your ajax request.
Edit:
You are using <?php if(isset($_SESSION["CUSTOMER_ID"])){ line in your code, if you are not using session_start() in your code then this check will not work.
For this line data:{"name":name,"email":email}, i didnt see name and email in your code, where you define these 2 variables which you are using in your ajax params.

Only pass GET information if isset

I am using a form with the method of GET to add to the query string.
I am running into an issue. When the form is submitted every field is sent and added to the query including with no values.
Example:
http://web.com/?filter-types=news&filter-document-type=&filter-topics=we-have-a-topic&filter-featured=&filter-rating=
Can I not add these to the query string if they are not set? !isset() or is there another way to do this?
You could alternatively manipulate the form inputs thru javascript, just a Mike said in the comments, on submit check the fields, if empty, disable them so that they wont be included on submission.
This is just the basic idea (with jQuery):
<form method="GET" id="form_inputs">
<input type="text" name="field1" value="field_with_value" /><br/>
<input type="text" name="field2" value="" /><br/><!-- empty field -->
<input type="text" name="field3" value="field_with_value" /><br/>
<input type="submit" name="submit_form" id="submit_form" value="Submit" />
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$('input[name="submit_form"]').on('click', function(e){
e.preventDefault();
$('form').children().each(function(i, e){
if($(e).is('input') && $(this).val() == '') {
$(this).prop('disabled', true);
// or $(this).attr('name', '');
}
});
$('form').submit();
});
</script>
Or if you do not want to use jquery at all:
document.getElementById('submit_form').addEventListener('click', function(e){
e.preventDefault();
var children = document.getElementById('form_inputs').childNodes;
for(i = 0; i < children.length; i++) {
if(children[i].type == 'text' && children[i].value == '') {
children[i].disabled = true;
}
}
document.getElementById('form_inputs').submit();
});
The reason all those keys show up in query string is because they exist as inputs in the form. If you don't want them sent, remove them from the form, or at least give them some meaningful defaults.
I guess you are looking a condition
if (!empty($_POST['var'])) {
}
OR
if (!isset($_POST['var']) && !empty($_POST['var'])) {
}

Redirect GET form with action in another url

I have a form with the action set to "/resutls". But i have a txt input and i want to check if that is not empty to redirect to another location than "/results". Is this possible?
Code example as below:
<form id="results" action="/results" method="get">
<select id="country" name="country">
....
</select>
<input type="text" name="id">
<input type="submit" class="form-submit" value="Apply Search" name="submit">
</form>
Any ideas? Can this be done with jquery?
Sure you can do that in the submit handler. Warning: I wouldn't give a form control a name of id. It does cause confusion: if this refers to the form, should this.id refer to the id of the form or the text field with name="id"?
if( !!this.somefield.value ) { //did not want to write this.id.value !!!!
this.action = '/other-url';
} else {
this.action = '/results';
}
$(function() {
$('#results').on('submit', function(e) {
e.preventDefault(); // just so we can see that form action changes
if( !!this.somefield.value ) {
this.action = '/other-url';
} else {
this.action = '/results';
}
alert( this.action );
//$(this)[0].submit(); //now submit the form
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="results" action="/results" method="get">
<select id="country" name="country">
</select>
<input type="text" name="somefield">
<input type="submit" class="form-submit" value="Apply Search" name="submit">
</form>
Yes it is possible. Just set the form element's action property using jQuery .prop().
As a simple example:
var valid = false;
// go though validation here
if (false === valid) {
$('#results').prop('action', '/some/url/to/redirect/to');
}
HTML5 provides the "required" attribute wich will prevent the form for being posted, use it like this
<input type="text" name="id" required="required">
or, if you prefer to redirect to other page instead, you can do this
<script src="js/jquery-1.11.1.min.js" type="text/javascript"></script>
<script>
$("#results").submit(function (e){
e.preventDefault();
if($("#results input[name='id']").length < 1){
window.location.href = "your detiny url";
}
else{
this.submit();
}
});
</script>

jQuery Trigger Form Submit on Page Load if GET Parameters are set

I am trying to submit the form on my page upon page load if there are certain parameters set in the query string. The form submits using ajax and works fine and the pre-population of the form fields from the query string is fine aswell but no matter what I try to automatically submit the form, I end up in an infinite loop of page loads.
PHP
// top of page
<?php
if (isset($_GET['postcode'])) {
$postcode = trim($_GET['postcode']);
} else {
$postcode = '';
}
if (isset($_GET['phone_num'])) {
$phone_num = trim($_GET['phone_num']);
} else {
$phone_num = '';
}
?>
jQuery
/*
// causing infinite page loads
if ($('input[name="phone_num"]').val() != '' || $('input[name="postcode"]').val() != '') {
$('#check').trigger("click");
return false;
}
*/
$('form').submit(function() {
$.get("script.php", $(this).serialize(), function(data){
// process results
}, "json");
return false;
});
HTML
<form class="navbar-form pull-right" action="" method="get">
<input class="span2" type="text" name="phone_num" placeholder="Phone Number" value="<?php echo $phone_num; ?>">
<input class="span2" type="text" name="postcode" placeholder="Postcode" value="<?php echo $postcode; ?>">
<button type="submit" class="btn btn-primary" id="check">Check</button>
</form>
Instead of using a click function for the auto form submit I've tried doing the same $('form').submit but I get the same problem. I was expecting the page to function as normal so that if the parameters were set then the ajax call would automatically be made but this is obviously not the case.
You're exiting your code before you bind the submit event. Remove the return false in your if statement, then move the if statement to after the submit binding.
$('form').submit(function() {
$.get("script.php", $(this).serialize(), function(data){
// process results
}, "json");
return false;
});
if ($('input[name="phone_num"]').val() != '' || $('input[name="postcode"]').val() != '') {
$('#check').trigger("click");
//return false;
}
Try something like this:
if($('input[name="phone_num"]').val() && $('input[name="postcode"]').val()) {
$('form').submit(function() {
$.get("script.php", $(this).serialize(), function(data){
// process results
}, "json");
return false;
}).submit();
}
use this line on your code.
$('form').trigger("submit");
HTML
<form class="navbar-form pull-right" action="" method="get">
<input class="span2" type="text" name="phone_num" placeholder="Phone Number" value="<?php echo $phone_num; ?>">
<input class="span2" type="text" name="postcode" placeholder="Postcode" value="<?php echo $postcode; ?>">
<input type="button" class="btn btn-primary" id="check">Check</button>
</form>
jQuery
$('#check').click(function(e) {
e.preventDefault();
$.get("script.php", $('form').serialize(), function(data){
// process results
}, "json");
return false;
});
if ($('input[name="phone_num"]').val() != '' || $('input[name="postcode"]').val() != '') {
$('#check').trigger("click");
}
When using a submit button, you are performing the default event (submitting the form) as well as processing the handler of the .click() event. To avoid this, use e.preventDefault(); causing only the scripted portion of the event to process.

Categories