How to set variable to external content? - javascript

So I have this code that uses JQuery to output a live calculation from data entered in a text field. It all works fine as seen below:
$(document).on('keyup', '#w_amount', function(){
// alert('pressed')
var totalcost= 11 * $(this).val()
$(".total_cost").html(totalcost);
})
and it's outputted here:
<span class=\"total_cost\" style=\"display: inline; vertical-align: inherit;\">0</span>
Currently the code takes whatever number is entered into the text field and multiplies it by 11. However what I want it to do is multiply it by the number located at the following url: https://www.eobot.com/api.aspx?coin=DOGE
There is just a number at that url nothing else i.e. 0.00014253
I'd appreciate any help you can give! Received a great response last time.
Thanks!

Because of Cross-origin policy, you can't make an ajax request to it. Instead I would recommend using curl or something on your server and then either input that value into the page at load time, or make an ajax request to your server which would then make the request to that link.

Edit: as suggested by #Sukima: the data parameter renamed to url_figure to avoid declaring unnecessary variable.
Assuming that your jQuery script, HTML files are both hosted on the same server that has the figure (eobot.com) then here is how it could be done.
$(document).on('keyup', '#w_amount', function(){
// alert('pressed')
$.get( "https://www.eobot.com/api.aspx?coin=DOGE", function( url_figure) {
var totalcost= url_figure * $(this).val()
$(".total_cost").html(totalcost);
});
});

