Passing JavaScript values to PHP file using XHR call - javascript

I have a PHP file on a server that needs to take dynamic values from client-side use on a web page in order to query my database. The user will click a link which (as well as directing the user to a new tab) takes the document location string that the link is connected to. I am currently trying to pass these values to the server side code using jQuery/AJAX and an XHR call, but when I run it, it seems that the PHP does not execute properly. Here is the JavaScript code:
// Clicking the link
$('a.docs').on('click', function(){
// Getting the values needed for the query from existing table
var theData = subtable.row($(this).parents('tr')).data();
// The document string
var thedoc = theData[7];
// Pass the document value to the PHP file on the server
$.post('https://example.com/TEST/dashboard/change.php', {
document: thedoc
});
// Make XHR call to execute the PHP file on the server
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://example.com/TEST/dashboard/change.php", true);
xhr.send();
});
As you can see, I try to send the value of thedoc to the file on the server before making the GET XHR call. Here is the what PHP code on the server does:
<?php
// The line that grabs the document variable being passed
$document = $_POST['document'];
// ... MySQL query stuff using $document as parameter...
?>
When I test this and click the link on the webpage, the JavaScript correctly grabs the document link variable, it's just the passing that has not been working. Any ideas on what I am doing incorrectly?

I cannot comment :(
I agree with jorgonor1.
You are performing 2 separate requests to your server.
The first. You are sending data to the server with JQUERY in the section $.POST(...). And from the sample code, ignore the results.
Then secondly, you perform a clean request of the generic page with the xhr request.
If you use $.POST(), and want to perform something with the result from the server try:
$.post('https://example.com/TEST/dashboard/change.php', {document: thedoc}, function(result){
//do something with the data returned form the server, server response stored in "result" variable
});
See the example on W3Schools

if you want to use jQuery, just try
let data = form.serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
or if you want to use xhr, you need to send the data as key/value pair string:
let data = "document=thedoc"

Related

How to soft reload page [duplicate]

I have a website where I need to update a status.
Like for a flight, you are departing, cruise or landed.
I want to be able to refresh the status without having my viewers to have and reload the whole page. I know there is a way to do it with AJAX and jQuery, but I don't have any understanding of how that works. I also don't want them to have and click a button.
If anybody knows how that would be done I much appreciate it!
This is typically achieved with a technique called AJAX. This technique loads data asynchronously (in the background) so it can update your content without needing to reload the page.
The easiest way to implement AJAX is with the jQuery load() method. This method provides a simple way to load data asynchronous from a web server and place the returned HTML into the selected element. The basic syntax of this method is: $(selector).load(url, data, complete); where the arguments are:
selector the existing HTML element you want to load the data into
url a string containing the URL to which the request is sent
data (optional) a plain object or string that is sent to the server with the request
complete (optional) a callback function that is executed when the request completes
The required URL parameter specifies the URL of the file you want to load.
The optional data parameter allows you to specify data (i.e. key/value pairs) that is sent to the web server along with the request. The optional complete parameter can be used to reference a callback function. The callback is fired once for each selected element.
A visualisation:
A simple example of using load(), where we load data dynamically when a button is pressed:
DEMO
// no need to specify document ready
$(function(){
// optional: don't cache ajax to force the content to be fresh
$.ajaxSetup ({
cache: false
});
// specify loading spinner
var spinner = "<img src='http://i.imgur.com/pKopwXp.gif' alt='loading...' />";
// specify the server/url you want to load data from
var url = "http://fiddle.jshell.net/dvb0wpLs/show/";
// on click, load the data dynamically into the #result div
$("#loadbasic").click(function(){
$("#result").html(spinner).load(url);
});
});
If you don't want to use the jQuery library, you can also use plain Javascript. Loading content is slightly more difficult that way. Here is an example of how to do it with javascript only.
To learn more about AJAX, you can take a look at https://www.w3schools.com/xml/ajax_intro.asp
Suppose you want to display some live feed content (say livefeed.txt) on you web page without any page refresh then the following simplified example is for you.
In the below html file, the live data gets updated on the div element of id "liveData"
index.html
<!DOCTYPE html>
<html>
<head>
<title>Live Update</title>
<meta charset="UTF-8">
<script type="text/javascript" src="autoUpdate.js"></script>
</head>
<div id="liveData">
<p>Loading Data...</p>
</div>
</body>
</html>
Below autoUpdate.js reads the live data using XMLHttpRequest object and updates the html div element on every 1 second. I have given comments on most part of the code for better understanding.
autoUpdate.js
window.addEventListener('load', function()
{
var xhr = null;
getXmlHttpRequestObject = function()
{
if(!xhr)
{
// Create a new XMLHttpRequest object
xhr = new XMLHttpRequest();
}
return xhr;
};
updateLiveData = function()
{
var now = new Date();
// Date string is appended as a query with live data
// for not to use the cached version
var url = 'livefeed.txt?' + now.getTime();
xhr = getXmlHttpRequestObject();
xhr.onreadystatechange = evenHandler;
// asynchronous requests
xhr.open("GET", url, true);
// Send the request over the network
xhr.send(null);
};
updateLiveData();
function evenHandler()
{
// Check response is ready or not
if(xhr.readyState == 4 && xhr.status == 200)
{
dataDiv = document.getElementById('liveData');
// Set current data text
dataDiv.innerHTML = xhr.responseText;
// Update the live data every 1 sec
setTimeout(updateLiveData(), 1000);
}
}
});
For testing purpose: Just write some thing in the livefeed.txt - You will get updated the same in index.html without any refresh.
livefeed.txt
Hello
World
blah..
blah..
Note: You need to run the above code on the web server (ex: http://localhost:1234/index.html) not as a client html file (ex: file:///C:/index.html).
You can read about jQuery Ajax from official jQuery Site:
https://api.jquery.com/jQuery.ajax/
If you don't want to use any click event then you can set timer for periodically update.
Below code may be help you just example.
function update() {
$.get("response.php", function(data) {
$("#some_div").html(data);
window.setTimeout(update, 10000);
});
}
Above function will call after every 10 seconds and get content from response.php and update in #some_div.
If you want to know how ajax works, it is not a good way to use jQuery directly. I support to learn the native way to send a ajax request to the server, see something about XMLHttpRequest:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://some.com");
xhr.onreadystatechange = function () {}; // do something here...
xhr.send();

How to pass a JavaScript array as parameter to URL and catch it in PHP?

I have an array in JS and I am trying to pass it as parameter to URL and catch it in PHP but I cant get to understand how to do it:
var trafficFilterHolder = ["roadworks","snow","blocking"];
var filters = encodeURI(JSON.stringify(trafficFilterHolder));
FYI: I am using windows.fetch for posting.
in PHP:
$trafficFilters = $_GET["trafficFilters"];
$obj = json_decode($trafficFilters);
var_dump($obj);
You are passing the data to php with fetch() intead of ajax, so the alternative of my first answer to do the same with the fetch() is:
var trafficFilterHolder = ["roadworks","snow","blocking"];
var trafficFilterHolderJoin = trafficFilterHolder.join(); // comma-separeted format => "roadworks,snow,blocking"
Now add the trafficFilterHolderJoin variable to the traffic query of the URL of your fetch(), like:
fetch('script.php?traffic=' + trafficFilterHolderJoin)
Then in your php script file you will convert the comma-separeted format to php array format using the explode function:
$traffic = explode(",", $_GET['traffic']);
It's quite simple, you are passing these data to php with ajax, correct?
First of all, you are creating the javascript array incorrectly:
var trafficFilterHolder = [0: "roadworks", 1: "snow", 2: "blocking"];
Don't use brackets to create arrays with keys, use this format instead:
var trafficFilterHolder = {0: "roadworks", 1: "snow", 2: "blocking"};
Now, in the ajax, just add the array in the data:
$.ajax({
data: { trafficFilters: trafficFilterHolder }
});
All demands to the server are executed as an http requests. Ther are two types of HTTP requests - GET and POST.
https://www.w3schools.com/tags/ref_httpmethods.asp
What you're describing is called GET request. With GET request the parameters are passed via the address bar. For making an http request you have two options.
The direct HTTP GET request.
For this you need simply open a new page with
window.location.href = 'http://your_site.com/file.php?name1=value1&name2=value2'
This will open a new page in your browser and pass a request with your parameters.
An Ajax HTTP GET request.
You have a lot of options here:
an old-fashion way with xmlHttpRequest object
a modern fetch API with promises
third-part libraries like jQuery.ajax etc.
AJAX request can send and receive information from the server (either in GET or POST request) without renewing the page. After that the result received can be managed with your javascript application however you want.
Hope, it makes more clear for you. You can search about all this technologies in the google. This is the way how to exchange data from front-end to back-end.
Try using ajax and pass that array and retrieve values at the PHP end.
var filters = encodeURI(JSON.stringify(trafficFilterHolder));
$.ajax({
type: "POST",
url: "test.php",
data: {data : filters},
cache: false,
success: function(){
alert("OK");
}
});

How do I reload a page without the user noticing?

I've been trying to figure out how to reload a page and pull dynamic info from a server without users noticing the page has been reloaded. For instance, if I want to create a 'live' message board system when the board updates every time other people make a comment or post a message.
I noticed that Javascript has a boolean function .reload() that when set to false reloads the page from the cache and when set to true reloads the page from the server, but from what it looks like, the function does something similar to reloading the browser. Is there another way do what I'm trying to do?
Something like this...
function getContent()
{
return new Promise(function(resolve, reject){
var url = "http://yourendpoint.ext"
$.ajax({
url: url,
success: function(data)
{
resolve(data);
},
error: function(err)
{
reject(err);
}
});
}));
}
// Usage
getContent()
.then(function(data)
{
$('#some-element').html(data);
});
Are you sure you really want to do an reload?
What you could do is make an AJAX Request to the server and display the result, without even reloading the Page. I would recommend using jQuery for this, just out of comfort.
AJAX stands for Asynchronous JavaScript and XML. In a simple way the process could be:
User displays page, a timer is started
Every 10s (or 20s or whatever) you do an AJAX Request using JavaScript, asking the server for new data. You can set a callback function that handles the result data.
Server answers with result data, your callback function inserts the new data.
Code Example (taken from jQuery Docs):
$.ajax({
method: "POST",
url: "target.php",
// Data to be sent to the server
data: { name: "John", location: "Boston" },
// success will be called if the request was successfull
success: function( result ) {
// Loop through each Element
$.each(result.newElements, function(index, value) {
// Insert the Element to your page
$('.classOfYourList').append(value);
}
});
});
Just set the proper endpoint of your server as the target and insert whatever you want to do in the success function. The function will get an answer containing whatever you sent to it from the server. More Information in the jQuery Documentation:
You can Achive what you want using AJAX. you can use ajax with either javascript or jquery. You can load the content you want dynamically without reloading the entire page. here is a quick example.
Here is a <div> with id load where your content will be loaded.
<div id="load">Loaded Content:</div>
<button id="load_more">load more</button>
JQuery to request for the data, where getdata.php is the php file which will send data you want to display.
<script type="text/javascript">
$(document).ready(function(){
$("#load_more").click(function (){
$.post("getdata.php", {variable1:yourvariable, variable2:ifneeded},function(data){
//data is the string or obj or array echoed from getdata.php file
$('#load').append(data); //putting the data into the loaded div.
}
});
});
});
</script>`
finally getdata.php file
<?php
//fetch data from Databas eif needed. or echo ut what you want to display in the div.
echo "This is a small example of using JQuery AJAX post request with PHP.";
?>
Hope that helps!

AJAX to retrieve and store object in a variable

I have two files. One is index.php where the user clicks and invokes an AJAX request. The second one is process.php whic sends back data back to index.php.
function AjaxResponse() {
var myData = 'connect=1';
jQuery.ajax({
type: "POST",
url: "process_facebook.php",
dataType: "text",
data: myData,
success: function(response){
$result = response;
window.location.replace("http://myurl.com");
}
the $result doesn't here. I can do like this $('#something').html(response); but can't store the value returned in a variable.
Kind of hard to tell what you would like here. But I'm going to guess that you want to store the result of the ajax call into a variable in php. So I'll remind you the order in which things proceed for a server/client web interaction.
Server processing ==> client side processing ==> repeat.
The only real way to store that value in a variable after receiving the data from your ajax request would be to submit a form and have your data serialized into JSON or xml and then parse it.
Alternatively, your process_facebook.php file could insert your data into a database and you could return a key to your callback, and either create a cookie on the users browser of that key, or have the browser pass that key as a get variable to your index.php (sanitize it so that a malicious user can't just go entering whatever they want), and then do what you want with that information.
To clarify, the session is not stored on the browser, it is stored on the server, you cannot set any session variables on the browser unless you did it in an ajax call to the server.

how to send asynchronous request to php page using jquery ajax

i am new to web development creating a kind of social networking website for college project. I want to include update the messages count in the message menu every time there is a new msg in the database for the user(like facebook message menu on homepage)
But it's frustrating learning ajax, however after searching on web and reading some topics from some books I came to the solution that i can make an $ajax call in my js file in the homepage and send data ('name'=>'user') stored in javascript cookie that i have created on loading of home page after the user login, to a php file which will search across the recent_msg table in database to fetch the recent message for the logged in user if any after fetching the php file will create the html file with code snippet and further another jquery code will append that snippet from file to the message list menu.
the PHP part is not the problem but how can i send the username to the php file using jquery ajax api, here is the code what i think i can apply but i am doubtful in that if this is the correct way
$(document).ready(function{
setInterval ( function()
{
var usr = getCookie("name");
$.ajax ( {
url: '/phpScripts/recent_msg.php',
type: 'POST',
data: usr,
success: function(data){
}
} );
},10);
});
what is the purpose of success function in the code?
data needs to be in the form of an object / key-value-pair (EDIT: or if a string, as a valid querystring). data: { name: usr }. However, since it's in a cookie, your PHP page will have direct access to that cookie. It's safer to let your session cookie tel the PHP page who the user is instead of relying on an AJAX call to tell the PHP page who it is.
http://php.net/manual/en/features.cookies.php
So I'd drop data from your AJAX call altogether, and in your PHP page, use $_COOKIE["name:"]
Then whatever HTML gets passed back from the PHP page will arrive in the data call. If it's HTML, then simply add it to your HTML to some message div, such as.
<div id="recent-messages"></div>
<script type="text/javascript">
$(document).ready(function{
setInterval ( function()
{
var usr = getCookie("name");
$.ajax ( {
url: '/phpScripts/recent_msg.php',
type: 'POST',
data: usr,
success: function(data){
$('#recent-messages').html(data);
}
} );
},10);
});
</script>
The success function executes whenever your ajax call completes successfully. This means that the page actually exists and no server-side errors occurred on the page. The variable data will contain whatever information is returned from the page on the sever /phpScripts/recent_msg.php. Generally this is either json or xml, but it entirely depends on your implementation of recent_msg.php.
If the user has to log in that means you have to have created a session. In that case you can store the logged in user's information such as their name in $_SESSION on the server and there is no need to store it as a cookie. Since $_SESSION is already on the server, there is no need to send that data via ajax in any case.

Categories

Resources