Pass Java Script var to PHP $var - javascript

How can I pass my javascript variables to my PHP scripts, without reloading webpage or using separated PHP script through AJAX or javascript itself?

Without reloading your browser you can use javascript
put this before the <body> tag
<script>
$(document).ready(function(){
$("#varbtn").click(function(){
var var1 = $("#var").val();
$.ajax({
method: "POST",
url: "post.php",
data: {
var:var1
},
success: function(data){
//#success will be the id of the div you want to put the response of the php file
$("#success").html(data);
}
});
});
});
</script>
in the form, you dont need to create <form> tag
<input type="text id="var" />
<button id="varbtn"> Submit</button>
<!--this div will be the result of the post.php file-->
<div id="success"></div>
in the post.php
//will check if the person will direct visit that post.php, this is not secured enough but hes doing his job actually
<?php
if(isset($_SERVER['HTTP_REFERER'])){
if(!isset($_POST['var'])){
//your codes here
}
}
?>

Related

Submitting a form for use with php inside content loaded with AJAX

I've been search for a solution to this for a while and haven't been able to find one.
My company has quite a few webtools that we use for our jobs and I have been tasked with combining them all into a dashboard page. One of my coworkers started this project but never finished it before he left, so now I have to figure it out and there are quite a few problems.
The dashboard page is composed of a couple of sidebars, plus a "main" element. The sidebar includes a bunch of links that when clicked load specific php pages into the "main" via a call to jQuery AJAX. Here's a simplified example:
<html>
<head>
<script>
$(function() {
$("#pageToLoad").click(function() {
$.ajax({
url: "some_directory/pageToLoad.php",
success: function(result) {
$("#main").html(result);
}
});
});
});
</script>
</head>
<body>
Load Page
<main id="main"></main>
</body>
</html>
The problem here is that most of our tools use forms that are submitted via POST and then parsed with PHP (has to be php because it connects to our database to get information needed). Here's a simplified example of a tool page:
<?php
$action = htmlspecialchars($_SRVER["PHP_SELF"]);
function getResults() {
if(isset($_POST["infoForQuery"])) {
//Do some sort of query to database and print out results
}
}
?>
<body>
<form action="<?php echo $action;?>" method="post">
<input type="text" name="infoForQuery">
<input type="submit" value="submit" />
</form>
<div>
<?php getResults();?>
</div>
</body>
I need to be able to use these tools inside the dashboard page, but whenever I try to submit a form, it just reloads the entire dashboard page, resulting in the POST data not existing (maybe this is because the PHP code is run before ajax loads the content into the dashboard page? not sure).
I know I can use AJAX to send the POST like so:
$(function() {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'some_directory/pageToLoad.php',
data: $('form').serialize(),
success: function() {
alert('form submitted');
}
});
});
});
However, this does not allow me to use the data collected in the form to query a database and print results out on the page.
Is it possible to accomplish this without having to leave the dashboard page, and if so, how?
Edit: I believe I've figured it out! What I wasn't realizing was that when I overrode the submit function and used ajax to send the post instead, I could actually retrieve the result of that post and put it into my page. Here's what I did:
<script>
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: 'some_directory/pageToLoad.php',
type: 'post',
data: $('form').serialize(),
success: function(result) {
$("#main").html(result);
}
});
});
</script>
Could be because the submit event is not firing. Since your forms are loaded dynamically do it like this:
$(function() {
$(document).on('submit', 'form', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'some_directory/pageToLoad.php',
data: $('form').serialize(),
success: function() {
alert('form submitted');
}
});
});
});

unable to fully retrieve text in php from ckeditor

