How to load PHP page with variables passed from javascript - javascript

I'm new to PHP and am trying to figure something out that I'm sure is very basic. What I am wanting to do is generate variables in javascript and pass these to a PHP page which then loads and displays. The problem is, I seem to be able to both POST variables to the PHP page and load the PHP page but am unable to load the PHP page with the variables that I POSTed.
Here is an example of my code:
index.php
...
<script language="javascript">
function passToPHP(){
$.ajax({
type: "POST",
url: "/TraceExperiment/TraceExperiment.php",
data: {
varToPass: "foo"
},
success: function(){
window.location.href="/TraceExperiment/TraceExperiment.php";
}
})
}
</script>
<input type="button", value="displayPHP", onclick="passToPHP()"></input>
TraceExperiment.php
<?php
$tempVar = $_POST["varToPass"];
echo("hello" . $tempVar);
print_r($_POST);
?>
What is happening when I click displayPHP is that the ajax POST succeeds and
TraceExperiment.php loads fine (it actually has a whole heap of other html, php etc. code that loads and displays fine but for simplicity I've excluded that) but the $_POST array seems to be empty.
i.e. what ends up being displayed when I try to echo and print the POST array and variables is:
Notice: Undefined index: varToPass in C:\xampp\htdocs\TraceExperiment\TraceExperiment.php on line 3
helloArray ( )
Any help resolving this would be much appreciated. Ultimately, I'm simply after a way to display a PHP page that uses variables passed from a javascript file.

You can dynamically create a form in JavaScript and submit it rather than calling ajax and refreshing the page:
<script language="javascript">
function passToPHP(){
$('<form action="/TraceExperiment/TraceExperiment.php" method="POST"><input type="hidden" name="varToPass" value="foo" /></form>').appendTo('body').submit();
}
</script>
<input type="button" value="displayPHP" onclick="passToPHP()"></input>

You can do a get request like this
<script language="javascript">
function passToPHP(){
var varToPass= "foo"
window.location = "/TraceExperiment/TraceExperiment.php?varToPass="+varToPass;
</script>
<input type="button", value="displayPHP", onclick="passToPHP()"></input>
<?php
$tempVar = $_GET["varToPass"];
echo("hello" . $tempVar);
?>
or a post request by creating a simple form
$('#frm').submit(function(e){
var varToPass= "foo"
e.preventDefault();
$(this).find('#varToPass').val(varToPass);
$(this).submit();
});
<form id ="frm" method="POST" action="/TraceExperiment/TraceExperiment.php">
<input type="hidden" id="varToPass"/>
<input type="submit"/>
</form>

dont redirect to the same page on success. you are getting the undefined var on second go to that page
function passToPHP() {
$.ajax({
type: "POST",
url: "/TraceExperiment/TraceExperiment.php",
dataType:text,
data: {
varToPass: "foo"
},
success: function(data) {
console.log(data);
}
})
}
try doing like this
if you want to show the message in the html
try
success: function(data) {
$('body').append(data);
}

There is 2 solution for This
by the different approach
Generate your variable value by JavaScript and than use
Write in TraceExperiment.php
function genratenumber(){
return "number"
}
window.location.href= "/TraceExperiment
/TraceExperiment.php?yourvar="+genratenumber()
</script>
<?php }else{
// get the value of $_GET['yourvar']
} ?>
Than get it by using $_GET['yourvar'] on same page
By using your approch
you need to put that variable in session (in ajax file) than only you can get that variable

Related

Place Javascript variable into a PHP Variable

I have the following JS code:
<script>
$('#mpxModalEdit').on('show.bs.modal', function(e) {
var editId = $(e.relatedTarget).data('edit-id');
$(e.currentTarget).find('input[name="editId"]').val(editId);
});
</script>
This places the CORRECT edit-id value into a form text box name=editIdas I wish.
I would like to add another line of JS so that it ALSO places the value into a PHP variable since I need to make a subsequent
$query = "select * from playlists where id='editId'
I don't know any PHP syntax, but what I can tell you is that PHP is executed on the server and JavaScript is executed on the client (on the browser).
if on your page you had:
<form method="get" action="blah.php">
<input name="test"></input>
</form>
Your $_GET call would retrieve the value in that input field.
So how to retrieve a value from JavaScript?
Well, you could stick the javascript value in a hidden form field...
That could be the best solution only.
<script type="text/javascript" charset="utf-8">
var test = "tester";
// find the 'test' input element and set its value to the above variable
document.getElementByID("test").value = test;
</script>
... elsewhere on your page ...
<form method="get" action="blah.php">
<input id="test" name="test" visibility="hidden"></input>
<input type="submit" value="Click me!"></input>
</form>
Then, when the user clicks your submit button, he/she will be issuing a "GET" request to blah.php, sending along the value in 'test'.
Or the another way is to use AJAX.
PHP-Scripts are only run, when you load your page before any js is run or make an AJAX. In addition, PHP runs on the server, while JS is client-side.
My first suggestion would be, to really think, whether you need to do this (or even tell us, why you think it is).
If you really need it, you can perfom an AJAX and send your variable as data to the Server.
Using AJAX call you can pass js values to PHP script. Suppose you are passing editId js value to logtime.php file.
$(document).ready(function() {
$(".clickable").click(function() {
var userID = $(this).attr('id');
//alert($(this).attr('id'));
$.ajax({
type: "POST",
url: 'logtime.php',
data: { editId : editId },
success: function(data)
{
alert("success!");
}
});
});
});
<?php //logtime.php
$editId = isset($_POST['editId']);
//rest of code that uses $editId
?>
Place the AJAX call after
$(e.currentTarget).find('input[name="editId"]').val(editId);
line in your js script.
then you can assign to your desired PHP variable in logtime.php file

Update img with jquery and php

i'm trying to update img cover without refresh the page using ajax and php but it does not work at all
HTML
<div class="cover" >
<img id="b1" src="<?php echo $user->picture_path();>"class="cover"/>
<div id="modal-cover" class="cov-lo"> </div>
</div>
js
$('#b2').on({
'click': function(){
$('#b1').attr('src', <?php echo $user->picture_path();?> + '?' + new Date().getTime());}
});
the input and form
<form action="profile.php" method="POST" enctype="multipart/form-data" >
<div class="hio">
Upload <input type="file" onchange="this.form.submit()" name="cover" id="bla2"class="custom-file-input" />
</div>
</form>
Ajax would look more like this:
js/jQuery:
$(document).on({'click', '#b2', function(){
$.ajax({
type: 'post',
url: 'my_ajax_processor_file.php',
data: '',
success: function(data){
$('#b1').attr('src', data);
}
}); //END ajax
}); //END #b2.click
my_ajax_processor_file.php:
<?php
$dt = new Date().getTime();
$pp = 'get user picture path here';
echo $pp .' - '. $pp;
Note that you need to have an external PHP file, which I've called my_ajax_processor_file.php, that does some additional PHP processing and ECHOs back a value.
This value is received in the AJAX code block's success function, and called data (call it what you like - the name is set here: function(data).
Note that the contents of data variable are only available within that success function.
Here are some more basic examples of what AJAX looks like:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
I think you have a fundamental misunderstanding of where the PHP and HTML are interpreted:
PHP is a server-side scripting language designed for web development (see this Wikipedia article). That means that the PHP code is executed on the server before arriving in the browser.
HTML is interpreted as plain text by the browser. No PHP is executed in the browser.
Therefore, once the JS gets to the browser, echo $user->picture_path(); has already been executed and is interpreted as plain text by the browser.
Your JS will look like this once it hits the browser:
$('#b2').on({
'click': function() {
$('#b1').attr('src', '/the/path/to/the/picture' + '?' + new Date().getTime());
}
});

PHP Post to a div on main html page - So it can be parsed by Javascript

I have PHP code which successfully gets the contents of a directory on my server.
I wish to then write this array to a specific div on my main html page (so that I can parse this later and use this information further)
Currently my PHP navigates me away from my current page to write this array which I want to prevent.
Furthermore I wish to do all of the PHP work on a button click, and return the values on the main html page after.
How can I do this???
My button on my html page is as follows:
<form action="PHP_Function.php">
<input type="submit" class="learnButton" name="insert" value="Find Available Evidence" />
</form>
And my PHP code looks like this to carry out the work:
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'insert':
insert();
break;
}}
I have an array: "IfPresentArray" which I then wish to write to my main html page:
if(in_array("Facebook.xml", $dirArray)){
$IfPresentArray[0]="1";
}else {
$IfPresentArray[0]="0";
}
Any help would be greatly appreciated as I am very new to PHP.
Thanks in advance
You need to use AJAX techniques to do this. Use a Javascript framework like jQuery to react to the button click, make a request to your PHP script, and then update the contents of the div.
See http://api.jquery.com/click/ for handling clicks, and http://api.jquery.com/jQuery.ajax/ for making the request.
Good luck!
You will need to use an ajax call. This allows your to click some div, send something to the server, receive a response and display an output in many different formats.
You can either reference the jQuery library in your header
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
or just download it and save it whereever
Here is a basic ajax call:
<script>
$(document).ready(function(){
$('#someval').click(function(){
var content = $('#somecontenttoadd').val; //this could be many things... etc(.text, .html)
$.ajax({
type:'post',
url: 'PHP_Function.php',
data: 'action='+content,
success: function(resp){
$('#somediv').html(resp); //lets put the information into a div
//this could be anything response format like .val or .text instead of .html
},
error: function(e){
alert('Error: ' + e);
}
});
});
});
</script>
HTML -- you can get rid of the tags and just use the id of the object.
<input type="submit" class="learnButton" name="insert" value="Find Available Evidence" id="someval"/>
As others said, AJAX is the solution, I will give you the code that works for me, so that you have an exact starting point.
As I understand you have a separate html page and a php file that includes your function.
In order to make this work you will have to implement a function with an AJAX call.
This should be placed in a javascript file and will be invoked after the form submit button is clicked on the html page.
The AJAX call will then invoke your php function, get the response data back from php.
The javascript function will update the html page in the end.
You will need three files:
main.html
script.js
function.php
Let me replace my original answer with a full example of the three files.
main.html
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="/script.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<form id="myForm" method="post" action="function.php">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Name">
</div>
</form>
<div class="modal-footer">
<button type="submit" form="myForm" class="btn btn-primary" id="SaveButton">Submit</button>
</div>
<div id="resultbox">
</div>
</div>
</body>
</html>
Here we included jQuery, our own javascript and bootstrap just to look better. the form action is our function.php, the form 'id' is used in our jQuery code. the "result box" box will display the response.
script.js
$(function(){
$("#myForm").submit(function(event) {
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
success: function(data)
{
//display data...
$("#resultbox").html(data.name).show;
}
});
return false;
});
});
this will override the default form submit behavior. I had a typo here in the original answer, I fixed it. url and data are taken from the html form, dataType is set to json, because we expect a json back.
function.php
<?php
echo json_encode(array('name' => $_POST['name']));
Our php code is just one line, we build an array and return it as json. You can then used in jQuery, just like any other json, as shown in the above code.

