How to call php function from JavaScript using Ajax? - javascript

In my Wordpress site, I want to create a dropdown menu with all the tags, but since it has more then 7.000, it needs to load only after the user click. I now it is only possible using Ajax, and I have started, but not accomplished yet.
http://jsfiddle.net/7kf1r9vw/2/
In this Fiddle, after the click, this javascript file is loaded:
/echo/js/?js=hello%20world!.
The second example in Fiddle is just to show my actual code. I want that the results populated by the php funcion only starts after the user click.
But I don't know how to change it to a PHP function. Also, is it possible to add plain PHP script in the output or only with it embedded in a file?

As Draco18s said, in your case, Javascript is executed client-side and PHP is executed server side.
In this case what you can do is a request to the server using Ajax.
For example, if you have the following html:
<select name="tag-dropdown" id="selectTags">
<option value="#">Select an artist</option>
</select>
You can use Ajax to make a POST request to a PHP script:
$( document ).ready(function() {
$.ajax({ url: 'merge2.php',
data: {operationName: "tagsNames"},
type: 'post',
success: function(output) {
tagNamesres = JSON.parse(output);
jQuery.each(tagNamesres, function(name, val) {
$("#selectTags").append('<option value="'+val+'">'+name+'</option>');
});
}
});
});
The PHP script can contain something like:
<?php
if (isset($_POST['operationName']) && !empty($_POST['operationName']) && $_POST["operationName"]=="tagsNames") {
$resultarray = array();
$resultarray["tagName1"] = "tagValue";
$resultarray["tagName2"] = "tagValue2";
echo json_encode($resultarray);
return;
}
?>
In order to return something from the PHP function you need to print or use echo.
This is just an example so you could start working with this :)
For more information about how Ajax request works, read this http://thisinterestsme.com/simple-ajax-request-example-jquery-php/

