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>
Related
I am running a Wordpress website, and trying to call PHP methods from my Javascript code.
When a button is tapped, the saverFoo() Javascript method is called, and attempts to call the PHP method save_image_data().
function saverFoo() {
var dataURL = canvas.toDataURL();
<?php echo save_image_data(dataURL); ?>;
}
function loaderFoo() {
var loadedImage = <?php echo loadimagedata(); ?>;
console.log(loadedImage);
}
The PHP method's implementation is in the function.php file, and is simply attempting to save some image data (dataURL) in the user's meta
function save_image_data($imageData) {
global $current_user;
update_user_meta( $current_user->ID, 'user_design', $_POST['$imageData']);
}
function loadimagedata() {
global $current_user;
$old_notes = get_user_meta($current_user->ID, 'user_design', true);
return $old_notes;
}
Inspecting my web-page in Chrome, shows me an empty space where loaderFoo () (javascript) is supposed to be calling loadimagedata() (php) , and loadedImage is an undefined variable, when I try to log it, such as:
function loaderFoo() {
var loadedImage = ;
console.log(loadedImage);
}
Not sure what fundamental mistake I'm making here.
Always remember that PHP runs on the server side, and javascript on the client side. So we have an order here, the server receives the request PHP processes what it should process and render the page, only here Javascript will be executed.
In this example, when the 'saverFoo()' function is executed, this function <? Php echo save_image_data (dataURL); ?>; has already been written on the page. PHP will not be able to get the information contained in the dataURL variable, not on this way. To do this, we must make a request to the server with this desired information, but with an "image" is not trivial to do this, as there is a limit on the size of the post when using a normal String field.
function saverFoo () {
var dataURL = canvas.toDataURL ();
<? php echo save_image_data (dataURL); ?>;
}
PHP doesn't work that way. It is a pre-processor. It is all run and done server side and the resulting text/html/binary data/whatever is sent out to the client. In the case of a content type of text/html the browser will load it, parse it, render it, and run whatever javascript is called.
How you can mix PHP and JavaScript in-line like that would be to use PHP to fill in variables. For example
alert("<?php print($_SERVER['SCRIPT_FILENAME']); ?>");
would work because the client would see
alert("/path/to/foo.php");
and render that for the user.
To really interact with PHP using JavaScript, you'll want to look into using a http based REST type service and perhaps one of the various popular tool sets like Angular, Vue, etc.
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.
I have a page with a header include, and the include needs a phone number to change on it ONLY if the filename of the current page contains a certain word.
Normally, for a change that is not within an include, the below code would work.
<?php if (strpos($_SERVER['REQUEST_URI'],'example-match') !== false)
{
echo '555-555-5555';
}
else
{
echo '1-800-555-5555';
}
?>
However, since the code is in an included file on the page, rather than the original page itself, the server instead is returning the name of that included file.
Example: www.example.com/im-on-this-page.html returns the name of the include the php file is in - www.example.com/header-include.php.
Is there a way to grab the URL of the page the include is "included on", rather than the url of the include, from code that is within the include?
UPDATE:
The file is being included via Javascript, since the page is it being included on is an html file:
<script>
$('#Header').load('/includes/header.php');
</script>
As of your last comment:
Then it is not an include but a GET request to the PHP delivering a JavaScript. And then, the given URL is proper. In order to find out from where the script has been included you may either look for the referer header (which is instable) or pass the current file to the script itself:
<script> $('#Header')
.load('/includes/header.php?from=encodeUriComponent("<?php echo $_SERVER['REQUEST_URI'] ?php>")'); </script>
Within your script, instead of $_SERVER['REQUEST_URI'] then use $_GET['from']
As commentors have mentioned as well. This is incorrect. $_SERVER does not change for the duration of the script (and includes). Including a file will not alter it.
A javascript include, meaning it is actually called by the client by an ajax call, and not included on the server before the page is presented.
(you load a page, and then load another page which you "print" somewhere on the first)
a quick and dirty fix would be to write something along these lines on the first php file
<?php if (strpos($_SERVER['REQUEST_URI'],'example-match') !== false)
{
echo "<script> var phone_number = '555-555-5555';</script>";
}
else
{
echo "<script> var phone_number = '1-800-555-5555';</script>";
}
?>
which will create a variable on the client side, which you then can call from the loaded page as a javascript 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'm trying to update is a javascript which when you hover over an image, a div object floats near your mouse with information, this information is stored in a .js file as an array,
eg.
Text[0]=["image 1","data 1"]
Text[1]=["image 2","data 2"]
in the past if this array is change/data added to/removed from it would require uploading a new copy of the .js file, if data was added to/removed from it would also require a change to the .dwt file for the new image which would update every file that use the .dwt file as the main template which could result in 20+ pages being uploaded
i figured i can automate this by using the database by flagging records if they are active and using a mysql query to get only those which are active, this way a blackened app can add to the database and deactivate record thus eliminating having to upload files every so soften.
to do this, i had planned on storing the information in the database and building the above array based off the results, researching how to use mysql queries in javascript lead me to code like this
$.ajax( "path/to/your.php" )
.done(function() { alert("success"); })
.fail(function() { alert("error"); })
now i understand that i need to make a .php file which runs my query and that my formatting of the query results into the array would be one in the .done part but what i don't understand is what i'm supposed to do in the .php file to output the query results how in the .done part i'm supposed to reference the output
bellow is the code i use to echo my query results to the page to ensure i am getting results
$resultIndex = 0
while($row = $results->fetch_array(MYSQLI_ASSOC))
{
echo '<'.strval($resultIndex).'><br>';
echo 'id = 'strval($row['id']).'<br>';
echo 'name = 'strval($row['name']).'<br>';
echo 'desc = 'strval($row['desc']).'<br>';
echo 'active = 'strval($row['active']).'<br>';
echo '-----------------------<br>';
$resultIndex += 1;
}
i am wondering 2 things
do i just echo or print_r what i want returned from my .php file
how to i access what my .php file returns in .done
I recommend using http://www.php.net/json_encode to output into Json. Yes, just echo the output. On success, a callback is called passed with the data from server.
$.post (url, function (data){
//do some stuff with data from server
});
See http://api.jquery.com/jQuery.post/
Your $.ajax function just points to a page and reads the data on that page. If you want that page to use MySQL, you will need to use php to set up the MySQL query and print the data. The layers of a web app are complicated, but I'll try to break it down for you.
A traditional php/mysql setup works like this:
Javascript:
Client side, only deals with content already available on the page. Often edits html based on user interaction.
HTML
Client side, defines the content on a page
PHP
Server side, runs on the server and construct the html
MYSQL
Server side, used to communicate between the php and the database
Database
Server side, used to permanently store data
Ajax is a way for the Javascript layer to call some php in the background. That php can use MySQL to access data in the database and print it out in a format that the javascript can parse and use. Typically the javascript will then edit the HTML.