Well, I don't like to leave you at an "it's not possible" answer so here you go:
Name your file test.php and use it on a live server or on localhost
<?php
if( isset($_GET["getCoinValue"]) ){
$val = #file_get_contents("https://www.eobot.com/api.aspx?coin=DOGE");
exit ($val ? "$val" : "Could not retrieve data");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>GET DOGE</title>
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
W <input id="w_amount" type="text"><br>
* <input class="doge_value" type="text" readonly><br>
= <input class="total_cost" type="text" readonly>
</body>
<script>
$(function(){
var $dogeValue = $(".doge_value");
var $totalCost = $(".total_cost");
$("#w_amount").on('keyup', function(){
var thisValue = parseInt(this.value, 10);
$.ajax({
data : {"getCoinValue":true} ,
success : function( resp ){
$dogeValue.val( resp );
$totalCost.val( thisValue * resp );
},
error : function(x, e){ console.log(x, e); }
});
});
});
</script>
</html>
The trick is to fool AJAX that the result is on our server,
achieved by pulling the content from the external site using PHP and file_get_contents
On "input" AJAX contacts the same .php file using GET (jQ's AJAX defauly type).
PHP gets the content from the external URI to our server, and exits with a String response.
AJAX serves the response back from our server (without COP issues)
The result is than multiplied by the entered value.

Related

Unknown problem with (probably) POST method

This task is quite simple but I just can't seem to get it to work. What the outcome should be is explained in the picture below. I guess that there is some kind of a problem with POST in php, but I'm not sure. Do you see what's the problem that's causing this not to work?
Problem: No results are shown when there should be.
<?php
$conn = mysqli_connect("localhost", "root", "", "podaci");
if($conn === false){
die("Konekcija nije uspešna. " . mysqli_connect_error());
}
$number = $_POST['number'];
$result_array = array();
/* SQL query to get results from database */
$sql = "SELECT brojKartice, imeVlasnika, prezimeVlasnika, adresaVlasnika,
ostvareniBodovi, ostvareniPopust FROM podatak WHERE brojKartice = '".$number."' ";
$result = $conn->query($sql);
/* If there are results from database push to result array */
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
/* send a JSON encded array to client */
echo json_encode($result_array);
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<meta charset="UTF-8">
</head>
<body>
<div class = "container" >
<strong>Unesite broj kartice: </strong><input id="number" name="number" required/>
<input type="button" id="getusers" value="Provera"/> <br><br>
<div id="records"></div>
</div>
<script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
$(function() {
$('#getusers').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'provera.php',
data: {
number: $('#number').val()
}
});
});
});
$(function(){
$("#getusers").on('click', function(){
$.ajax({
method: "GET",
url: "provera.php",
}).done(function( data ) {
var result= $.parseJSON(data);
var string='<table width="100%"><tr><th>#</th><th>Korisnik</th><th>Adresa</th><th>Bodovi</th><th>Popust</th><tr>';
/* from result create a string of data and append to the div */
$.each( result, function( key, value ) {
string += "<tr> <td>"+value['brojKartice'] + "</td><td>"+value['imeVlasnika']+' '+value['prezimeVlasnika']
+ "</td><td>"+value['adresaVlasnika']+ "</td><td>"+value['ostvareniBodovi']+ "</td><td>"
+value['ostvareniPopust']+"</td> </tr>";
});
string += '</table>';
$("#records").html(string);
});
});
});
</script>
</body>
</html>
CREATE DATABASE podaci;
CREATE TABLE podatak (
brojKartice VARCHAR(10) NOT NULL,
imeVlasnika VARCHAR(20) NOT NULL,
prezimeVlasnika VARCHAR(30) NOT NULL,
adresaVlasnika VARCHAR(50),
ostvareniBodovi VARCHAR(10) NOT NULL,
ostvareniPopust VARCHAR(10) NOT NULL,
rokVazenja DATE NOT NULL
);
INSERT INTO podatak VALUES
('0123456','Đorđe','Anđelković',NULL,'15','150','2021-1-9'),
('6543210','Snežana','Bojović',NULL,'20','200','2021-5-3'),
('9876543','Goran','Stojadinović',NULL,'10','100','2021-9-7'),
('3456789','Bojana','Marković',NULL,'25','250','2021-12-15');
Welcome. Here are a few pointers to help you identify the source of the issue:
Is your browser making the HTTP requests that you expect? By glancing at your Javascript, you expect both a POST and a GET. If you are using Google Chrome, check Dev tools - Network
What HTTP requests is the server receiving? You can debug your PHP code by following the official debugging documentation and reading its comments. Especially:
<?php print_r($_POST); ?>
Is the server answering the data you are expecting? Check the HTTP verb (GET or POST) used to get the number (hint: line 8 of your code). Now check on which HTTP call (GET or POST) you put the Javascript callback to handle the server response.
Answer: your PHP code reads the number from the POST request, but your Javascript code only supports responses from the GET request.
Simplify your Javascript by moving the callback (the function block passed as argument of the .done() method) from the GET request to the POST request. Then delete the Javascript code dealing with the GET request.
Alternatively, replace $_POST with $_GET and remove the POST call.
First of all, you have two event handler for #getusers button. This doesn't make sense in the first place. Whenever you assign multiple event handler on a html element only the last one will trigger. In this case, it's only the ajax call with the GET method. And on your server side (php), this variable $number = $_POST['number']; will not have a value because the method was GET.
So to solve this you have two options I can think of:
#1. Move the first ajax call that you have where you have the POST request and then place it where you have the ajax call with GET method. In short, replace GET with POST event.
#2. Change your php code to use $_GET and update your ajax call for GET to adhere with the PHP change.
You can remove either of the event handler of your button and just bind only one.
Here is for a quick reference on javascript event handler and addEventListeners: https://gist.github.com/belmer/5e433aabbab24086af5c12ce0fb7323c
Best regards,

PHP Undefined POST variables and unable to execute INSERT function [duplicate]

