Know a lot about php but novice at jquery or javascript and I'm trying to update a variable after a form submit.
I have a form that submits to a php page.
<form name="FindUser" id="userform" class="invoform" method="post" action="" />
<div id ="userdiv">
<p>Name (Lastname, firstname):</p>
<input type="text" name="username" id="username" class="inputfield" />
<input type="submit" name="find" id="find" class="find" value="Find" />
</div>
</form>
Which is echoed back via the below method:
<div id="infowrapper">
<div id="usernameinfo" class="info">
<?php
if(isset($_POST['find'])){
include('includes/find.php');
}
?>
</div>
</div>
One of the vars that comes back from the php page is
$hidefields="1"
The problem is although I can see php update the var correctly, jquery does not update with this new value. I've tested with an alert box which still displays the var as 0 while php is echoing it as a 1. I can only assume it's cached or something.
<script>
$(document).ready(function(){
$("#userform").hide();
});
$(document).ready(function(){
var hide = <?php echo $hidefields; ?>;
if(hide == 1){
$("#userform").hide();
$("#infowrapper").show();
$("#passwordreset").show();
$("#enabledisable").show();
}
else {
$("#userform").show();
$("#infowrapper").hide();
$("#passwordreset").hide();
$("#enabledisable").hide();
}
alert(hide);
});
</script>
Is there some simple line I can add to get jq to update with this new var? I'm so close to getting this finished and it's the last obstacle in a steep learning curve. Then I can do some sweet powershell integration ^^.
Thanks.
You can reduce this a bit :
$(document).ready(function(){
$("#userform").hide();
});
$(document).ready(function(){
var hide = <?php echo $hidefields; ?>;
function firstAction(){
$("#userform").hide();
$("#infowrapper,#passwordreset,#enabledisable").show();
}
function secondAction(){
$("#userform").show();
$("#infowrapper,#passwordreset,#enabledisable").hide();
}
hide == 1 ? firstAction() : secondAction();
alert(hide);
});
Related
Hi iam learning jquery with php. I created very small php and jquery code to getting value but it's not working. I check console but not giving any information i have referred jquery api documentation same process i followed but no use. How can i solve this.
<script>
$(document).ready(function(){
$("#submit").click(function(){
var term= $("#sterm").val();
$.post('oopsdata.php', {nwterm: term}, function(data){
("#container").html(data);
});
});
});
</script>
<body>
<form class="" action="" method="post">
<input type="text" name="" value="" id="sterm">
<input type="submit" name="" value="Search term" id="submit">
</form>
<div id="container">olddata</div>
PHP Code
<?php
$newterm = $_POST['nwterm'];
if($newterm == 'bio'){
echo "Request received This is the new data"
} else {
echo "no data received;"
}
?>
There are few issues with your code, such as:
You need to prevent your form from being submitted in the first place. Use jQuery's .preventDefault()
Missing $ before ("#container").html(data);
Based on the above two points, your jQuery code should be like this:
$(document).ready(function(){
$("#submit").click(function(event){
event.preventDefault();
var term= $("#sterm").val();
$.post('oopsdata.php', {nwterm: term}, function(data){
$("#container").html(data);
});
});
});
There are two syntax errors in your PHP code. Missing ; in both your echo statements.
So based on the above point, your PHP code should be like this:
<?php
$newterm = $_POST['nwterm'];
if($newterm == 'bio'){
echo "Request recieved This is the new data";
}else{
echo "no data recieved";
}
?>
Updated: It still not work after I add "#".
I am new to ajax. I am practicing to send value to php script ,and get result back.
Right now, I met one issue which I can not show my result in my html page.
I tried serves answers online, but I still can not fix this issue.
My index.html take value from the form and send form information to getResult.php.
My getResult.php will do calculation and echo result.
How do I display result into index.html?
Hers is html code
index.html
<html>
<body>
<form name="simIntCal" id="simIntCal" method="post"
>
<p id="Amount" >Amount(USD)</p>
<input id="amount_value" type="text" name="amount_value">
<p id="annual_rate" >Annual Rate of Interest
(%)</p>
<input id="rate_value" type="text" name="rate_value">
<p id="time_years" >Time (years)</p>
<input id="time_value" type="text" name="time">
<input id="calculate" type="submit" value="Calculate">
</form>
<p id="amount_inteCal" >The Amount (Acount
+ Interest) is</p>
<input id="result" type="text">
</body>
</html>
ajax script :
<script>
$('#simIntCal').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'getResult.php',
data: $('#simIntCal').serialize(),
success: function (result) {
$("#result").text(result);// display result from getResult.php
alert('success');
}
});
});
</script>
getResult.php
<?php
if ($_SERVER ["REQUEST_METHOD"] == "POST") {
//do some calculation
$result=10;//set result to 10 for testing
echo $result;
}
?>
You are missing the '#' in front of your css selector for result.
$("result").text(result);// display result from cal.php
Should be
$("#result").text(result);// display result from cal.php
index.php
----php start---------
if(isset($_POST['name'])){
echo 'Thank you, '.$_POST['name']; exit();
}
----php end ---------
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function test(){
var formDATA = {'name': $('#input_name').val()}
$.ajax({
type: 'POST',
url: 'index.php',
data: formDATA,
success: function(response){
$('#result').html();
}
});
}
</script>
<input id="input_name" type="text" value="">
<button onclick="test();">Test Ajax</button>
<div id="result"></div>
Try something simple, this is a very basic version of ajax and php all in one page. Since the button triggers the function you don't even need a form (doesn't mean you shouldn't use one). But i left it simple so you could follow everything.
Sorry when i added php open and closing tags it didn't show up as code.
Also don't forget to include your jquery resources.
In your html file where you want the result to display, you probably want to be using a div.
Currently your code is using an input field:
<input id="result" type="text">
And what you probably want is something like this:
<div id="result"></div>
Unless you were intending to have the result show up in an input field inside your form, and in that case, the input field isn't actually inside your form code.
I'm trying to create a search feature that searches a database based on the criteria a user has entered. Right now, I'm just trying to get the jQuery variable data into PHP. I've decided to use the shorthand AJAX $.post method because this is just a demo project. I know there are numerous similar questions like mine, but I have yet to find an answer to any of them that I can use.
So what I'm trying to do is, the user will click on a drop down menu and select an option. AJAX then sends the selected value to the PHP file and the PHP will eventually perform a database search based on what was selected. The issue is, in PHP, I'm getting a string of "Search" when the data is parsed and I echo it but when I do a console log on the variable that was sent, I'm getting the correct text. Can anyone tell me where I'm going wrong?
Here's what I have so far.
AJAX
$("#search_form").on("submit", function(ev){
ev.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
console.log(data);
})
})
PHP
ob_start();
require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo $criteria;
HTML
<form id="search_form" method="post">
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search" id="search" />
<input type="submit" class="button" value="Search_Now" />
</fieldset>
As Requested
Here is a fiddle of the drop down menu to show how it works.
http://jsfiddle.net/xvmxc0zo/
Your form is being submitted via default form submission; the ajax call is misplaced, it should be within the submit handler, which should prevent default form submission.
Note that I have removed both name and id attributes from the submit button; you do not need them. Just let the submit button do it's job and listen for the submit event on the form where you would then use event.preventDefault(); to make sure the form does not submit, then you can make your ajax call.
$("#searchBy").on("click", ".option", function(){
$('#search').val( $(this).text() );
});
$('form').on('submit', function(e) {
e.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
//jsonData = window.JSON.parse(data);
console.log( data);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="hidden" name="search" id="search" />
<input type="text" name="search_text" id="search_text" />
<input type="submit" class="button" value="Search" />
</fieldset>
</form>
In your PHP use echo $criteria; instead of echo json_encode($criteria);.
I'd suggest to use the way of jQuery documentation to check changes in your drop down.
$( "select" ).change(function () {
$( "select option:selected" ).each(function() {
$.post("../php/test.php", {search: $(this).text()}, function(data){
jsonData = window.JSON.parse(data);
});
});
})
You are getting "Search" on the PHP side because that is the value of your submit button.
You want the post to occur when you click on an option? Try adjusting your selector as follows:
$("#searchBy .option").on("click", function () {
var search = $(this).text().trim();
$.post("../php/test.php", { search: search }, function (data) {
jsonData = window.JSON.parse(data);
})
});
I think your header.php is provoking the error. I created a test file myself with your code and that works perfectly fine:
<?php
if($_POST)
{
ob_start();
//require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo json_encode($criteria);
exit;
}
?>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search_text" id="search_text" />
<input type="submit" name="search" id="search" class="button" value="Search" />
</fieldset>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$("#searchBy").on("click", ".option", function(){
var search = $(this).text();
$.post("<?=$_SERVER['PHP_SELF']?>", {search: search}, function(data){
jsonData = window.JSON.parse(data);
console.log(jsonData); //Prints the correct string
})
});
</script>
<form method="POST">
<div id="showme">Show me <?php echo $_POST['name']?></div>
Send the value<input type="radio" name="name" value="ja"/>
<input type="submit" id="submit" name="submit" value="BEREKENEN! ">
</form>
<script>
$(document).ready(function () {
$('#showme').hide();
$('#submit').click(function(e) {
e.preventDefault();
$('#showme').fadeIn(5000);
});
});
</script>
This code won't send the value of the radiobutton to the showme div.
I can't receive the $_POST['name'] when I use hide() and fadeIn() between the <script> tags.
Whenever I don't use jQuery it sends the data - when using it , it won't let me send the value.
How do I fix this problem, this is just an example of 1 radio button. I have a list of 6 radiobuttons that need to be sent to PHP section in the same file, I don't want to make another file for this.
This code will FadeIn the requested div, it shows me Show me but it won't show the value where I ask for with the line <?php echo $_POST['name']?>
PHP is parsed on the server. <?php echo $_POST['name']?> has already been evaluated and echod to the page long before any of the submission stuff happens. What you need is to use AJAX.
You can replace the submit button with just a regular button, remove the <form> element entirely even.
jQuery:
$('#submit').on('click', function(evt) {
var e = evt || window.event;
e.preventDefault();
$.post('page.php', { name: $('input[name="name"]').val() }, function ( data ) {
$('#showme').append(data).fadeIn(5000);
});
return false;
});
(if you do what I did below turning submit into button, you dont need the e.preventDefault())
PHP:
if(isset($_POST['name'])) {
echo $_POST['name'];
return;
}
HTML:
<div id="showme">Show me </div>
<label for="name">Send the value</label><input type="radio" name="name" value="ja"/>
<input type="button" id="submit" name="submit" value="BEREKENEN!">
I'm not so sure you can get a non-BOOLEAN value from a radio button with PHP though. You're probably better off using <input type="hidden" value="ja" /> or maybe type="text".
Here's my JS code...
function da(){
var a=document.forms["user"]["age"].value;
if(this.age.value < 18 || this.age.value > 85) {
alert('some text...');
this.age.focus();
return false;
}else{
window.location.href='file.php?&'+a;
}
}
It simply passes the parameters to the page where I'm standing...
Here's the form just in case (I'm a beginner keep in mind)...
<form name="buscar" method="GET"> Some text <input onmouseover="Aj2('d');document.getElementById('box').style.display='block';" onmouseout="clean();" type="number" name="age" id="age" > Age <div id="help" ><!-- --> </div><br />
<input type="button" value="Send" onclick="da()">
</form>
The Aj2 function is not the problem here...
Thanks for any help y might get...
Just a thought, if you don't actually have to reload the page and just want to get information to your javascript code from PHP, you could do something like
<script>
<?
$phpvariable = "my variable";
?>
var jsvariable = <?php echo json_encode($phpvariable); ?>;
</script>
Now the javascript variable, jsvariable, will hold the PHP variable's content.
Some thing like this I am not a expert.
$('button name').on('click', function() {
var age_ = document.getElemenetById('age');
$.get('path of your file', {'age' : age_}, function(resp) {
// code to pass parameter
alert(age_);
});
});