Run a JavaScript function from a php if statement - javascript

I would like to create a php IF statement so If it receives the key "test" by POST, <h2> hello </ h2> should be output, otherwise <span> error </ span>
How can I make that?
<div id="rre">
<h2 class="desktop">Hamburg,a major port city in northern Germany.</h2>
<h2 class="mobil">Berlin,is the capital and the largest city of Germany.</h2>
</div>
<form action="viereck.html" method="POST">
<input type="text" name="check"?>
<input type="button" value="Klick" onclick="klick();" />
</form>
<script type="text/javascript">
function klick() {
jQuery('#rre').html('<h1>Hallo</h1>');
}
</script>

The response that you return needs to be inside script tags like:
echo '<script type="text/javascript">alert();</script>';

Why you don't do that with jquery: Try smth like this
<script type="text/javascript">
function klick() {
if($("#text").val() == 'test'){
jQuery('#rre').html("<h1>Hello there!</h1>");
}else{
jQuery('#rre').html("Error");
}
}
</script>
Html
<div id="rre">
<h2 class="desktop">Hamburg,a major port city in northern Germany.</h2>
<h2 class="mobil">Berlin,is the capital and the largest city of Germany.</h2>
</div>
<form action="viereck.html" method="POST">
<input type="text" name="check"? id="text">
<input type="button" value="Klick" onclick="klick();" />
</form>
JSFIDDLE

If the page you're posting to is viereck.html, you're going to be unable to use PHP on it.
If you can change the file to viereck.php, you can POST to it like you're doing, with action="viereck.php" method="POST" Then, at the top of your page, check for POST values in PHP like:
<?php
if(isset($_POST['check'])){
$check = '<span>error</span>';
if($_POST['check'] == 'test'){
$check = '<h1>Hallo</h1>';
}
}
?>
And if your jQuery is on the same page, you can insert the PHP like:
<script type="text/javascript">
function klick() {
jQuery('#rre').html(<?= $check; ?>);
}
</script>
Doing it this way though can lead to some serious headaches as your project grows, I wouldn't recommend it. Why not look into using AJAX? You can submit a form and return a message indicating success or failure, as well as why. You can then create your HTML in jQuery instead of a PHP string like:
// On form submit
$.ajax({
url: "viereck.php",
type: 'POST',
success: function(result){
var msg = $('<h1>').text('Hallo');
$('#rre').html(msg);
},
error: function(result){
var msg = $('<span>').text('Error');
$('#rre').html(msg);
}
});

Related

Display PHP on HTML with AJAX