I know there a fair few entries on SO and the web on this however I just can't get to work - any help would be appreciated.
So i have an array in Javascript which I'm trying to pass on to PHP.
I've got a little JS function to first POST it, so:
function sendToPHP() {
$.post("index.php", { "variable": toSearchArray });
}
Then down the page, I have the PHP:
<?php
$myval = $_POST['variable'];
print_r ($myval);
?>
*The prints just there for me to check.
Any ideas - fyi I'm using MAMP so its localhost:8888/index.php. Could this be causing issues in that the URL is not correct?
Thanks.
You have a misunderstanding about how ajax works. Although jquery makes it easy, it is still not automatic. You should just find a tutorial about ajax with jquery, but if you want to just send an array to php and see the output on screen, something like this would work:
index.php
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
//attach to the button a click event
$('#btn').click(function(){
//get the value from the textbox
var txt=$('#txt').val();
//if txt is blank, alert an error
if(txt == ''){
alert("Enter some text");
} else {
//send txt to the server
//notice the function at the end. this gets called after the data has been sent
$.post('catcher.php', {'text':txt}, function(data){
//now data is an object, so put the message in the div
$('#response').text(data.message);
}, 'json');
}
});
});
</script>
</head>
<body>
<input type="text" id="txt">
<input type="button" id="btn">
<pre id="response" style="overflow:auto;width:800px;height:600px;margin:0 auto;border:1px solid black;"> </pre>
</body>
</html>
catcher.php:
<?php
//if something was posted
if(!empty($_POST)){
//start an output var
$output = array();
//do any processing here.
$output['message'] = "Success!";
//send the output back to the client
echo json_encode($output);
}
It is better to use 2 files, one for the user to load that initiates the ajax call and one page to handle the ajax call. Sending an array works the same, just replace getting the textbox value with sending an array.
Instead of declaring variable toSearchArray as array. consider it an javascript object.
var toSearchArray = {}.
This is what happens when you open your page (index.php)
A GET request is issued to index.php and the content is returned. There are no values in the $_POST array so your print_r() line does nothing.
Javascript is executed that sends a POST request to index.php via AJAX. Note that this is an entirely new request, separate to the original GET. The $_POST array will be populated on this request however the response is discarded.
Hopefully this will illustrate what you can do.
ajax.php
<?php
header("content-type: application/json");
exit(json_encode($_POST));
index.php
<script>
const toSearchArray = ['some', 'array', 'with', 'values'];
$.post('ajax.php', {
variable: toSearchArray
}).done(data => {
console.log(data) // here you will see the result of the ajax.php script
})
</script>
Well I don't think thats the right way to do it when it comes to arrays, see you need to use JSON encode in javascript then JSON decode in php
Refer to this question Pass Javascript Array -> PHP

How to call php function from JavaScript using Ajax?

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 */ });
}
}

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

Call a PHP function after AJAX

