jQuery find() vs. filter() with PHP - javascript

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.

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();});}

Run a JavaScript function from a php if statement

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);
}
});

checking isset at bottom of page not working

I have a dilemma (which I am yet to find a way around). For some reason, PHP doesn't want to check if $_POST["login"] at the bottom of the <body> tag within my document.
It will work if it is put at the very top of the document, or even the top of the <body> tag. However, if I put it at the top of the document / <body> tag, the output JavaScript will not execute!
For example, this is the document (where the PHP will not execute):
<form>
<span id="example-element">Displaying.</span>
<input type="text" name="example">
<button type="submit" name="login">Login</button>
</form>
<?php
if(isset($_POST["login"])){
echo "
<script>
document.getElementById('example-element').style.display = 'block';
</script>"
}
?>
If I am to do something like this, however (the PHP will execute):
<?php
if(isset($_POST["login"])){
echo "
<script>
document.getElementById('example-element').style.display = 'block';
</script>"
}
?>
<form>
<span id="example-element">Displaying.</span>
<input type="text" name="example">
<button type="submit" name="login">Login</button>
</form>
But due to how JavaScript compiles, it will throw an error saying how it cannot set a style on a null element.
I have no idea how to get around this dilemma, so all help is appreciated!
Cheers.
<form>
<span id="example-element">Displaying.</span>
<input type="text" name="example">
<button type="submit" name="login">Login</button>
</form>
<?php
if(isset($_GET["login"])){
echo "<script>
document.addEventListener('DOMContentLoaded', function(){
document.getElementById('example-element').style.display = 'block';
}, false);
</script>";
}
?>
Check if this works..... I've added the display code inside the DOMContentLoaded event and change the $_POST variable to $_GET. Works fine in my local system.
You can do it as follows
<style>
.someClass {
display: block;
}
</style>
<?php
if(isset($_POST["login"])){
$hasClass = true;
}
?>
<form method="post">
<span id="example-element" class=<?php if(isset($hasClass)==true) echo "someClass"; ?> >Displaying.</span>
<input type="text" name="example">
<button type="submit" name="login">Login</button>
</form>
The other problem with your code is that you are not setting method of your form and by default it is GET where as in php you were looking for POST request.
You could solve it either by using $_REQUEST in php when you are not sure about the method.
Actally php executes before javascript.
Change like this
<script>
var isSubmit = "<?php isset($_POST['login'])?true:false; ?>";
if(isSubmit){
document.getElementById('example-element').style.display = 'block';
}
</script>"

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.
}
});
})
})

passing javascript throught textarea inside a form

I would like to ask a question.
Is there a way to pass jquery script over textarea and being accepted by php with $_POST function?
just like w3schools did, I've tried but the jquery script are missing and I don't know why..
Please somebody help me. Thank you!
<form action="showHTML.php" method="post" >
<textarea name="html" id="hello">
<script src="lib/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("body").css({backgroundColor:"red"});
});
</script>
</textarea>
<form>
And this is my php file that i used to grab the content from the $_POST
<?php
if(isset($_POST['html']) and !empty($_POST['html'])){
$data = htmlentities($_POST['html']);
}else{
echo '<p>Edit the HTML to the right.</p>';
}
echo html_entity_decode($data);
?>
<script src="lib/jquery.min.js"></script>
<form action="showHTML.php" method="post" >
<textarea name="html" id="hello">
$(document).ready(function(){
$("body").css({backgroundColor:"red"});
});
</textarea>
<form>
Now get the script as text from showHTML.php and process it from there. I guess you can't put script tag inside text area like what you have done.
your code should look like this: close your form tag and add a button to submit.
<script>
$(document).ready(function(){
$("body").css({backgroundColor:"red"});
});
</script>
<form action="showHTML.php" method="post" >
<textarea name="html" id="hello">
</textarea>
<input type="submit" value="submit"/>
</form>
----^
php:
<?php
if(isset($_POST['html']) and !empty($_POST['html'])){
$data = htmlentities($_POST['html']);
}else{
echo '<p>Edit the HTML to the right.</p>';
}
echo html_entity_decode($data);
?>

Categories

Resources