How to tell which Javascript file is requesting data in PHP? - php

I have two javascript files, call it
test1.js
test2.js
they are used to request data from the php file using the following:
var xmlhttp= new XMLHttpRequest();
xmlhttp.open("GET", "../forum/getSomething.php", true);
xmlhttp.send();
and I have a php file which is used to do some queries and return the encoded json obj back to one of the js files above, call it
getSomething.php
my question is, how can I tell which file js is making the request to the php? Ultimately, I want to state a condition and do something like the this:
# inside getSomething.php
# conditional statements
if request from test1.js
do A
else if request from test2.js
do B
Any tips would be helpful, thanks

This is not possible without having the different files actually specify this themselves - this can for instance be done by adding custom headers to the XMLHttpRequest, or by adding additional query params.

You can use HTTP_REFERER with HTTP_X_REQUESTED_WITH but it can be tricky I'll advice you can to identify each js request with ID
Example
xmlhttp.open("GET", "../forum/getSomething.php?action=test1", true);
Then PHP
switch ($_GET['action']) {
case "test1" :
// Do Test 1
break;
case "test2" :
// Do Test 2
break;
}

You can not generically write code that says "this is coming from script x" - JavaScript engines do not keep track of where any particular line of code come from.
You can always pass explicit data (i.e. in query string) differently from each script i.e.
xmlhttp.open("GET", "../forum/getSomething.php?from=test1", true);
Side note: consider using JQuery.ajax for more generic code...

Related

how can I turn the content of the span into a php variable / How do I start a mysql query when clicking a word and send that word to _post in php

I am building a dictionary and I have my words and definitions stored in a MySQL database.
I want to make some words clickable (maybe as spans or buttons) so when I click them a new query that has this word as key starts (so how can I send the content of this clicked word into to _post in my details.php file)? Or how can I turn the content of the span into a php variable?
<html>
Click this <button>word</button>
</html>
<?php
echo "You clicked that " $word;
?>
MySQL communicates with your server-side code (PHP).
Your PHP code reads/writes data into MySQL, generates (or loads) HTML templates that are sent to the browser when requested.
Your browser requests a page via URL when someone visits your site, sending a request to your URL and getting some response, presumably HTML in return.
From the moment when the page is received, CSS rules are being applied with design purpose and programmatic code (Javascript) is being executed.
Now, your span is part of your HTML, which was either received from the server, or generated by your client-side code (Javascript).
It is important to note that in production mode the browser and the PHP code are running on different, remote computers and sometimes the MySQL RDBMS is also running on a separate computer, a database server.
So, the thing you want to do is to have a Javascript event that sends some content to your server, which processes it and then stores it into your MySQL database.
Event creation via Javascript
Read this article: https://developer.mozilla.org/en-US/docs/Web/Events/Creating_and_triggering_events
Basically you will need to create an event, which will either be an
onclick="yourJavascript()"
or a call to addEventListener. Try to implement a trivial example for that, like below:
document.getElementById("mybutton").addEventListener('click', function() {
alert("Yay! The click was handled!");
});
<input type="button" value="click me" id="mybutton">
Later on you will need to replace the function body with a request sending.
Send an AJAX post request and receive a callback
Read this article: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
Read this article as well: https://javascript.info/xmlhttprequest
Example:
let xhr = new XMLHttpRequest();
xhr.open("POST", URL, somedata);
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 3) {
// loading
}
if (xhr.readyState == 4) {
// request finished
}
};
It is worth converting something similar to a parameterizable function so in the future you would be able to reuse most of the benefits of your current work. And call this function I just suggested in your event listener.
Explanation:
XMLHttpRequest is the type you instantiate in order to send an AJAX request
xhr is the resulting object of the instantiation
xhr.open is a function that you need to call, passing the request method (which is "POST" in this case, the URL, which is the target and some data)
somedata is a variable the code above assumes that was already defined, but you will need to properly initialize it yourself
send is sending the request, in our case asynchronously, that is, the request will not end yet when the next line is processed
xhr.onreadystatechange is a callback which is executed when the ready state changes; state 3 is loading, state 4 is request finished, so your meaningful code should be inside the if that checks for the state being 4
Handle POST requests with PHP
Read this article: https://www.codegrepper.com/code-examples/php/php+handle+post+request
Basically you will have your data in $_POST, you can process whatever logic you want and you can generate an HTML/JSON/whatever response the way you like.
PHP - MySQL
You can generate MySQL queries with PHP and you can use PDO, for example, to generate parameterized queries and sanitize your dynamic parameters, especially those defined by the users, to avoid SQL injection.

I cannot `$_GET['id']` from URL

