Display PHP on HTML with AJAX - javascript

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

Related

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

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.

How can I open a URL inside a DIV tag using AJAX?

I have the following php files. One that captures a user's text from a simple form, and the other echos this text. The files are shown below..
file1.php:
<form action="output.php" method="post">
Paste text document: <br><br>
<textarea name="doc" rows="5" cols="50" value="">
</textarea><br><br>
<input type="submit" name="submit" value="submit">
<input type="reset" name="reset" value="Clear">
</form>
<br><br>
<div id="output_area">
</div>
</body>
</html>
output.php:
<html lang="en">
<head><title>Output</title></head>
<body>
<?php
$doc = $_POST['doc'];
echo $doc;
?>
</body>
</html>
I want the output to be displayed between the DIV tags, rather than to load and show the output on a new page. I want the text to be output in between the DIV tags on the same page. Maybe the best way is to use AJAX to display output.php within the DIV tags and output the text after the user has clicked on the "submit" button. How can I use AJAX to do this in the most basic way possible?
You can use JQuery ajax function:
JQuery:
$("form").on("submit", function(event){
event.preventDefault();
$.ajax({
type: "POST",
url: "output.php",
data: { doc: $('#doc').val()}
})
.done(function( data) {
$("#output_area").html(data);
});
});
Change html:
<textarea name="doc" id="doc" rows="5" cols="50" value=""></textarea>
You can use the function:
$(document).ready(function() {
$( "#output_area" ).load( "output.php" );
});
But remeber!
That the load function from jquery, loads everything on the page you are asking for, so dont use:
<html lang="en">
<head><title>Output</title></head>
<body>
</body>
</html>
Now the load(function), will put in the PHP you made in output.php
if you want to output the answer on a submit i would do it like:
First add:
Show doc
Then add jquery:
$(document).ready(function() {
$('.pressme').on('click', function(){
var yourdata = $(this).parent().find("textarea[name='doc']").val();
$.ajax({
type: "POST",
url: "output.php",
data: {doc: yourdata},
success: function(data) {
$('#output_area').html(data);
});
});
});
I added a <a>, instead of using the <input type="submit"> because the submit, will post the form, thats not what you need, after what i understand, you need to preview the textarea in a div.
Hope it helps!
If you want your $_POST variable to be shown on the same page, then
1.change form's action to it. In your case
action="file1.php" or leave it empty to reload the page on submit (not valid in HTML5)
2.insert echo part directly in your div
<div id="output_area">
<?php
echo $_POST['doc'];
?>
</div>
not in another file
You need not use ajax for this. You can do this by using javascript. It will improve your performance of your code.
Try This:
<script>
function show() {
document.getElementById("output_area").innerHTML=document.getElementById("doc").value;
return false;
}
</script>
<form action="#" method="post">
<textarea name="doc" id="doc" rows="5" cols="50" value="">
</textarea>
<input type="submit" name="submit" value="submit" onclick="return show();">
<input type="reset" name="reset" value="Clear">
</form>
<div id="output_area"></div>
</body>
</html>

Is there a way to send data from html tags to php?

I am trying to alter the functionality of submit button for some reasons. If have called a JS function which is called by clicking submit button but i have no idea how can i manually send my data from html tags to php variables. Below is the short description of code.
<html>
<body>
<input class="inputtext" id="email" name="email" type="text"></div>
<input value="Submit" name="v4l" id="login" class="inputsubmit" type="button" onclick="myFunction();return false">
<script>
function myFunction() {
var TestVar =document.getElementById("email").value;
document.write(TestVar);
//store data of testvar to php
}
</script>
<html>
<body>
I know it can be done by form but i need it this way.
Using a PHP form would be a really simple solution: http://www.w3schools.com/php/php_forms.asp
You could pretty much post it strait to the PHP page.
I hope you are comfortable with jQuery.
Try
$("#login").click(function(){
var email= $("#email").val();
jQuery.post(
"*your parsing url*",
{email:email},
function(data){
// Data returned from the ajax call
}
)
});
The jQuery library makes this, and many other tasks, very simple:
<html><head></head><body>
<form id="myForm">
<input class="inputtext" id="email" name="email" type="text"></div>
<input value="Submit" name="v4l" id="login" class="inputsubmit" type="button" onclick="myFunction();return false">
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function myFunction() {
jQuery.ajax({
url: 'yourcode.php',
type: 'POST',
data: jQuery('#myForm').serialize(),
success: function(response) {
alert('The data was sent, and the server said '+response);
}
});
}
</script>
</body></html>
See http://api.jquery.com/jquery.ajax/ for more information.

Displaying the content of a DIV on submit

I have a HTML form. On submission the form POST values to page.php. The view then navigates to page.php and displays a success message. I want to prevent the user from navigating to page.php, and display <div id="first">
In other words, what i want to do is a reset. (Displaying <div id="first"> after user clicks the Done button)
<form action="page.php" method="post">
<div id="first" class="m span3">
THIS DIV CONTAINS FEW TEXT BOXES
</div>
<div id="second" class="m2 span3">
THIS DIV CONTAINS FEW TEXT BOXES AND COMBOBOXES
</div>
<div id="last" class="m3 span3">
THIS DIV CONTAINS FEW TEXT BOXES
</div>
</form>
Once the user clicks the DOne button the following function gets fired
function onComplete() {
$('form').submit();
alert("clicked");
}
if you want to post data to main.php without redirecting the page I recommend you to use Ajax. this is a simple code but can give you an idea to build your application :
<html>
<head>
<script type="javascript" src="jquery.js"></script>
<script type="text/javascript">
function complete() {
$.ajax({
type : "post",
data : "text="+$("#"+textbox_1).value,
url : "page.php",
success : function(response){
alert("Done!");
}
});
}
</script>
</head>
<body>
<form action="page.php" method="post">
<input type="text" id="textbox_1">
<button onclick="complete()">submit</button>
</form>
</body>
</html>
and use $_POST['text'] in page.php
$('form').submit(function (e) {
e.preventDefault();
$('first').show();
}
Try something like this.
you can ad a value to the url and use that one value to call the div.
eg:
<form action="page.php?action=formSent" method="post">
// form data
</form>
then use some php to get the action call and use it to show the div:
<?php
if(isset($_GET['action']) && $_GET['action'] == "formSent" ){
<div id="first">
div content
</div>
}
?>
you can place the php code above of the form

Categories

Resources