I was recently doing a PHP web-app, which turns out needs AJAX to display temporary and permanent results without reloading the page or redirecting to another page. Just simply update.
So I have a form on my index, where it collects search terms:
<form action="search.php" method="post">
<label for="fname" id="label">Enter search terms:</label>
<br>
<input type="text" id="fname" name="search"><br>
<input type="submit" id="submit">
Then I have it take it to my PHP script, which then processes the search terms and in theory should display them on the same page just in the other paragraph with something like this which is permanent:
echo 'Selected search terms: '. $terms. ".<br>
Search terms found: ".$termc."." ;
While my PHP script is working, I display a permanent "Loading..." and when it finishes it should display "Done." replacing the "Loading..." text.
Would anyone know how I could implement this with AJAX? How could I talk to PHP?
use the below code to help display data with out refresh the page.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>New User Registration</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
<div id="newUserHld">
<form name="serarch_frm" method="post" id="serarch_frm">
<label for="fname" id="label">Enter search terms:</label>
<br>
<input type="text" id="fname" name="search"><br>
<input type="submit" id="submit" onclick="formSubmit(); return false;" >
</form>
</div>
<div id="success">
</div>
</body>
<script>
function formSubmit(){
$.ajax({
type:'POST',
url:'search.php',
data:$('#serarch_frm').serialize(),
success:function(response){
$('#success').html(response);
}
});
return false;
}
</script>
</html>
create the search.php file and put this code.
<?php
echo 'Selected search terms:'.$_POST['search'];
exit;
?>
you need to write js code something like this
(function($){
$(document).ready(function(){
$("form").submit(function(e){
$( ".result" ).html( "Loading.." );
e.preventDefault();
// ajax call to your php file
$.post( "file.php", function( data ) {
$( ".result" ).html( data );
});
});
});
})(jQuery);
Please follow below step.
1) You can put form tag like this <form onsubmit="submitFormData()">
2) Create javascript function.
3) function submitFormData(){ var form_data ='search='+$('#fname').val();$("#loading").show(); $.ajax({url: "yourphpfile.php",type: "POST",data: form_data,success: function (res){$("#loading").hide();});}

jQuery find() vs. filter() with PHP

I tried to refresh content on a div only when a user submits a form. The page is .php, and the action= is on the same page. Here is what I tried:
<?php
session_start();
if($_SERVER['REQUEST_METHOD'] == "POST")
{
if($_POST['user'] === 'mysecret' && $_POST['pass'] === 'page')
$_SESSION['auth'] = true;
}
if(isset($_SESSION['auth']))
{
?>
<html>
<body>
<div id="anothercontainer"> </div>
<div id="container">
<p id="mycontent"> Here is my new content </p> </div>
</body>
</html>
<?php
exit();
}
?>
<html>
<body>
<form id="changing" action="test3.php" method="POST">
User:
<input type="text" name="user" />
Pass:
<input type="password" name="pass" />
<input type="submit" value="Send" />
</form>
<div id="content"> Here is the content to be updated </div>
<script src="scripts/jquery-3.2.0.js"></script>
<script>
$('#changing').on('submit', function(e) {
e.preventDefault();
var $content = $('#content');
var details = $('#changing').serialize();
$.post('test3.php', details, function(data) {
$content.html( $(data).find('#container') );
});
});
</script>
</body>
</html>
It should refresh content on #content div. However, it does nothing. But if I use .filter() instead of .find(), it works fine.
My question is... why this doesn't work? It has something to do with the PHP or something like this?
I read from Jon Duckett's book... he used .find() and it worked. The only difference I saw was it's a .html page instead of .php. The code is like this (ajax request):
success: function(data) { // Show content
$content.html( $(data).find('#container') ).hide().fadeIn(400);
},
(the full .js code is here: http://javascriptbook.com/code/c08/js/jq-ajax.js).
Could somebody help me? Because I'm really confused. Thank you.

Get value from input text in php without pressing Enter

Hay I'm new to php and I have made php code like this :
<?php
session_start();
echo 'Hellow Hisoka';
?>
<form name="form" method="post">
<div class="col-sm-3">
<label class:>Nama :</label>
</div>
<div class="col-sm-9">
<input type="text" name="nama_tamu" id='nama_tamu' class="form-control" placeholder="Nama Lengkap">
<?php
$myValue = $_POST['nama_tamu'];
?>
</div>
<br/><br/>
<?php
echo $myValue;
?>
</form>
When I want to show the echo message, I need to hit enter on my keyboard first in order to get the value of $_POST['nama_tamu'];. My question is can I get the value of nama_tamu input without pressing enter, or maybe without using POST or GET and then assign it to $myvalue?
You will need to use Javascript. You can use the Jquery events :
<script>
$( "#nama_tamu" ).keyup(function() {
alert( $this.val() );// alerting the value of the input field
});
</script>
Web development is all about communication. In this case, communication between two (2) parties, over the HTTP protocol:
The Server - This party is responsible for serving pages.
The Client - This party requests pages from the Server, and displays them to the user. In most cases, the client is a web browser.
Each side's programming, refers to code which runs at the specific machine, the server's or the client's.
You cannot get values without submitting for the user has not entered any yet. PHP is a server side language. To get values before submit and do certain actions with them you will need javascript (a client side programming language).
The simplest method to get a value is using the getElementById().
var something = document.getElementById('someid');
<input type="text" name="something" id="someid">
You can also use jQuery:
var something = $('#someid').val();
Conclusion
The simple answer to your question is: This is not possible.
Why not? I hear you asking. Because PHP doesn't know the values of your form before you send the form to your webserver.
Use keyup().
function check(id)
{
document.getElementById("result").innerHTML = id;
}
<input type="text" name="test" id="test" onkeyup="check(this.value);">
Your value: <span id="result"> </span>
$(document).ready(function() {
$("#check").keyup(function(){
alert($(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="check" >
For this purpose you should use .keyup function/event. Following are the snippet :
$(document).ready(function () {
$("#nama_tamu").keyup(function(){
$("#enterdata").html($("#nama_tamu").val());
$.ajax({
type: 'POST',
url: "getdata.php",
data: "nama_tamu="+$("#nama_tamu").val(),
success: function(res)
{
$("#outputdata").html(res);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
session_start();
echo 'Hellow Hisoka';
?>
<form name="form" method="post">
<div class="col-sm-3">
<label class:>Nama :</label>
</div>
<div class="col-sm-9">
<input type="text" name="nama_tamu" id='nama_tamu' class="form-control" placeholder="Nama Lengkap">
<?php
$myValue = $_POST['nama_tamu'];
?>
<br> You press following character:<div id="enterdata"> </div>
</div>
<br/><br/>
<div id="outputdata"></div>
<?php
echo $myValue;
?>
</form>
Also create one file for the required output.
Now in getdata.php file
echo $nama_tamu=$_POST['nama_tamu'];

Trying to get returned Ajax string to remain constant and not disappear when page is changed

as you can see in the code, I have a form which gets displayed by clicking on the "Edit" word. Then the user inputs his profile, which on submit, via Ajax, gets processed by a PHP script I have that saves it in SQL. Once saved, the form disappears and -theoretically- I would want the new profile to be copied back in there.
My question is: how do I get the to be fixed there, once I chance page? The SQL Update and .ajax work perfectly, but when I change page and go back here, I lose what's inside the div and the user won't be able to see his newly saved profile link.
As you can see, I have a session variable with the profile in the code which I print so that when user gain's first access to his account, he sees his profile. Unfortunately, this remains after he's saved the new profile.
I'd be really glad if you could help, it's been days now I've tried to get my head around this. Thank you very much!
<?php
session_start();
$email = $_SESSION['email'];
?>
<html>
<style>
#form1{display:none;}
</style>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">
$("document").ready(function(){
$(".js-ajax-php-json").submit(function(){
var data = {"action": "test"};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "tryoutwo.php",
data: data,
success: function(data) {
$(".the-return").html(data["profile"]);
}
});
return false;
});
});
</script>
</head>
<body>
<div class="container">
<table>
<tr>
<td><p><b>My Facebook profile:</b></td>
<td>
<div class="the-return"></div>
<p id="editprofile"><? php print($profile); ?>
<form action="return.php" onsubmit="hideform()" class="js-ajax-php-json" method="post" id="form1">
<input type="text" name="profile" value=""/>
<input type="submit" name="submit" value="Submit form">
</form>
</p>
</td>
<td><p onclick="return showform()"><a href>Edit</a></p></td>
</tr>
</table>
</div>
<script>
function showform() {
document.getElementById("form1").style.display = 'block';
document.getElementById("editprofile").innerHTML = "";
return false;
}
function hideform() {
document.getElementById("form1").style.display = 'none';
return false;
}
</script>
</body>
</html>
This is what you should do:
<?php
session_start();
if( isset( $_POST['profile'] ) )
$_SESSION['profile'] = $_POST['profile'];
?>
and the html
<p id="editprofile">
<?php
if( isset( $_SESSION['profile'] ) )
echo $_SESSION['profile']; ?>
</p>

Refreshing div with AJAX

Index.php
...
<form id="calculator_form" name="form" action="" method="get" >
<input name="one" type="text">
<input name="two" type="text">
<input type="submit">
</form>
...
<!-- refresh area -->
<?php if(isset($_GET["one"])) { ?>
<div>
<?php echo $_GET["one"] . " " . $_GET["two"]; ?>
</div>
<?php } ?>
<------------------->
I would like to submit the form and reload the refresh area indicated above. I know this can be achieved by using AJAX but I'm not quite sure how.
I have tried putting the refresh area in a separate ajax.php file and using JQuery but it didn't work;
$(document).ready(function() {
$("#calculator_form").submit(function(event) {
event.preventDefault();
$("#divtoappend").load("ajax.php", data);
})
})
I've also tried using $.get() but to no avail.
I'm able to send the data back and forth to a seperate php page but I'm stuck trying to achieve what I am looking for.
EDIT:
The code that I posted was quickly written and the syntax isn't the issue in question, I'm merely wondering how I can refresh a <div> under the form so that it will once again do the if(isset($_GET["one"])) check and print the updated php variables.
EDIT 2:
My code is now as follows:
Index.php
...
<form id="calculator_form" name="form" action="" method="get" >
<input name="one" type="text">
<input name="two" type="text">
<input type="submit">
</form>
...
<div id="append">
<!-- where I want the ajax response to show -->
</div>
...
ajax.php
<?php if(isset($_GET["one"])) { ?>
<div>
<?php echo $_GET["one"] . " " . 4_GET["two"]; ?>
</div>
<!-- assume there's n number of divs -->
<?php } ?>
Now I want the ajax.php div to append to the #append div in index.php. There has to be a better way than altering the ajax.php and using echo:
ajax.php (with echo)
<?php
if(isset($_GET["one"])) {
echo "<div>". $_GET["one"] . " " . $_GET["two"] . "</div>";
}
?>
So, as ajax.php could be very large, is there a better solution than
just echoing data from ajax.php to index.php?
Now this can be done in many ways.. One of them is Following.. Try this:
Index.php file
<form method="get" id="calculator_form">
<input name="one" type="text" id="one">
<input name="two" type="text" id="two">
<input type="submit" name="submit">
</form>
<div class="result"></div>
<script type="text/javascript">
$(document).ready(function(){
$("#calculator_form").on('submit', function(event){
event.preventDefault();
var one = $('#one').val(); // Taking value of input one
var two = $('#two').val(); // Taking value of input two
$.get( "ajax.php", { one:one, two:two }). done( function( data ) {
$('.result').html(data); // Printing result into result class div
});
});
});
</script>
ajax.php
<?php if(isset($_GET["one"])) { ?>
<div>
<?php echo $_GET["one"] . " " . $_GET["two"]; ?>
</div>
<?php } ?>
Use this,
$(document).ready(function() {
$(document).on('submit',"#calculator_form",function(event) {
event.preventDefault();
$.get(
'ajax.php',
function(ret_data){
$("#divtoappend").html(ret_data);
}
);
});
}) ;
The original syntax for $.get is,
$.get(
URL,
{
VAR_NAME1:VAL1,
VAR_NAME2:VAL2
},
function(response){
// your action after ajax complete
}
);
Typo: You have accidentally used $(document).read( instead of $(document).ready(! That will stop your code running.
Note: jQuery has a handy shortcut for the document ready handler:
$(function(){
// your code here
});
I'm not sure if I understand the question correctly, but here is what you can do: Assign some ID or at least the css Class name to the target div and paint the stuff you are getting from AJAX response something like below.
$(document).ready(function() {
$("#calculator_form").submit(function(event) {
event.preventDefault();
$.ajax({
url: "Ajax_URL",
success: function(result) {
$("#targetDiv").html(result.one + " " + result.two); //assuming you have assigned ID to the target div.
}
});
})
})

Categories

Resources