Your question appears to be "how do I call a php function on the server from my browser javascript code". In your code, you have the following function where the first parameter is the server side request:
function getSuccessOutput() {
getRequest(
'/echo/js/?js=hello%20world!', // demo-only URL
drawOutput,
);
return false;
}
To change that to call a server php routine, you would change '/echo/js/?js=hello%20world!' to the url on your server you want to have executed: e.g. '/myPHPFolder/someRoutine.php' . The results will be delivered back to your req object.
In your initial html file (e.g. index.html, or where ever you start your flow), include the onload option on the body tag:
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="yada yada yada">
<meta name="author" content="you">
<title>title for browser tab</title>
</head>
<body class="tutorial" onLoad="initPage()">
<select id="optionList"></select>
</body>
</html>
This tells the browser to run the "initPage()" function with no parameters. The initPage() function then issues an async call and loads up your data, perhaps saving it to a local variable in the process.
function initPage()
{
$('#optionList').empty(); // this ensures that you don't duplicate the info in the select list.
$.when($.get('/myPHPFolder/someRoutine.php').done(function(res)
{ // if of interest, save the results to a cookie or variable.
// you could also include a check to see if the data has already been downloaded.
// This is a 'happy path' example, which does not include error checking from the host
// build the optionList select HTML element
for (let each in res)
{(function(_idx, _arr)
{
// append the correct value to the select list.
// this example is based on returning a JSON object with an
// element called "id" which has the value I want to display in the options list
$('#optionList').append('<option value="'+_arr[_idx].id+'">' +_arr[_idx].id+'</option>');})(each, res);
}
// create a function to execute when the user selects a different buyer
$('#buyer').on('change', function() { /* do something useful here */ });
}
}

Related

How to save a dynamic html page which displays results of tests written in javascript

I have a dynamic html page index.html.
When I hit that page in the browser it runs some tests which is written in JS and generates dynamic results on the page. On every reload it writes fresh data on index.html page.
Now I want to save this html page into another html page so that I can save the results and view later.
One method of doing it would be to write the dynamic results to an element on the page, and then save the contents of that via an ajax call.
For example create an element with an ID results on your index.html page:
<div id="results"></div>
Write the dynamic results to this element. I'm going to write the js in jquery syntax for brevity; but you can adapt this to vanilla js:
$('#results').html(data); // data is the dynamic content
Now you can grab the data inside #results and make an ajax call to a script which could write it to a HTML file:
$(function() {
$.ajax({
url: '/save-data.php', // script to save your data
method: 'POST',
cache: false,
data: {
results: $('#results').val() // the html inside #results
}
});
});
Your save-data.php script would read the contents in the POST variable ($_POST['results']) and then write it to a file, e.g.
<?php
$fp = fopen('data.html', 'w');
fwrite($fp, $_POST['results']);
?>
This is merely to illustrate the concepts required. You need to take care of security, particularly sanitising the POST data.
The js to make the ajax call will execute on page load of index.html. You could adapt this to work when the user presses a button or takes some other action. You may also want to look at the .done() method in jquery because this is where you could perform checks to see if save-data.php has actually saved the data and display an appropriate message.
For example save-data.php might return a JSON response on successfully saving the data:
echo json_encode(['result' => 'success']);
You could then use the .done() callback to display an appropriate message to the user when the data has been saved:
// previous ajax code
// ...
.done(function(response) {
if (response.result == 'success') {
// write message to the page to say it's been done successfully
// You will need an element with the class .status to hold the message, e.g. <span class="status"></span>
$('.status').html('Successfully saved your page').
}
});

How you can save appends to variables an then convert them to php so you can save them in a database?

<html>
<head>
<meta charset="utf-8">
<title>Test page for Query YQL</title>
<link rel="stylesheet" href="http://hail2u.github.io/css/natural.css">
<!--[if lt IE 9]><script src="http://hail2u.github.io/js/html5shiv.min.js"></script><![endif]-->
</head>
<body>
<h1>Test page for Query YQL</h1>
<div id="content"></div>
<input type="button" name="bt1" value="click" onclick="pesquisa()">
<form name="s2">
<input type="text" name="s1">
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="jquery.query-yql.min.js"></script>
<script type="text/javascript">
function pesquisa(){
$(function () {
var t = $('#content').empty();
var url= document.s2.s1.value;
var statement = 'select * from feed where url="'+url+'"';
$.queryYQL(statement, function (data) {
$('<h2/>').text('Test: select * from feed').appendTo(t);
var r = data.query.results;
var ul = $('<ul/>');
$.each(r.item, function () {
$('<li/>').append(this.title).appendTo(ul);
$('<li/>').append(this.link).appendTo(ul);
<?php
$titulo = "<script>document.write(titulo);</script>";
$site = "<script>document.write(site);</script>";
//echo $titulo;
//echo $site;
?>
});
ul.appendTo(t);
});
});
};
</script>
</body>
</html>
How can you save the this.title and the this.link values into 2 different variables an then call them into php so you can insert the data into a DB?
It's just a simple YQL query to search on rss feeds.
After doing the query, I want the results to be saved in a database, but I can't discover how to do that.
First of all, you have to understand that you are working on a Client-Server architecture.
This means:
Let's say that this file you are showing us is called "TestYQL.php" (because you did not say the name of it). This file is executed by php (server side), which reads line by line the contents of it, and generates another new file from the original. For educational purposes, let's say the generated file is called "GeneratedTestYQL.html". This file no longer has any php code inside, since it is directly html and js flat. It knows nothing about php. So there are no php functions, variables, nothing. This last file is the one that reaches the client, and the code is executed by a web browser like Chrome, Firefox, etc.
In your case, the file "TestYQL.php" all you have of php is what is inside the <? Php ....?> Tags. With php you creates 2 variables, each with a tag inside, but without any purpose since they are not used in any way. So, the generated "GeneratedTestYQL.html" file is the same as the original, but without the lines inside the <? Php ...?>.
This means that: The contents of the variables that you use in PHP can be sent to the browser, because with PHP you will generate the file that will be executed in the browser.
Now, when the file "GeneratedTestYQL.html" arrives, the browser starts to show all the contents of the file, it generates the form in which, when you click the button, executes the function pesquisa() and now starts javascript (JQuery) bringing data of the feeds, and for the first time, these variables "this.title" and "this.link" begin to exist in javascript.
Since there is no such thing as php here, you can NOT access those variables from php.
So, how to save that data in a DB?, well, the common way is to send all the data you want from the browser, to the server, then the server sees what to do with that data. To send data from the browser to the server, you do it by making GET or POST requests to a php file from the server (preferably another file, let's say it will be called "saveFeeds.php").
Data can be sent with a GET request, but it is semantically incorrect since GET means you want to fetch data from the server. So to send that data to the server, you will have to make a POST request from the browser, which is more appropriate.
There are now 2 simple ways to make a POST request. The first and most common of these is from a form in the browser, the other way is using Ajax.
How to do it from a form?
Currently in your code, you have already put a form (That is called "s2"), although currently the same is not necessary, but leave that now.
If you wanted to send the data through a form, you should do 2 things. First and most obvious, create the form; second, the data received from the internet (title and link of feed), send them to the server.
Assuming you fetch data from a single feed per url, and the designated file in charge of receiving the request will be "saveFeeds.php". So, you could create a form like the following after the previous one:
<Form class = "sender" action = "saveFeeds.php" method = "post">
  <Input type = "hidden" name = "title" value = ""> <br>
  <Input type = "hidden" name = "link" value = ""> <br>
  <Input type = "submit">
</ Form>
Then you need to put the feed data inside the form, because, at this moment, you can't send anything. You could add a function like:
Function appendFeedToForm (title, link) {
  Var form = $ (". Sender");
  Form.title.value = title;
  Form.link.value = value;
}
And then call it from inside the $ .each of the result as
AppendFeedToForm(this.title, this.link);
The second case, the easiest way to make a request to the same file using Ajax is with a JQuery shortcut:
$.post("saveFeeds.php", r.item);
If you are interested in validations, you can take a look at the JQuery documentation. The important thing about ajax requests is that you can send all the data you want without having to force you to reload the page. Therefore, you can send as many feeds as you want in the same way you would send one.
Now with the data sent from the client to the server, it is necessary to handle the reception of the data. Currently we were pointing all the data to the file "saveFeeds.php", so, now, finally we can put the content from javascript. To access them, simply in that file, you should check the fields:
$ _POST ['title'] // This names are from input names of form
$ _POST ['link'] // or properties sended through Ajax
So, here, you have tp prepare the connection to your database and save those parameters. Currently you did not mention which database engine you are using, so, for this moment, I'll shorten the answer here.
Note: I was not giving you the best practices to solve your problem, but rather the minimum necessary.

How to pass data from JavaScript to PHP and then on to MySQL [duplicate]

This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 2 years ago.
How do I pass have a Javascript script request a PHP page and pass data to it? How do I then have the PHP script pass data back to the Javascript script?
client.js:
data = {tohex: 4919, sum: [1, 3, 5]};
// how would this script pass data to server.php and access the response?
server.php:
$tohex = ... ; // How would this be set to data.tohex?
$sum = ...; // How would this be set to data.sum?
// How would this be sent to client.js?
array(base_convert($tohex, 16), array_sum($sum))
Passing data from PHP is easy, you can generate JavaScript with it. The other way is a bit harder - you have to invoke the PHP script by a Javascript request.
An example (using traditional event registration model for simplicity):
<!-- headers etc. omitted -->
<script>
function callPHP(params) {
var httpc = new XMLHttpRequest(); // simplified for clarity
var url = "get_data.php";
httpc.open("POST", url, true); // sending as POST
httpc.onreadystatechange = function() { //Call a function when the state changes.
if(httpc.readyState == 4 && httpc.status == 200) { // complete and no errors
alert(httpc.responseText); // some processing here, or whatever you want to do with the response
}
};
httpc.send(params);
}
</script>
call PHP script
<!-- rest of document omitted -->
Whatever get_data.php produces, that will appear in httpc.responseText. Error handling, event registration and cross-browser XMLHttpRequest compatibility are left as simple exercises to the reader ;)
See also Mozilla's documentation for further examples
I run into a similar issue the other day. Say, I want to pass data from client side to server and write the data into a log file. Here is my solution:
My simple client side code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<title>Test Page</title>
<script>
function passVal(){
var data = {
fn: "filename",
str: "this_is_a_dummy_test_string"
};
$.post("test.php", data);
}
passVal();
</script>
</head>
<body>
</body>
</html>
And php code on server side:
<?php
$fn = $_POST['fn'];
$str = $_POST['str'];
$file = fopen("/opt/lampp/htdocs/passVal/".$fn.".record","w");
echo fwrite($file,$str);
fclose($file);
?>
Hope this works for you and future readers!
I'd use JSON as the format and Ajax (really XMLHttpRequest) as the client->server mechanism.
Using cookies is a easy way. You can use jquery and a pluging as jquery.cookie or create your own.
Using Jquery + jquery.cookie, by example
<script>
var php_value = '<?php echo $php_variable; ?>';
var infobar_active = $.cookie('php_value');
var infobar_alert = any_process(infobar_active);
//set a cookie to readit via php
$.cookie('infobar_alerta', infobar_alerta );
</script>
<?php
var js_value = code to read a cookie
?>
I've found this usefull Server-Side and Hybrid Frameworks:
http://www.phplivex.com/
http://www.ashleyit.com/rs/
I've been using Ashley's RSJS Script to update values in HTML without any problem for a long time until I met JQuery (ajax, load, etc.)
There's a few ways, the most prominent being getting form data, or getting the query string. Here's one method using JavaScript. When you click on a link it will call the _vals('mytarget', 'theval') which will submit the form data. When your page posts back you can check if this form data has been set and then retrieve it from the form values.
<script language="javascript" type="text/javascript">
function _vals(target, value){
form1.all("target").value=target;
form1.all("value").value=value;
form1.submit();
}
</script>
Alternatively you can get it via the query string. PHP has your _GET and _SET global functions to achieve this making it much easier.
I'm sure there's probably more methods which are better, but these are just a few that spring to mind.
EDIT: Building on this from what others have said using the above method you would have an anchor tag like
<a onclick="_vals('name', 'val')" href="#">My Link</a>
And then in your PHP you can get form data using
$val = $_POST['value'];
So when you click on the link which uses JavaScript it will post form data and when the page posts back from this click you can then retrieve it from the PHP.
You can pass data from PHP to javascript but the only way to get data from javascript to PHP is via AJAX.
The reason for that is you can build a valid javascript through PHP but to get data to PHP you will need to get PHP running again, and since PHP only runs to process the output, you will need a page reload or an asynchronous query.
the other way to exchange data from php to javascript or vice versa is by using cookies, you can save cookies in php and read by your javascript, for this you don't have to use forms or ajax

On button click reload a php pull from mysql database without page reload

I've got a .php page where I display table from MySQL database using PHP based on cookie value.
On this page, without page reload I'm able to change cookie data with a button click:
$(document).ready(
function(){
$(".button").click(function () {
Cookies.remove('cookie');
Cookies.set('cookie', 'value', { expires: 7 });
});
});
How to refresh mysql SELECT in the same click functionality so the data inside table reloads without page reloading?
I've got my php data in:
<div id="refresh-table">
<?php include 'pull-from.php'; ?>
</div>
I have read all over the place I have to use AJAX - but I cannot set it up according to all posts i've been through. I would really appriciate your support.
You need to add some code to your pull-from.php file (or create another file that uses it to get the data) that can accept parameters from the AJAX call and return a response, preferably JSON. This is basically your web service.
Below is a barebones example of what the php basically needs to do. i included an html page that fetches data from the web service and displays it.
<?php
$criteria = $_POST['criteria'];
function getData($params) {
//Call MySQL queries from here, this example returns static data, rows simulate tabular records.
$row1 = array('foo', 'bar', 'baz');
$row2 = array('foo1', 'bar1', 'baz1');
$row3 = array('foo2', 'bar2', 'baz2');
if ($params) {//simulate criteria actually selecting data
$data = array(
'rows' => array($row1, $row2, $row3)
);
}
else {
$data = array();
}
return $data;
}
$payload = getData($criteria);
header('Content-Type: application/json');//Set header to tell the browser what sort of response is coming back, do not output anything before the header is set.
echo json_encode($payload);//print the response
?>
The HTML
<!DOCTYPE html>
<html>
<head>
<title>Sample PHP Web Service</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<script>
$(document).ready(function(){
alert("Lets get started, data from the web service should appear below when you close this.");
$.ajax({
url: 'web-service.php',
data: {criteria: 42},//values your api needs to query data
method: 'POST',
}).done(function(data){
console.log(data);//display data in done callback
$('#content').html(
JSON.stringify(data.rows)//I just added the raw data
);
});
});

Refresh Part of Page (div)

I have a basic html file which is attached to a java program. This java program updates the contents of part of the HTML file whenever the page is refreshed. I want to refresh only that part of the page after each interval of time. I can place the part I would like to refresh in a div, but I am not sure how to refresh only the contents of the div. Any help would be appreciated. Thank you.
Use Ajax for this.
Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.
Relevant function:
http://api.jquery.com/load/
e.g.
$('#thisdiv').load(document.URL + ' #thisdiv');
Note, load automatically replaces content. Be sure to include a space before the id selector.
Let's assume that you have 2 divs inside of your html file.
<div id="div1">some text</div>
<div id="div2">some other text</div>
The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.
You can, however, communicate between the server (the back-end) and the client.
What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.
Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.
setInterval(function()
{
alert("hi");
}, 30000);
You could also do it like this:
setTimeout(foo, 30000);
Whereea foo is a function.
Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.
A classic AJAX looks like this:
var fetch = true;
var url = 'someurl.java';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'fetch' : fetch // You might want to indicate what you're requesting.
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
$('#div1').html(res1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.
I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.
You need to do that on the client side for instance with jQuery.
Let's say you want to retrieve HTML into div with ID mydiv:
<h1>My page</h1>
<div id="mydiv">
<h2>This div is updated</h2>
</div>
You can update this part of the page with jQuery as follows:
$.get('/api/mydiv', function(data) {
$('#mydiv').html(data);
});
In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.
See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/
Usefetch and innerHTML to load div content
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"
async function refresh() {
btn.disabled = true;
dynamicPart.innerHTML = "Loading..."
dynamicPart.innerHTML = await(await fetch(url)).text();
setTimeout(refresh,2000);
}
<div id="staticPart">
Here is static part of page
<button id="btn" onclick="refresh()">
Click here to start refreshing every 2s
</button>
</div>
<div id="dynamicPart">Dynamic part</div>
$.ajax(), $.get(), $.post(), $.load() functions of jQuery internally send XML HTTP request.
among these the load() is only dedicated for a particular DOM Element. See jQuery Ajax Doc. A details Q.A. on these are Here .
I use the following to update data from include files in my divs, this requires jQuery, but is by far the best way I have seen and does not mess with focus. Full working code:
Include jQuery in your code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Create the following function:
<script type="text/javascript">
function loadcontent() {
$("#test").load("test.html");
//add more lines / divs
}
</script>
Load the function after the page has loaded; and refresh:
<script type="text/javascript">
$( document ).ready(function() {
loadcontent();
});
setInterval("loadcontent();",120000);
</script>
The interval is in ms, 120000 = 2 minutes.
Use the ID you set in the function in your divs, these must be unique:
<div id="test"></div><br>

Categories

Resources