I try to use the update method from bootstrap modal, but when I click edit and url appears in this way http://localhost/../pages/typography#edit?id = 15.
I can not $ _GET ['id']
The error is, the indeterminate index
Try http://localhost/../pages/typography?id=15#edit
The hash part (everything after #) is typically not sent to the server for processing. Anything you want your server to receive needs to be before the # symbol.
This URL http://localhost/../pages/typography#edit?id = 15 ends after #
So, your server gets URI /../pages/typography
The structure or URL is:
protocol://domain_name/URI#anchor
Anchor (after #) can be proceeded on client side with JavaScript.
It seems like the one of the easiest ways to acomplish this is to send an AJAX request to your server using GET. Assuming that your page doesnt change based on the change or sending of the id variable, the following code will work.
Javascript:
xhttp.open("GET", "typography?id=" + id, true);
xhttp.send();
If your page does change by sending the id variable, then your page would have to reload. If that is a no-go you would have to implement a way for the PHP would return a JSON file with the data then your javascript on the gape would have to change the HTML based on the JSON data. This is better long term but is unnecessary to implement for small projects.

passing variable value from javascript to php

I am working on a project where I used ajax for asynchronous DB access.
I store the value in JavaScript variable as follows..
var content=xmlhttp.responseText;
now what I wanted is to pass this value to the php module on same page..
Please suggest me..its urgent
You'll have to make a separate AJAX request to another script to achieve this. PHP is server-sided and therefore cannot directly interact with the client.
You should handle the data (which you are assigning to content) in PHP because, as the other answers here tell you, PHP is server-side and JavaScript is on the client. If you are getting this data from a page you control, instead of var content = xhr.responseText; just modify the data BEFORE you send it. For example, if you are making an AJAX call to a process.php file on your server to get the data you are otherwise assigning to content in JavaScript, be sure to handle the data in process.php PRIOR to echo()'ing the data (which you are then storing inside content on the client):
In process.php:
// below is the normal server script which you are storing in content on the client
// echo $result;
// instead, we are going to operate on the data first:
return doSomething($result);
Then on the client:
var newContent = xhr.responseText;
And the newContent variable will contain the data you previously wished to modify with PHP. If you DO NOT have control of the server script which you are calling with AJAX, then as mentioned here already, you will need to send a SECOND AJAX call to the server with your PHP, and use $_GET or $_POST to retrieve that content data and then play with it there.
Am unclear about your need to pass value from javascript to php.
But I can give you,
A non-recommended but working approach towards your problem:
You said, you are making an Ajax call at first. While processing the corresponding server side php function, Store the response value (value of xmlhttp.responseText) into a $_SESSION variable. Finally Reload the page (using location.reload()) inside the ajax response handler function.
And a recommended approach towards your problem:
You might have added some if-else control-flow structures in the php code and expecting to execute them after getting the ajax response value (sadly you cannot do that). So if you do have some logic like that, then convert those if-else conditions to corresponding Javascript code. May be a javascript function and call that function by passing the ajax response value to it. This new function will use your ajax response value and make changes in some parts of your webpage by applying necessary logic.

Use ajax to call a php method

Hi i would like to use ajax in my website where all requests pass are loaded in index.php (i use htacess for rewriting urls) so when i use ajax i always reload the current page and then use if(expressio) to check if the user has called a function with ajax but this cause that all the page is reloaded each time i use ajax.
I was wondering if there is a method to call a specific php method/function or property in the current page with ajax without reloading all the page.
I'm using the jquery library for ajax
If someone knows some other ways is ok!
A main use of ajax is that you call asynchronously something. Most often functions-methods that are called with ajax do rely on the same php file (if not then it's okay) with other stuff that you do not need to call asynchronously.
For example you have a method that is called via ajax to autocomplete a text field (like google search) in a file that there is other stuff you don't want to execute too.
If you are under some mvc then you have controller check this out and make sure that only the requested method is called (I've done it successfully). So it is easier controlled under an mvc, all things are in classes...
If not under mvc then I guess you have to implement something like controller in order to call only the methods you like. However there is a conition that should be espected, no code should be found out of classes cause it would be executed on "include", it would go like this:
file ajax handler
1.Check if an ajax call
2.if check false return;
3.if true then get the name of the class file
4. call the desired method (or methods, you have an execution flow predefined during to your needs)
So it can be done. It is important not to execute code that is not supposed to be executed since then undesired results (or errors) would occur.
in ajax i use the current url as the action of the request but this
cause the re-load of the whole page.
Since you have your own mvc it could go like this index.php/rt=request/action where request=the name of the controller (which in the end is a class), and action is the name of the action (which in the end is a method inside the class-controller you are requesting) for example
mysite.com/rt=user/create
My point is that you don't care what the current url is, all you care is to call the right method(=action) of the right class(=controller).
The login class is istantiater in all pages because it check if a user
is logged;
I don't really understand this (when you say pages you mean php files?), whatever it is I suggest (if haven't done already) to follow the single entry point (no need to do this for ajax calls) where every request hits only to index.php like I showed you above. Then a few lines of code on the very top can do the login check.
And a last thing what kind of ajax is this that reloads all the page, this an example how I do ajax for autocomplete in a text field:
put this as it is in head-script-javascript to make the connection
var request = false;
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
or even better you can have it in a separate file and include it wherever you need it
then I use a function to do the asunchronous call, what I am doing is similar to your needs because I too get data from html and pass it to php (read the comments) and then execute sql.
function getMatch()
{
//get the form values, I have one value here, you get as need as many as you need
var str = document.getElementById("categ_name").value ;
var url = "internal.php";//php file to execute
//now pass the html form parameters to php
//do you see here controller is defined, it is named asynch
//then see the action (method of controller class) it is called getMatch
//then see how I pass the html form data with str, it is the string to match
//comcateg is the mysql table to get the match
var params = "rt=asynch/getMatch&data=" + (str)+"&from=comcateg";
request.open("POST", url, true);//use post for connect harder to attack, lots of data transfer
//Some http headers must be set along with any POST request.
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded;charset=utf-8");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = updatePage;
request.send(params);
}////////////////////
Then when the answear will be back this function will be called because we defined so above in the code
function updatePage() {
if (request.readyState == 4) {
if (request.status == 200)
{
//test
var r=request.responseText.split("$$");
alert(r[1]);
}
else{
//alert("status is " + request.status);
}
}
}
I think now you can do it without problem, remeber whatever would be echoed by php even errors all of them will come back in the request.responseText. This is a tutorial among others about mvc that I like, https://sites.google.com/site/mhabipi/php-reading-material/superMVC.htm?attredirects=0&d=1 it's written by Kevin Waterson but sadly phpro.org does not work anymore.

javascript with XMLHttpRequest's open method: using post and its parameters

Users of my website will, ideally, be sending a few hundred posts to a db server over the course of about an hour (basically its an online-experiment). The experiment is implemented in js, so I'm trying to use an XMLHttpRequest object to post the data the script collects.
The thing I'm uncertain about is how to use the POST parameter. I want to set about 8 different key/value pairs to the $_POST variable so it can be accessible to a .php page for processing before sent to the db server. I'm not interested in retrieving any information from the server itself, only sending it (which is why, and I'm not sure whether it's the correct approach, I'm setting the readyState conditional to '1'/open).
Here's the script I'm working with at the moment:
function postData(dataList) {
var xmlhttp = new XMLHttpRequest();
var processingUrl = "process_exercise_data.php";
var POSTBody = "";
POSTBody+="block_type="+encodeURIComponent(dataList[0]);
POSTBody+="&block_number="+encodeURIComponent(dataList[1]);
POSTBody+="&trial_type="+encodeURIComponent(dataList[2]);
POSTBody+="&trial_number="+encodeURIComponent(dataList[3]);
POSTBody+="&input_value="+encodeURIComponent(dataList[4]);
POSTBody+="&output_value="+encodeURIComponent(dataList[5]);
POSTBody+="&prediction_value="+encodeURIComponent(dataList[6]);
POSTBody+="&error="+encodeURIComponent(dataList[7]);
xmlhttp.open("POST",processingUrl,true);
if (xmlhttp.readyState==4) {
xmlhttp.send(POSTBody);
}
}
The main goal is to send the key/value pairs to the .php page using POST while remaining on the current page(simple AJAX request, if I'm not mistaken). Any comments or suggestions are very appreciated!
Remember, all I'm trying to accomplish is having the user, when he/she acts in a certain way under a certain condition (outside of the scope of this function), to call this function and POST this data to the server. A server response text isn't needed.
EDIT:
Now my question is this: Will I still be able to access the $_POST array in at the processing php page? Here's an example:
$block_type = $_POST['block.type'];
You don't want to set request headers. What you want is to send request body along. And the body should be like
'block_type='+encodeURIComponent(dataList[0])+'&block_number='+encodeURIComponent(dataList[1])
etc. Guess you got the idea. Body is what you pass to the send() method of XMLHTTPRequest object.
Consider using jQuery, it will make your task so much easier. Using the jQuery.post method you only have to provide the data hash, you don't have to worry about serialization, correct escaping or readyState.
You must call send before readyState will change.
Replace
xmlhttp.open("POST",processingUrl,true);
if (xmlhttp.readyState=4) {
xmlhttp.send(POSTBody);
}
with
xmlhttp.open("POST", processingUrl, false);
xmlhttp.send(POSTBody);
If you want to handle a response, add define xmlhttp.onreadystatechange:
xmlhttp.open("POST", processingUrl, false);
xmlhttp.onreadystatechange = function () {
if (this.readyState === 4) {
// handle response
}
};
xmlhttp.send(POSTBody);
Edit: I would also like to mention that = is not the JavaScript equality operator, it's the assignment operator. Use === for equality checking and == for type-converting equality checking.

Categories