var PId = 12;
var catId = 3;
var Param = 'productid='+PId+'&CatId='+catId;
var encriptedCode = '<?php echo $this->encrypt->encode( .... need to pass the Param .... );?>';
I am trying to pass the javascript value into php method, whatever i am trying it's not working. Any one help me to detect where i am wrong. using this code in time of ajax call
You would need to make an Ajax request and pass that information through using the GET request.
Something like this:
var PId = 12;
var catId = 3;
var Param = 'productid='+PId+'&CatId='+catId;
$.get( Param ); // makes the call to the PHP script
Then in your PHP file you can retrieve the data passed.
I guess that you need result of $this->encrypt->encode method to use in your JS file. So you need to retrieve it using XMLHttpRequest.
var PId = 12;
var catId = 3;
var Param = 'productid='+PId+'&CatId='+catId;
var req = new XMLHttpRequest();
var encriptedCode;
req.open('GET', 'path/to/your/file.php?' + Param, true);
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200) {
encriptedCode = req.responseText;
// Do some something with your encrypted code
} else {
// Handle error here
}
}
};
req.send(null);
and the PHP file should looks like here
<?php
// Load here libs for encryption
$productId = (int)$_GET['productid'];
$catId = (int)$_GET['CatId'];
echo $encryptObj->encrypt->encode($productId, $catId);
It should be as simple as:
encriptedCode = '<?php echo $this->encrypt->encode(?>Param<?php);?>';
Related
I'm do output with json_encode to sending to javascript, with this code.
<?php
include "Connection.php";
$syntax_query = "select * from product";
$thisExecuter = mysqli_query($conn, $syntax_query);
$result = array();
while($row = mysqli_fetch_assoc($thisExecuter)){
array_push(
$result,
array(
"id" => $row["product_id"],
"name" => $row["product_name"]
)
);
}
echo json_encode($result);
?>
so output show like this,
[{"id":"121353568","name":"Baju Casual - Black"},{"id":"556903232","name":"Tas LV - Red"},{"id":"795953280","name":"Sword - Wood"},{"id":"834032960","name":"Scooter - Iron Plate"}]
and code javascript like this
function showHint() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
var obj = this.responseText;
document.getElementById("txtHint").innerHTML = obj.id;
}
xmlhttp.open("GET", "Download.php");
xmlhttp.send();
}
so obj.id its not working, output show undifined.
I use ajax calls when I want to call a Php file and get a response from the same as below to try once that as I have shown. Before moving with Ajax you must need jquery to be imported into the calling file.
If Jquery is imported then ignore the steps
Here are steps,
Go to the link https://code.jquery.com/jquery-3.6.0.min.js copy whole content (use ctl+A to select whole content and ctl+C to copy)
Open a new file in the current project folder and paste the copied content (use ctl+V to paste) save it as 'jquery-3.6.0.min.js'
Import the js file in the HTML file in script tag as shown '
Now, this is the ajax example to call the PHP file and to get a response
function showHint() {
//since you have used GET method I have used here GET but You can use POST also here
$.ajax({
url: 'Download.php',
type: 'get',
//if any value you want to pass then uncomment below line
// data: {'name_to_pass':'value'},
//the variable can be accessed in the php file by 'name to pass' under $_GET['name_to_pass'] or $_POST['name_to_pass'] based on type
success: function(res)
{
// open DevTool console to see results
console.log(JSON.parse(res));
}
});
}
Hope this will help you out, thank you
Maybe you need a JSON.parse in the response, something like JSON.parse(this.responseText).
And also I can see the result is an Array so you will need to iterate obj
obj.forEach(item => {
document.getElement("txtHint").innerHTML = item.id;
});
you should define the response type as json
header('Content-Type: application/json; charset=utf-8');
echo json_encode($result);
function showHint() {
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
**var obj = this.responseText;**
document.getElementById("txtHint").innerHTML = obj.id;
}
xmlhttp.open("GET", "Download.php");
xmlhttp.send();
}
When you get the responseText it's text, not an object.
var obj = this.responseText; should be let obj = JSON.parse(this.responseText);
Then you can access obj.id as a property.
Hello I am trying to create a simple javascript that pulls data from a REST API. I am looking to only pull 1 data set within the API or json list of items.
Where as I only need the "last" data set to be included within the population not everything else.
I have tried using a different method of retriving the last price data set via curl however the resource blocks requests in php. Thus I need to do this with javascript.
document.getElementById("output").innerHTML = (ourRequest.responseText);
I have tried changing this section to be
document.getElementById("output").innerHTML = (ourRequest.responseText.last);
and a few other variables however returned no success on the output.
Below is the js code that I have made so far however it shows all the API information on the page where I only need to select 1 part of the information.
<p id="output"></p>
<script>
var burl = "https://api.idex.market/returnTicker?market=ETH_STASH";
var url = burl;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET',url,true);
ourRequest.onload = function(){
document.getElementById("output").innerHTML = (ourRequest.responseText);
}
ourRequest.send();
</script>
I am expecting to have only 0.00000001512001 as the result being the "last" data set.
and the output is the following:
{"last":"0.00000001512001","high":"0.00000015","low":"0.00000001512001","lowestAsk":"0.00000058999999999","highestBid":"0.00000001","percentChange":"-89.91999333","baseVolume":"0.965950839330223243","quoteVolume":"24272447.879302712135495139"}
You can test and edit it here to try: https://www.w3schools.com/code/tryit.asp?filename=FYUDV3ZFYNA9
Try changing
document.getElementById("output").innerHTML = (ourRequest.responseText);
to
document.getElementById("output").innerHTML = (JSON.parse(ourRequest.responseText).last);
Full working solution:
<script>
var burl = "https://api.idex.market/returnTicker?market=ETH_STASH";
var url = burl;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET',url,true);
ourRequest.onload = function(){
document.getElementById("output").innerHTML = JSON.parse(ourRequest.responseText).last;
}
ourRequest.send();
</script>
Convert the responseText to a valid JavaScript Object using
let returned_data = JSON.parse(ourRequest.responseText);
Then access the last property as
last = returned_data['last'];
Editted
<script>
var burl = "https://api.idex.market/returnTicker?market=ETH_STASH";
var url = burl;
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET',url,true);
ourRequest.onload = function(){
let returned_data = JSON.parse(ourRequest.responseText);
let last = returned_data['last'];
document.getElementById("output").innerHTML = last;
}
ourRequest.send();
</script>
I've created a new array in javascript and I'm adding values to it indexes from a function an then passing the array to the ajaxCall function were I try to convert it to json and send it to a php file via ajax, but the variable json is allways empty. I've been reading a lot about how to send javascript objects json_encoded via ajax and looks like this is the way to do it, but obviously I haven't readed enought or there is something I've been missing. Anycase I'm newbie in javascript and any help would be apreciated.
function createArray()
{
var advancedFormVars = new Array();
advancedFormVars['checkbox1'] = document.getElementById('OfferID').value;
advancedFormVars['checkbox2'] =document.getElementById('offerName').value;
AjaxCall(advancedFormVars);
}
function AjaxCall(advancedFormVars){
var json = new Array();
json = JSON.stringify(advancedFormVars); //in debuger it shows me this as content of json variable--> [] but advancedFormVars is not empty
$.ajax({
url : 'AL_loadForm.php',
type : 'POST',
data : {
json : json
},
dataType:'json',
success : function(data) {
alert(data);
}
...
You are trying to use your array as a hash, so the values are not being set..
Instead of setting
var advancedFormVars = new Array();
Try setting
var advancedFormVars = {};
Example
JS:
var advancedFormVars = {};
advancedFormVars['checkbox1'] = 'valueA';
advancedFormVars['checkbox2'] = 'valueB';
var json = JSON.stringify(advancedFormVars);
console.log(json); //{"checkbox1":"valueA","checkbox2":"valueB"}
PHP
<?php
$json = '{"checkbox1":"valueA","checkbox2":"valueB"}';
$obj = json_decode($json);
var_dump($obj);
/*
object(stdClass)#1 (2) {
["checkbox1"]=>
string(6) "valueA"
["checkbox2"]=>
string(6) "valueB"
}
*/
?>
If all you have are two smaller arguments, I'd keep it simple and make an http get request. Encode your arguments if neccessary.
var url = "http://wherever.com/something.php?arg1=";
url += document.getElementById('OfferID').value;
url += "&arg2=" + document.getElementById('offerName').value;
httpGetAsync(url, returnMethod);
function httpGetAsync(theUrl, callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
}
xmlHttp.open("GET", theUrl, true); // true for asynchronous
xmlHttp.send(null);
}
I couldn't find anything on javascript but this might be clarified very quickly. I am working on a website where I have to retrieve data via http requests from a server. Because I need to make several requests and the data is constant what I want to do is make table with keys and values -> store those values in a file -> and then be able to retrieve those values. That way I have to read one file as apposed to fetching data via 30 http requests
General Idea :
Given: spell id = number (Ex. 45)
Output: name of spell = string (Ex. fire...)
Use this output to then fetch the url of the image of the spell (containing the spell name)
EDIT
Code :
// When I fetch the file i use (json data)
function getChampionImage(id) {
var champUrl = "https://na.api.pvp.net/api/lol/static-data/na/v1.2/champion/" +id +"/?api_key=....."
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", champUrl, false );
xmlHttp.send( null );
var jsonText = xmlHttp.responseText;
var champData = JSON.parse(jsonText);
var champName = champData.key;
return "http://ddragon.leagueoflegends.com/cdn/" + versionNum + "/img/champion/"+champName+".png";
}
all you need to do is tack the response onto an object, keyed by input.
this is especially simple in sync IO because you don't have to worry about callback scope.
Since functions are objects in JS, you can just use the procedure itself as a namespace, which plays well with methods because you don't need an outside variable:
// When I fetch the file i use (json data)
function getChampionImage(id) {
var cached=getChampionImage["_"+id];
if(cached) return cached;
var champUrl = "https://na.api.pvp.net/api/lol/static-data/na/v1.2/champion/" +id +"/?api_key=....."
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", champUrl, false );
xmlHttp.send( null );
var jsonText = xmlHttp.responseText;
var champData = JSON.parse(jsonText);
var champName = champData.key;
return getChampionImage["_"+id]="http://ddragon.leagueoflegends.com/cdn/" + versionNum + "/img/champion/"+champName+".png";
}
EDIT: to persist the url data between page visits, use localStorage as the hash object:
function getChampionImage(id) {
var cached=localStorage["_"+id];
if(cached) return cached;
var champUrl = "https://na.api.pvp.net/api/lol/static-data/na/v1.2/champion/" +id +"/?api_key=....."
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", champUrl, false );
xmlHttp.send( null );
var jsonText = xmlHttp.responseText;
var champData = JSON.parse(jsonText);
var champName = champData.key;
return localStorage["_"+id]="http://ddragon.leagueoflegends.com/cdn/" + versionNum + "/img/champion/"+champName+".png";
}
note that with localStorage, you'll have to self-expire the cache if you make changes.
In JSP page I have written:
var sel = document.getElementById("Wimax");
var ip = sel.options[sel.selectedIndex].value;
var param;
var url = 'ConfigurationServlet?ActionID=Configuration_Physical_Get';
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
httpRequest.open("POST", url, true);
httpRequest.onreadystatechange = handler(){
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
param = 'ip='+ip;
param += 'mmv='+mmv;
param += "tab="+tab;
}};
httpRequest.send(param);
I want this param variable in my ConfigurationServlet. Can anyone tell me how to get this json object in servlet?
Update: I changed my statements and now it is showing status code as 200.
var index = document.getElementById("Wimax").selectedIndex;
var ip = document.getElementById("Wimax").options[index].text;
httpReq = GetXmlHttpObject();
alert(httpReq);
var param = "ip=" + ip;
param += "&mmv=" + mmv;
param += "&tab=" + tab;
alert("param "+param);
var url="http://localhost:8080/WiMaxNM/ConfigurationServlet?ActionID=Configuration_Physical_Get";
url = url+"?"+param;
httpReq.open("GET",url,true);
alert("httpReq "+httpReq);
httpReq.onreadystatechange = handler;
httpReq.send(null);
But new problem has occured. Control is not at all going to the servlet action ID as specified in url. Please tell me what is wrong here.
The code in the handler will only be invoked AFTER the request is been sent. You need to populate param before this. You would also need to concatentate separate parameters by &.
Thus, e.g.
// ...
httpRequest.onreadystatechange = handler() {
// Write code here which should be executed when the request state has changed.
if (httpRequest.readyState == 4) {
// Write code here which should be executed when the request is completed.
if (httpRequest.status == 200) {
// Write code here which should be executed when the request is succesful.
}
}
};
param = 'ip=' + ip;
param += '&mmv=' + mmv;
param += "&tab=" + tab;
httpRequest.send(param);
Then you can access them in the servlet the usual HttpServletRequest#getParameter() way.
That said, the Ajax code you posted there will only work in Microsoft Internet Explorer, not in all the four other major webbrowsers the world is aware of. In other words, your Javascript code won't work for about half of the people in the world.
I suggest to have a look at jQuery to lessen all the verbose work and bridge the crossbrowser compatibility pains. All your code could be easily replaced by
var params = {
ip: $("Wimax").val();
mmv: mmv,
tab: tab
};
$.post('ConfigurationServlet?ActionID=Configuration_Physical_Get', params);
And still work in all webbrowsers!
Update: as per your update, the final URL is plain wrong. The ? denotes a start of the query string. You already have one in your URL. You should use & to chain parameters in the query string. I.e.
url = url + "&" + param;