When a user submits the form on my page I use AJAX to submit the information without refreshing the page. After the user submits the information I want to run a PHP function that I have already written that displays the information. Is this possible or do I need to run another ajax function to update after
$(function () {
$('add').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'submit.php',
data: $('this').serialize(),
success: function () {
alert('form was submitted');
}
});
e.preventDefault();
updateWords(); //PHP FUNCTION
});
});
You will need to run another AJAX call on success of the first one.
JavaScript cannot interact with PHP directly and therefore you can't call a PHP function from the success/complete function of the AJAX call.
in response of this.
I have multiple forms on the page and probably 5 different ajax calls
in which no more then 2 are called at the same time, if json is better
do you have a link to some reading material or additional stack
example similar to this so i can teach myself – user934902
first of all
jquery was made for old browsers to support basic functions that ie6 does not support
the use of jquery is good if you want to have full support on almost all browser
but there are also many bad sides:
it's 81kb code wich is insane (without plugins)
it's very slow compared to native functions.
it's used by ppl who don't know how to write simple javascript.
and much more if we start to talk about the plugins.
now we are in a era where most of the ppl use their mobile devices and modern browsers
which support standard javascript 1.7.Android,ios,safari,internet explorer 10,chrome,opera & firefox support javascript 1.7
http://caniuse.com/
the code below is supported by those browsers.
this is a ajax function written by me it handles post & get
you can read more about that function here
https://stackoverflow.com/a/18309057/2450730
function ajax(a,b,e,d,f,g,c){
c=new XMLHttpRequest;
!f||(c.upload.onprogress=f);
!g||(c.onprogress=g);
c.onload=b;
c.open(e||'get',a);
c.send(d||null)
}
// Params:
// Url,callback,method,formdata or {key:val},uploadFunc,downloadFunc,placeholder
a simple get request would be
ajax('example.php',responseFunction);
and a complex post function would be
ajax('example.php',responseFunction,'post',new FormData(form),uploadFunc,dlFunc);
you need that.
so if you have your form
<form id="myForm">
<input name="name"> Name
<input name="surname"> Surname
<input name="mail"> Email
<input name="file" type="file" multiple> File/Files
</form>
you just have to write a function like that
var form=document.getElementsById('myForm');
form.onsubmit=function(e){
e.preventDefault();
ajax('submit.php',SUCCESS,'post',new FormData(this));
}
and here we come to your question :
create the submit.php file for your needs
<?php
// do whatever you need with the posted info
// copy files to a specific folder
// insert/update/delete the database
// check for errors
// lets say no errors
$err=array();
// load extra info from database to an array called $extrainfo
// load some functions... (you can do what you want here)
// like executing the function you have already written and add that info to
// the $extrainfo.
$extrainfo=array('updated correctly','files copied');
$data=array('post'=>$_POST,'files'=>$_FILES,'info'=>$extrainfo,'errors'=>$err);
echo json_encode($data);
?>
this returns a json encoded array to use later in javascript.
now we need to elaborate this json. in the SUCCESS function
function SUCCESS(){
var data=JSON.parse(this.response);
if(data.errors.length>0){
// you have some errors
}else{
// no errors
// display your response in a proper way.
console.log(data);
}
}
inside this function you just have to display based on the response data.
data contains everything you need.
here is the whole code.
copy and past into a txt file and save it as submit.php.
i have tested only in chrome for now.
<?php
if($_POST){
$err=array();
$extrainfo=array('updated correctly','files copied');
$data=array('post'=>$_POST,'files'=>$_FILES,'info'=>$extrainfo,'errors'=>$err);
echo json_encode($data);
}else{
?><!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>upload</title>
<script>
var form,result;
function ajax(a,b,e,d,f,g,c){
c=new XMLHttpRequest;
!f||(c.upload.onprogress=f);
!g||(c.onprogress=g);
c.onload=b;
c.open(e||'get',a);
c.send(d||null)
}
function SUCCESS(){
console.log(JSON.parse(this.response));
var data=JSON.parse(this.response);
if(data.errors.length>0){
result.textContent='you have some errors:'+data.errors[0];
}else{
result.textContent=JSON.stringify(data, null, '\t');
}
}
window.onload=function(){
form=document.getElementById('myForm');
result=document.getElementById('response');
form.onsubmit=function(e){
e.preventDefault();
ajax('submit.php',SUCCESS,'post',new FormData(this));
}
}
</script>
</head>
<body>
<form id="myForm">
<input name="name"> Name
<input name="surname"> Surname
<input name="mail"> Email
<input name="file[]" type="file" multiple> File/Files
<input type="submit" value="send">
</form>
<pre id="response"></pre>
</body>
</html>
<?php
}
?>
If the function is dependant on the AJAX call to submit.php finishing, then create a new AJAX call. If not, then just append the function to submit.php and call it at the end of the file.
You should use the ajax function that performs the update information to update the page itself at the same time.
Just return usable HTML as the return from the ajax, and use that as the HTML content of the page.
Example: test.php
<script>
function updateName() {
var url = './test.php?inpName=' + $('#inpName').val();
$.get( url, function( data ) {
$( "#frmDivUpdate" ).html( data );
alert( "Call was performed." );
});
}
</script>
<div id="frmDivUpdate">
<form>
Enter your name : <input name="inpName" id="inpName">
<br>
<input type="button" onClick="updateName();" value="Update">
</form>
</div>
<?php
if (isset($_GET))
{
$inpName = $_GET["inpName"];
echo "You updated your val to $inpName";
}
?>
PHP is serverside , javascript is clientside.
you can't call php from client if the page is already loaded.
so the easy way is ajax
in the submit.php add:
echo json_encode($_POST);
or the
PHP function that I have already written
... the information what you need.
and in the success function
success: function () {
// i don't use jquery but the response contains the json string
console.log('the words you wanna update:',JSON.parse(response));
// updateWords(JSON.parse(response));
}
EDIT
you also don't need more than one ajax function
you say you already wrote a script to display the next information to the client.
add that script to the submit.php
and the succes function will give you what you need as response.
i added echo json_encode($_POST); because most of the time as answer/update info you need is that one you just posted.

Categories

Resources