Ajax form not getting a reply from php file

This form is working perfectly fine, e.g. it stops the form submitting, there's no javascript errors in the console log. However, when I press submit, I get an alert with nothing in it. I have searched the internet for multiple solutions and they all give the same for me.
Here's my Javascript/Html
<script>
$(function(){
$("#submit").click(function(event){
event.preventDefault();
$.ajax({
type:"post",
url:"templates/process-token.php",
data:$("#form").serialize(),
success:function(response){
alert(response);
}
});
});
});
</script>
<form id="form" method = "post" action = "security_check">
<input type = "text" name = "fld1" id = "fld1" />
<input type = "text" name = "result1" id = "result1" value = "value_from_php_page" disabled />
<input type="submit" value="Submit" id="submit">
</form>
And here's the PHP, it's so simple but doesn't work:
<?php
echo $_POST["fld1"];
?>
Any help here would be appreciated. Thank you.
Change data from $('#form').serialize() to a one test variable so you can see if it is JS or PHP that is causing the issue.
On your PHP page:
<?php
isset($_POST["fld1"]) ? $myvar1 = $_POST["fld1"] : $myvar1 = 'No data passed...';
echo $myvar1;
?>
This confirms that there is infact an fld1 in the $_POST, and if not, says so, taking away the guess work...
You could do this with JSON both ways. Here's how I would implement this kind of thing in JavaScript and PHP.
There's a great function in jQuery that is a shortcut for getting JSON data. It's a shortcut for $.ajax specifically for simple calls.
$.getJSON( "templates/process-token.php?"+$("#form").serialize(), function( data ) { alert( data.reponse ) } );
PHP could return a json encoded string so it can be accessed from the JavaScript code more easily.
<?php echo json_encode( array('response'=>$_POST['fld1']) ); ?>
That can happen only if the text box #fld1 is empty. Type something in the text box and it will work.

