How start a JQuery inside PHP - php

I want to start a jquery (freeow plugin) when I got an error in e-mail input field form.
I'm checking some fields on the form and each error that I got I want to open an alert message.
I can do this using a button, like this...
<div id="freeow-tr" class="freeow freeow-top-right"></div>
<div id="freeow-br" class="freeow freeow-bottom-right"></div>
<div class="form-line-check">
<input id="freeow-title" value="Freeow!" type="hidden" class="text" />
<input id="freeow-error" value="0" type="hidden" />
<input id="freeow-position" value="#freeow-tr" type="hidden" />
<input id="freeow-style" value="smokey" type="hidden" />
<input id="freeow-message" value="Error message..." type="hidden" />
</div>
<div class="form-line">
<input id="freeow-show" type="button" value="Click to Freeow!" />
</div>
How do this without the button? Inside the PHP code.
if ($erro == "0") {
if(filter_var($email01, FILTER_VALIDATE_EMAIL)){
$erro = "0";
} else {
echo "<div id=\"freeow-tr\" class=\"freeow freeow-top-right\"></div> ";
echo "<div id=\"freeow-br\" class=\"freeow freeow-bottom-right\"></div> ";
echo "<div class=\"form-line-check\"> ";
echo "<input id=\"freeow-title\" value=\"Freeow!\" type=\"hidden\" class=\"text\" /> ";
echo "<input id=\"freeow-error\" value=\"0\" type=\"hidden\" /> ";
echo "<input id=\"freeow-position\" value=\"#freeow-tr\" type=\"hidden\" /> ";
echo "<input id=\"freeow-style\" value=\"smokey\" type=\"hidden\" /> ";
echo "<input id=\"freeow-message\" value=\"Error message...\" type=\"hidden\" /> ";
echo "</div> ";
$erro = "1";
}
}

You have to create a javascript function
function mensagem01() {
var title, message, opts, container;
title = $("#freeow-title").val();
message = $("#freeow-message").val();
message = 'E-mail not in database...';
opts = {};
opts.classes = [$("#freeow-style").val()];
opts.prepend = false;
opts.classes.push("error");
opts.autoHide = false;
opts.classes.push("slide");
opts.hideStyle = { opacity: 0, left: "400px" };
opts.showStyle = { opacity: 1, left: 0 };
container = $("#freeow-position").val();
$(container).freeow(title, message, opts);
}
HTML code need to have the freeow definitions
<div id="freeow-tr" class="freeow freeow-top-right"></div>
<div id="freeow-br" class="freeow freeow-bottom-right"></div>
<div class="form-line-check">
<input id="freeow-title" value="Lembrou?" type="hidden" class="text" />
<input id="freeow-error" value="0" type="hidden" />
<input id="freeow-position" value="#freeow-tr" type="hidden" />
<input id="freeow-style" value="smokey" type="hidden" />
<input id="freeow-message" value="message field must be empty" type="hidden" />
</div>
Inside PHP code
You need to include the javascript code to call the javascript function message
echo "<script type=\"text/javascript\"> $(document).write(mensagem01()); </script> \n";
When the php is executed the javascript write the document, which contains the call to the freeow message.

What you are trying to achieve will is best done with AJAX and some more logic than you have in your code.
You want to catch the form submit with jQuery. Using event.prefentDefault() you can stop the form from submitting. Then, you want to AJAX your FormData to the server.
In your PHP script, you do your validation. If it succeeds, return something (for example, a JSON object) that tells your front end that the validation was a success. If not, you want an object that describes what exactly is failing.
From front end, you check to see if the validation was a success (do whatever), or not (show freeow)

Related

Creating a dropdown with a custom input field

I've written the code below as a text input, but ideally I'd like to have a dropdown menu with options for bin/bash, zsh, and custom. If a custom input is chosen, the user should be able to input their login shell as a text input. Any help is welcome!
<?php
echo "<h5>Login Shell</h5>";
echo
"<div class='inline'>
<form action='' method='POST'>
<input type='hidden' name='form_type' value='loginshell'>
<input type='text' name='loginshell' placeholder='Login Shell (ie. /bin/bash)'
value=" . $USER->getLoginShell() . " required>
<input type='submit' value='Set Login Shell'>
</form>
</div>";
?>
Use a <select> element and show/hide the text input when (event change) the value is right.
document.querySelector("#choose").addEventListener('change', function() {
var textarea = document.querySelector("#custom-text");
if (this.value == 'custom') {
textarea.style.display = 'block';
} else {
textarea.style.display = 'none';
}
})
<p>Please select a version
</p>
<select id="choose">
<option>bin/bash</option>
<option>zsh</option>
<option>custom</option>
</select>
<br>
<input id="custom-text" placeholder="type your choice" style="display: none;">

