I can pass data with this url code to my second php file.
www.test.com/second.php?task=demo&id=55
and I can pass data with this javascript code
<script>
$(function(){
var postdata= 'task=demo&id=55';
$.ajax({
type:'GET',
url:'second.php',
data:postdata,
});
});
</script>
I want to pass this data task=demo&id=55 with php, How can I do that? Thank you.
I can do this with form but I have to do this automatically after page loaded
second.php
$task = $_GET["task"];
$id = $_GET["id"];
...
...
...
other codes
There are several ways to pass values. If second.php is not executed by the same environment, then you can send the values using cURL.
If you intend to redirect to the second page, then you can redirect to second.php using this command:
$youridvalue = 55;
$task = "demo";
header('Location: http://www.test.com/second.php?task='.$task.'&id='.$youridvalue);
If you intend to execute second.php, but to stay on first.php, then you can set the $_GET values, like this:
$_GET['task'] = 'demo';
$_GET['id'] = '55';
and then require or include second.php. However, in this case it is recommended to separate the functionality from second.php into a class or function, so you can reuse the functionality without the need to include or require second.php and/or duplicate your code on multiple places.
Related
Okay so, I'm a bit stuck... Here's my problem. So, what I'm trying to achieve is I have a JS calendar and what I want it to do is when I click on a date, it fetches the times available for that day and displays it and then changes depending on what day you click on WITHOUT refreshing the page. Now, looking around, the only way I can seem to do this is with AJAX (suggestions welcome) although I have never touched AJAX before so have no idea what I'm doing here.
So I've currently got my .HTACCESS files setup on my webserver to use dynamic subdomains.
It's sort of like a multi-step form, and I'm collecting data in the SESSION as I go. Now what I'm guessing the way to do is here, to send a AJAX query with a JS variable with the date and then that runs an SQL query and gets the times and displays them. Here's what I have so far.
Update Session
<div class="output"><?PHP echo $_SESSION["outputTimes"]; ?></div>
<script>
$("#clickme").click(function(e) {
e.preventDefault();
$.ajax({
type:'POST',
url:'data.php',
data: { date: '2020-07-04'},
success:function(response){
alert(response);
}
});
});
</script>
data.php
<?php
//Start Session
session_start();
//Include Database Config
include ("config.php");
//POST
$requestDate = $_POST["date"];
//Define SQL Query
$app_get_sql = "SELECT * FROM cc_av WHERE date=$requestDate";
//Run Query
if($result = mysqli_query($db_connect, $app_get_sql)){
while($row = mysqli_fetch_assoc($result)){
$_SESSION["outputTimes"] = '<li>'.$row["time"].'</li>';
}
}
?>
Currently, when I run this, I get the response in the alert() as the current code of the page I'm on. Hence why I noted about my HTACCESS although I can include() it just fine using the same root. Also, from the results of the data.php, how would I output the code sort of update what would be there at the moment.
Here's what I'm trying to create...
https://drive.google.com/file/d/1bgxSUxN6j2IOZcQBuAOo-PeCsuRgdmZ-/view?usp=sharing
Thanks in advance.
So, I've managed to work out what was going wrong. Because my HTACCESS file is creating SubDomains, it was also redirecting the Paths so in the AJAX code I used a URL to the code instead and then added a header to my PHP code on the file that needed to be requested.
header("Access-Control-Allow-Origin: (URL NEEDING TO BE REQUESTED)");
Final AJAX Code
var scriptString = 'THISISMYSTRING';
$('#clickMe').click(function(){
$.ajax({
method: 'get',
url: '(URL)/data.php',
data: {
'myString': scriptString,
'ajax': true
},
success: function(data) {
$('#data').text(data);
}
});
});
Currently I am working in One PHP Symfony Project Regarding the Performance Evaluation of an Employee.
So I need to know how we can get PHP session variable of an employee (Employee Role) Please see the php file ( $role = $_SESSION['empRole']; ) to an external js file.(js file also attached). I am using PHP Symfony framework.
Actually I need to check who is logged in to the website.if it is admin/core members / Hr.
I need to apply validation to some fileds only when the Coremembers login the website.
Here is the code section that I need to pass $role to External JS file(in pastebin)
public function executeIndex(sfWebRequest $request) {
if (isset($_SESSION['empId'])) {
$role = $_SESSION['empRole'];
if ($role == "admin") {
$empId = $this->getUser()->getAttribute('empId');
$team_members = GroupwareEmployeesPeer::getAllSubordinatesId($empId`enter code here`);
$nc = new Criteria();
$nc->add(PeD`enter code here`ates`enter code here`Peer::NAME, 'Dashboard');
$resultset = PeDatesPeer::doSelect($nc);
So Can you guys give me a solution regarding this, since I am stuck with this for a long time.
Please see thepastebin code for php and external js file.
https://pastebin.com/kbkLjSFa - PHP File.
https://pastebin.com/M60Rg64U - JS file
Yes you can get the php variable into the js file.
Method I:
Rename your .js file to .js.php and pass the php variable as a query string to this file where you link this file in your page.
So, if you have some test.js file, rename it to test.js.php and use it in your page like this
<script src="test.js.php?session_var=<?= $your_var_here;?>&any_var=<?= $any_php_var;?>"></script>
And in your js file, retrieve the values from query string parameters
So inside test.js.php, you can simply
var some_var = "<?= $_GET['session_var']";
var any_var = "<?= $_GET['any_var'];?>";
//rest of your logic goes here
Method II:
Use an AJAX request.
var some_var, another_var;
$.ajax({
url : '/url-which-returns-session-vars', //return the session data in json from this url
asnyc : false,
dataType : 'json',
success : function(res){
some_var = res.some_var;
another_var = res.another_var;
}
});
//rest of the logic goes here.
Both of these methods work. But I prefer the first method, since I don't have to write extra code.
Edit:
Suppose the response of the ajax call looks like this
{
some_var : 'value here',
another_var : 'another value here'
}
So res in the success function argument contains this response and since the response is a JSON you can access these values using the . notation.
Thus,
some_var = res.some_var;
another_var = res.another_var;
and since these variables are global variables, you can use them anywhere in your code in this file.
?> <script> var php_variable = '<?php $variable ?>'; </script> <?php
Global variable should be declared before external js file include . in js file access it using this variable name php_variable
After the above code . jquery external file should be included here
<script src="external.js" ></script>
external.js
consol.log(php_variable);
I have a webpage which contains an array generated with JavaScript/jquery. On a button press, I want to run a PHP function, which updates a MySQL database with the JavaScript array.
I have a .php file with a PHP function that connects to the database and runs an UPDATE query, I want to use the array with that.
So I have home.php, which has the button:
<?php
include_once ('submit.php')
?>
<center><button id="submit" class="button1" >Submit<span></span></button></center>
and the array:
<script>
selectedItemsArray;
</script>
and I have submit.php, which has the sql UPDATE:
function submit(){
$sql = $dbh->prepare("UPDATE pending_trades SET item_list=:itemlist,");
$sql->bindParam(':itemlist', /*array taken from home.php*/);
$sql->execute();
}
I'll convert the array into a JSON before I put it into the database, but I need to know how to get access to the array with my submit.php file, and how to run the submit() function on the HTML button click.
There are multiple issues here. Most crucially, you seem to be confusing server-side and client-side scripting.
You are including submit.php in home.php, which declares a function submit() on the server-side. Your code never executed this function while on the server-side, and so the server-side output is empty,i.e. <?php include_once ('submit.php');?> evaluates to nothing. What the client-side receives is a HTML file with only the button, the function submit() is never passed to the browser.
Remember: server-side scripts are ALWAYS executed on the server and NEVER passed to the browser. That means you will never see anymore <?php and ?> when the file hits the browser - those PHP codes have long finished.
What you need to find out in order to accomplish what you intend:
Use client-side script (JavaScript) to listen to button clicks.
Use client-side script (JavaScript) to submit the form to server through AJAX.
Use server-side script (PHP) to read the data POST-ed, extract the data into an array.
In effect, you are asking three questions. And they are really straightforward; you can read up yourself.
What I'd do is to suggest an architecture for you:
home.php or home.html: contains the button, <link href="home.css"> and <script src="home.js">.
home.js: client-side script to listen for button click and submit AJAX to submit.php.
home.css: styles for the button and other elements in home.html/home.php.
submit.php: server-side script to check for POST variables and the SQL update operation.
Another issue: you are using a deprecated tag <center>. I'd advise you to remove it and layout the button using CSS instead.
use jquery AJAX.
<button id = "submit" class = "button1" > Submit <span></span></button>
your js code
$('#submit').click(function(){$.ajax({
method: "POST",
url: "submit.php",
data: itemlist,
.done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
and your php file. don't include file
$array = json_decode($_POST['itemlist'], true);
Remember your js array itemlist should be json format e.g.
$itemlist = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
I got stuck when using ajax as primary request sender to php.
I was trying to send data to php file and then take that data to view in another file, but the problem is I don't know how to do it .
I tried
var ajax = ajaxObj("POST", "function.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
window.location = "view.php";
}
}
ajax.send("a="+a+"&b="+b);
it locate view.php and I want to take contents that sent
function.php and view it's contents in view.php.
That is where my problem occurs.
So, my question is HOW TO TAKE THOSE CONTENTS
I think you don't understand the use of ajax... here you don't need ajax at all. Ajax is used to update/send content without refreshing the page. So if you want to pass data to a new php file, just pass the variables directly to view.php in your case.
For instance:
go to view.php?a=[your value]&b=[your value]
in view.php you can get the values:
$a = $_GET['a'];
$b = $_GET['b'];
and pass it to your function.php
Use Jquery to avoid dealing with browsers specifications and also jquery is pretty popular and simple to use library
Assuming you are familiar with php and JavaScript
first you have to do all this work in you www or htdocs folder depending on the stack you are using whether it is XAMPP,WAMP or LAMP
let's say as an example we want to send post request to function.php file and that file should verify the existance of $_POST['username'] and return the length of username otherwise it returns 0
so the function.php file should be something like this :
if(isset($_POST['username'])){
echo strlen($_POST['username']);
}else{
echo 0;
}
and the view.php file is the file used to send post request and get the response and displays it in a #display div
so here is the content of view.php
// first you should include jquery
// here is a cdn link
// https://code.jquery.com/jquery-2.1.3.min.js
// or you can use a local jquery file it is up to you
<div id="display">
</div>
// here is the simple js code to send and get the data from function.php file
<script>
$(document).ready(function(){
// waiting for the document until it is ready to use
$.post('function.php',{username:'myusername'},function(data){
// data here is the returned data from the function.php file
$('#display').text('username length is : '+data);
});
});
</script>
I need help on how to call an external PHP script from within JavaScript.
See below for my example
INDEX.PHP
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var myName = 'John';
phpResult = /* Need help calling script.php passing is myName and assigning result to phpResult */;
document.getElementById("demo").innerHTML = "The text from the intro paragraph is " + phpResult;
</script>
</body>
</html>
SCRIPT.PHP
<?php
//script.php
//Need help adding last name to John (i.e. Smith) and returning John Smith to calling javascript
?>
First things first: What are you asking is cannot be done in the way you think. When a page is requested, the server runs the php file, and after that it will send you the javascript/html/css page to you. So when you see the page the php script has already done. Javascript is running on your machine, so that's why you can handle with it user interactions.
But, if you send a post request to the script.php, sending the information you want, then you will be able to interact with a php file. To do this, you need jquery. Here is the script how you can do it in jquery:
$.ajax({
type: "POST",
url: "yoursite/script.php",
data: "name="+myName,
success: function(data){
phpResult = data;
document.getElementById("demo").innerHTML = "The text from the intro paragraph is " + phpResult;
}
});
You can download jquery from here: http://jquery.com/download/
After you have downloaded, you have to link it to your index.php the jquery.js file, as a normal javascript file.
In your php file, you can access the name with $_POST["name"], and the information you want to send back, you have to actually print it.
Something like this:
if(isset($_POST["name"])){
$result = "";
//Do something with the name, and fill accordingly the $result variable
// Something like:
$result = $_POST["name"]." Smith";
echo $result;
}
You can simply write
phpResult = '<?php echo $sometext; ?>';
But,
the js script needs to be in a php file. you cannot use this in .js file obviously.
this will not evaluate any runtime variables on the client side. because the page will already contain vars rendered by the php script from the server.
I use this method all the time specially for rendering php arrays and objects as js objects/arrays.