HTML Code
<form name='form' method='post'>
<textarea name='ckeditor'></textarea>
<input type='submit' name='submit' value='Save' />
<form>
javascript code
$(document).submit(function(event){
event.preventDefault();
$editor = CKEDITOR.instances['editor'].getData();
//alert($editor);
$.ajax({
method: "POST",
url : "someurl",
data : "full_text="+$editor,
success = function (response) {
alert(response);
}
});
});
PHP CODE
<?php
print_r($_POST["full_text"];
?>
when alert is used inside java script my full text is shown. But when used print_r function of php only two or three lines of text is shown.
If i have three paragraph text alert display all three paragraph but php shows only two lines. below is the image for more detail
First image shows alert inside javascript before submitting.
Second Image shows alert response from php page
$.post would be easier for a simple post request.
$.post("someurl", {full_text: $editor}, function(response){
alert(response);
})

Need to grab input from a form, process it with php, having the option the reload the page depending on the answer

this is my problem.
I have a startpage website on this address: http://battlestation.rocks/
It mostly revolves around a search bar in the front page that executes commands. Presently, every command is processed with php, like so:
if (isset($_POST['searchBar'])) {
$originalcommand = $_POST['searchBar'];
processcommand($originalcommand);
return;
}
With this, every command reloads the page, which is a waste as most of the times it just opens some link from the startpage. In other cases, the startpage is changed by the commands, and thus in those cases I would like the page to reload.
I've seen from other questions that you can have the page not reload with AJAX, but none of the answers I've seen send the form input to php for processing, nor do they include the option to reload if necessary.
I'm very much a hobbyist coder and have zero experience with AJAX, please don't get too technical on me. I'm obsessed with this startpage, I just need to get this working as intended. Please help!
If you use PHP directly then the page needs to reload. If you use AJAX then you can send it so without reloading. !-You need a new PHP file in which you process the input-! An example with jquery but works the same:
You normal site:
<form action=''>
<input type='email' id='email' placeholder='E-Mail' required=""/>
<input type='password' id='pwd' placeholder='Passwort' required=""/>
<button id='go_login'>Go</button>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$('#go_login').click(function() {
var bn = $('#email').val();
var pw = $('#pwd').val();
$.post('newphpsite.php', {'bn': bn, 'pw': pw}, function(data) {
alert(data); //send back echo from PHP
});
return false; //The form is not sent and does not reload the page.
});
</script>
newphpsite.php :
<?php
$bn = $_POST['bn'];
$pw = $_POST['pw'];
echo $bn."".$pw;
?>
?>
Yes, you should send the data via AJAX. One popular option is to use jQuery. Below is a simplified example using jQuery.
First, the HTML:
<input id="searchBar" name="searchBar" type="text" />
<button id="submit">Search</button>
<div id="searchResults"></div>
Next the jQuery:
<script type="text/javascript">
$("#submit").click(function() {
$.ajax({
type: "post",
url: "search.php", // Your PHP file
data: {
searchBar: $("#searchBar").val()
},
success:function(results) {
// Do something with your results
$("#searchResults").html(results);
}
});
});
</script>

How to get data from database in javascript

i'm Sanjeev
My webpage has a button (not submit button of form) inside form. On click of that button i have to run a SQL query and then set other form field on the basis of query result.
My problem is how to run SQL query from javascript
you have to use ajax script to achieve this process. on button click ajax script is executed and the result is fetched in ajax response then you have to append the results to other form fields.
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
function getResult(){
var x=document.getElementById('inp').value;
dat='param=' + x;
$.ajax({
type: "POST",
url: "server.jsp",
data: dat,
cache: false,
success: function(html) {
$('#textdiv').val(html.trim());
}
});
}
</script>
</head>
<body>
<input type="text" name="inp" id="inp">
<button onclick="getResult();">
<input type="text" name="result" id="textdiv">
</body>
<!-- You need server page to execute query and in php the result is echoed.it came back to ajax response inside success function. -->

Pass variables from HTML form -> ajax load()

What I am trying to do
I have a HTML form which looks like this:
[input text field]
[submit button].
I want the output results to display in only a small part of the page (don't want to refresh the entire page after the button is clicked).
What I have done so far
I am using jquery load() as follows:
<script type="text/javascript">
function searchresults(id) {
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
</script>
Results will appear in a div which is exactly what I want:
<div id='myStyle'></div>
The problem
The script above works just fine (I used a variation of it elsewhere). But I have 2 problems:
1-How to call the load() script from the form. I tried this but it doesn't work:
<form id="form" name="form" method="post" action="searchresults('1')">
2-If I am not able to call the load() script from the form, how do I pass what is into the input text field to the load() script so in the end it can be proceessed by the displaysearchresults.php file???
Thanks
Currently its not working since you have a typo:
function searchresult(id) {
/^ no s
$('#myStyle').load('displaysearchresults.php?id=' + id ; ?>);
}
Here:
action="searchresults('1')"> // this should be on the onsubmit
^
Since you're intention is to submit the form without reloading, you could do something like:
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: 'displaysearchresults.php',
data: {id: 1},
type: 'POST',
success: function(response) {
$('#myStyle').html(response); // assuming the markup html is already done in PHP
}
});
});
Of course in the PHP side, just call it like a normal POST variable:
if($_SERVER['REQUEST_METHOD'] == 'POST') {
$id = $_POST['id'];
// other stuff you have to do
// echo markup stuff
exit;
}
Ok I have been able to do what I wanted to do, i.e., displaying search results in part of the page without reloading.
Actually it is not necessary to use the ajax load() function. You can do it with the script below:
<form id="form" method="POST">
<input type="text" id="textbox" name="textbox" />
<input type="submit" name="test" />
</form>
<div id="myStyle"></div>
<p>
<script src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$('#form').on('submit', function(e){
e.preventDefault(); // prevent the form from reloading
$.ajax({
url: 'displaysearchresults.php',
type: 'POST',
dataType: 'html',
data: {text:$('#textbox').val()},
success: function(response) {
$('#myStyle').html(response);
}
});
});
});
</script>
So what is this doing:
It will "read" what the user entered in the textbox,
When the user click the "submit" button, it will put that into a POST variable and send it to "displaysearchresults.php" without reloading the page,
The search results will be displayed between the "mystyle" div.
Pretty nice.
Note for beginers: do not forget to copy the jquery file to your root folder otherwise ajax just won't work.

Categories

Resources