how to send javascript variable as a php parameter

hi i have a javascript function which opens a pop-up window and opens a php file into it but i even want to send a parameter with it but it doesnt work the parameter is sent as a variable name instead of its value
here is my script
<?php
if($addflag == 0){
echo "
<script type=\"text/javascript\">
function mopen(){
var mobj=document.getElementById('dtype').value; //// this variable is shown as a name instead of its value
window.open('quotprin.php?vouchno=' . urlencode($getvouch) . '&dtype=mobj','popUpWindow','height=800,width=950,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes');
}
</script>
";
echo "<td>";
echo '<font color="red">Print On Letter Head</font>
<input type="checkbox" id="dtype" name="dtype" value="1" checked="checked" />';
echo '<input class="cmdprint" type="button" id="submit" name="print" value="Print" onclick="mopen();"></td>';
echo "<td>";
}
?>
This is not exactly your original code, but it works. You have too many escape slashes and single or double quotes. It can be too confusing to figure out errors like this.
<?php
$getvouch = isset($_GET['getvouch'])? $_GET['getvouch'] : null;
?>
<script type="text/javascript">
function mopen(){
var mobj=document.getElementById('dtype').value;
var url="quotprin.php?vouchno=<?php echo $getvouch; ?>&dtype="+ mobj;
window.open(url,'popUpWindow','height=800,width=950,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes');
}
</script>
<table><tr><td>
<font color="red">Print On Letter Head</font>
<input type="checkbox" id="dtype" name="dtype" value="1" checked="checked" />
<input class="cmdprint" type="button" id="submit" name="print" value="Print" onclick="mopen();"></td>
</tr></table>
Most important here is to see how the "getvouch" variable is added to the getmobi url.
If you use this url: add-a-javascript-var-and-send-it-with-post.php?getvouch=6
get mobi links to : quotprin.php?vouchno=6&dtype=mobj
If this is not the issue, please explain a little better.
UPDATE.
Now I see the error is you did not escape the mobj variable in the url. try the changes.
try this:
<?php
if($addflag == 0){
$getvouch = urlencode($getvouch);
echo "
<script type=\"text/javascript\">
function mopen(){
var mobj=document.getElementById('dtype').value; //// this variable is shown as a name instead of its value
window.open('quotprin.php?vouchno= {$getvouch}&dtype=mobj','popUpWindow','height=800,width=950,left=100,top=100,resizable=yes, scrollbars=yes,toolbar=yes,menubar=no,location=no,directories=no, status=yes');
}
</script>
";
echo "<td>";
echo '<font color="red">Print On Letter Head</font>
<input type="checkbox" id="dtype" name="dtype" value="1" checked="checked" />';
echo '<input class="cmdprint" type="button" id="submit" name="print" value="Print" onclick="mopen();"></td>';
echo "<td>";
}
?>

PHP submit form if conditions are met

I'm NOT using javascript has it is disabled in my environment.
Please review the code below.
I'm trying to use PHP to create the logic that Javascript or jQuery would allow me to do with a simple : document.form2.submit()
<div>
<h2>How many services do you need ?</h2>
<form action="<?php $_SERVER['PHP_SELF']?>" method="POST" name="fServ">
<input type="number" name="numServ" />
<input type="submit" value="SEND">
</form>
<div>
<?php
if(isset($_POST['numServ']) && $_POST['numServ']!==""){
echo "We need ".$_POST['numServ']." services";
echo "<form name='form2' id='form2' method='get' action= $_SERVER[PHP_SELF]>";
for($k = 0 ; $k< $_POST['numServ']; $k++){
//echo "<input type=\"text\" value=\"services$k\">";}
echo "<br><input type='text' name='services$k' value=''>";
if(empty($_GET['services'.$k])){
echo "You didn't fill up all the fields. Please put in a service";
}
if (!empty($_GET['services'.$k])){
echo "Form Filled";//
}
}
}
echo "<input type='submit' name='sendForm' value='SEND'/></form>";
if(!isset($_POST['numServ'])){
echo "We don't have any services yet.";
}
else if($_POST['numServ']==""){
echo "Please put in a number";
}
?>
Can this be achievied through PHP ? Where if the conditions are met and the form fields are NOT blank then submit the form, otherwise die and show a message.
Even then you need to submit the details of the form:
Name: <input type="text" name="name" /> (Min 5 Chars)
Age: <input type="text" name="age" /> (Should be a Number)
<input type="submit" />
Now using server-side validation, this can be done this way:
if (isset($_POST["name"], $_POST["age"]))
if (strlen($_POST["name"]) > 5 && is_numeric($_POST["name"]))
die("Error! The conditions are not met!");
die("Form Submitted!");
This way you can submit the form where JavaScript is disabled.
If I understand, you need auto-submit the form without javascript.
Maybe this thread helps you:
How to submit a form on page load without clicking submit button?