jquery submit function does not work

I'm developing a webpage which creates a form with various select tags dynamically. Unfortenatley the jquery submit function passes incorrect information to the php file (form_submit.php) that must process this information; the (netbeans 7.4) debugger always shows default (not selected) values in $_POST within the php file instead of the selected values . The even stranger part: when I copy (in the code below) the console output with the serialised formdata straight into the following ajaxcode (see code), the php debugger shows the correct -selected values within the $_POST array..(?)
The resulting form is quite substantial. The only theoretical cause I can think of is that therefore the execution of 'var dataAjax = $( this ).serialize();' takes time and is not finished when the following ajax call starts...(??)
The code:
$("#myForm").submit(function(event){
event.preventDefault();
var dataAjax = $( this ).serialize(); //does not work, but when copying the string from the console in line below it does work.
console.log('SUBMITTED FORM: '+ dataAjax );
//next line is only used as a test
//var dataAjax = 'agreementapproval0=SolarX_10&selected_emeterproductid0=SolarX_10_1_1&selected_eproductid0=SolarX_10_2_4&selected_emeterproductid1=NOSELECTION&selected_emeterproductid2=NOSELECTION&selected_eproductid1=NOSELECTION&selected_eproductid2=NOSELECTION&form_token=30688e467ee88167805ad0f330809d74';
$.ajax({
type: "POST",
url: "form_submit.php",
data: dataAjax,
dataType: "json",
async: true,
success: function(msg){
if(msg.statusgeneral == 'success'){
}
else
{
}//else
}, //succes: function
error: function(){
$("#errorbox").html("There was an error submitting the form. Please try again.");
}
});//.ajax
//make sure the form doesn't post
//return false; //depreciated
//} //if(form.valid()
});//$("#myForm").submit()
<form id="myForm" name="myForm" action="" method="post">
<div id="wrapper"></div> <!--anchor point for adding set of product form fields -->
<input type="hidden" name="form_token" value="<?php echo $form_token; ?>" />
<input type="submit" name="submitForm" value="Confirm">
</form>
It works fine http://jsfiddle.net/a9DN4/
You might have been trying to hook form before it have been created, try to wrap your code with
$( document ).ready(function() {
// Handler for .ready() called.
});
PS and move event.preventDefault(); to the 1st string of your function, as Kevin says.

Categories