placing PHP Variables inside javascript file

As per title.
I have a piece of jQuery that looks like the following
$("<div class='creditCardDetails' id='usercurrentccbox'>
<div class='creditCard'>
<div class='cardChoice'>
<span>Choose Card Type</span>
<input name='cctype' type='radio' value='V' class='lft-field' id='visa' />
<label for='visa'></label>
<input name='cctype' type='radio' value='M' class='lft-field' id='mastercard' />
<label for='mastercard'></label><input name='cctype' type='radio' value='A' class='lft-field' id='amex' />
<label for='amex'></label>
</div>
<!--cardChoice-->
<div class='cardNumber'>
<input name='ccn' id='ccn' type='text' class='long-field' value='<?php echo MaskCreditCard($loggedInfo[ccn]);?>' maxlength='19' readonly />
</div>
<div class='cardCVV'>
<input name='cvv' id='cvv' type='text' maxlength='5' class='small-field' />
</div>
<div class='creditCardName'>
<input name='ccname' id='ccname' type='text' class='long-field' value='<?php echo $loggedInfo[ccname];?>' readonly/>
</div
<div class='cardDate'>
<input name='exp1' id='exp1' type='text' maxlength='2' class='small-field' value='<?php echo $loggedInfo[ccm];?>' readonly /><input name='exp2' id='exp2' type='text' maxlength='4' class='small-field' value='<?php echo $loggedInfo[ccy];?>' readonly />
</div>
</div><!--creditCard-->").insertAfter("#paymentCardChoice");
But as you'll see it has PHP Variables, if I have this embedded into my PHP file this works but I want to keep the PHP file as short as possible and placed this code inside a .js file and of course my variables only display the text of the PHP not the variable its self.
The variables I am trying to call are defined already in a config.php file.
Would I need to use something like this? if so I'm stuck with how I would call the variables in the code above.
$.post('phpfile.php', qString, function (data) {
}, "json");
PHP code will not execute in a .js file. A very simple workaround is to put your JavaScript+PHP code in a .php file; and set the content type header, for example:
<?php
#
# script.js.php
#
header("Content-type: text/javascript");
?>
$("<div><?php echo $foo; ?></div>");
You will find the json_encode function very handy for converting just about any PHP variable (string, number, arrays etc) into valid JavaScript. This function takes care of escaping characters such as ", \, \n etc which could break your JavaScript code. Following example demonstrates how you can pass arbitrary PHP variables to your JavaScript code:
<?php
#
# script.js.php
#
header("Content-type: text/javascript");
?>
var config = <?php echo json_encode(array(
"foo" => "foo",
"bar" => "bar",
"baz" => array(
"baz1",
"baz2"
)
)); ?>;
You can include "PHP-powered JavaScript" file in your PHP page using the <script src> tag:
<script type="text/javascript" src="script.js.php"></script>
If you place it in a separate .js file, it will not work since Javascript is client side and PHP is server side.
Your PHP variable only works now since it is declaired earlier in the page before you insert your javascript, so it is rendered when the page loads.
you can have a PHP file which will include your config.php file
include("config.php");
and then you can have your jquery code within script tags
<script>
// you jquery code with php config variables
</script>
.js
var qString = 'selectedID=' +selectedID;
$.post('/assets/inc/get-logged-info-card.php', qString, function (results) {
$("<div class='creditCardDetails' id='usercurrentccbox'>
<div class='creditCard'>
<div class='cardChoice'>
<span>Choose Card Type</span>
<input name='cctype' type='radio' value='V' class='lft-field' id='visa' />
<label for='visa'></label>
<input name='cctype' type='radio' value='M' class='lft-field' id='mastercard' />
<label for='mastercard'></label><input name='cctype' type='radio' value='A' class='lft-field' id='amex' />
<label for='amex'></label>
</div>
<!--cardChoice-->
<div class='cardNumber'>
<input name='ccn' id='ccn' type='text' class='long-field' value='"+results[0].maskccn+"' maxlength='19' readonly />
</div>
<div class='cardCVV'>
<input name='cvv' id='cvv' type='text' maxlength='5' class='small-field' />
</div>
<div class='creditCardName'>
<input name='ccname' id='ccname' type='text' class='long-field' value='"+results[0].ccname+"' readonly/>
</div
<div class='cardDate'>
<input name='exp1' id='exp1' type='text' maxlength='2' class='small-field' value='"+results[0].ccm+"' readonly /><input name='exp2' id='exp2' type='text' maxlength='4' class='small-field' value='"+results[0].ccy+"' readonly />
</div>
</div><!--creditCard-->").insertAfter("#paymentCardChoice");
}, "json");
.php
<?php
$selectedID = $_POST['selectedID'];
$q = "SELECT * FROM tbl_user WHERE user_id = '$selectedID'";
$sql = mysql_query($q);
$results = array();
while($row = mysql_fetch_array($sql))
{
$results[] = array(
'cct' => $row['user_cct'],
'ccn' => $row['user_ccn'],
'maskccn' => MaskCreditCard($row['user_ccn']),
'ccname' => $row['user_ccname'],
'ccm' => $row['user_date_m'],
'ccy' => $row['user_date_y']
);
}
echo json_encode($results);
?>

The jquery post from a view's form to its PHP controller is not posting

What is to be the value of $id is determined by a php file, 'afile.php', which gets to the view using include('view_file.php'). I want the form in 'view_file.php' to post data back to 'afile.php' and use it to again determine the value of $id.
From the 'view_file.php':
Here is my jquery/javascript:
function vote()
{
$.post('afile.php',{ poll:$('input:radio[name=poll]:checked').val(), id: $('input:hidden[name=id]').val()});
};
Here is my form:
<form name='poll' id='poll'>
<INPUT TYPE="radio" name='poll' value='poll3' checked/>Yes
<INPUT TYPE="radio" name='poll' value='poll2'/>Done
<INPUT TYPE="radio" name='poll' value='poll1'/>No
<INPUT TYPE='button' value='submit' onClick="vote();" />
<INPUT TYPE='hidden' name='id' value='<?php echo $id; ?>'/>
</form>
From the 'afile.php':
if(isset($_POST['poll']))
{
//code
}
else
//code
include('view_file.php');
However, the post is never set, and I just cannot figure out why that is.
Any help/hints/suggestions appreciated.
EDIT:
I realized I can do this easily without incorporating jquery/javascript.
Just use the HTML POST method:
<form name='poll' action='afile.php' method='POST'>
<INPUT TYPE="radio" name='poll' value='poll3' checked/>Yes
<INPUT TYPE="radio" name='poll' value='poll2'/>Done
<INPUT TYPE="radio" name='poll' value='poll1'/>No
<INPUT TYPE='submit' value='submit' />
<INPUT TYPE='hidden' name='id' value='<?php echo $id; ?>'/>
</form>
You could just use $('formSelector').serialize() to get the post data from the form directly, without needing to get the values for each input. Checkboxes and Radios only send POST data if they are :checked.
Now, it doesn't matter what the form's name is, it isn't passed to $_POST, so your condition
if(isset($_POST['poll']))
Will always be false, since there is not input with the name of 'poll'. I generally add a name to the submit button if there are multiple forms submitted to the same page.
EDIT: When testing locally the following code worked flawlessly:
<?php
$id = 1;
if (!empty($_POST)) {
if (!empty($_POST['poll'])) {
echo "POLL IS NOT EMPTY!! \n";
var_dump($_POST);
die();
}
else {
echo "BOO! POLL IS EMPTY! \n";
var_dump($_POST);
die();
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="author" content="Rikudo Sennin" />
<title>Untitled</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function() {
$('#poll').submit(function() {
$this = $(this);
$.post(
"form-get-test.php",
$this.serialize(),
function(data) {
alert(data);
}
)
return false;
});
})
</script>
</head>
<body>
<form name='poll' id='poll'>
<INPUT TYPE="radio" name='poll' value='poll3' checked/>Yes
<INPUT TYPE="radio" name='poll' value='poll2'/>Done
<INPUT TYPE="radio" name='poll' value='poll1'/>No
<INPUT TYPE='button' value='submit' onClick="vote();" />
<INPUT TYPE='hidden' name='id' value='<?php echo $id; ?>'/>
<button type="submit" name="poll_submit">Send</button>
</form>
</body>
</html>

Categories