I want to transfer Data between the cgi page and javascript/Jquery and return back to cgi page
Index.html has the form contents
login.cgi has
my $username= $cgi->param('uid');
if (($cgi->param('uid') eq 'demo') && ($cgi->param('pwd') eq 'demo')) {
my $cookie = CGI::Cookie->new(-name=> 'uid', -value=> $cgi->param('uid'));
print $cgi->redirect(-uri => '/cgi-bin/index.cgi', -cookie => $cookie);
index.cgi has
my $uid = $cookies{uid}->value;
print $uid;
print <<"HTML_CODE"
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script src="/scripts/test_javascript.js" type="text/javascript"></script>
</head>
<body>
<h2> This is a Demo Login Page of $uid </h2>
</body>
</html>
HTML_CODE
;
test_javascript.js has
$(document).ready(function () {
var uid = $('#uid').attr('value');
if (uid) {
$.ajax({
url:'/cgi-bin/index.cgi',
data: "uid=" + uid,
// script call was *not* successful
error: function() {
alert("script call was not successful");
},
// script call was successful
// data should contain the string returned by the Perl script
success: function(data){
alert("Your userid is: " + data)
}
});
}
}
)
Otion 1 - I would hardcode it in the index.cgi. This way you can insert the value into the javascript code.
This should be your index.cgi:
$(document).ready(function () {
var uid = $cookies{uid}->value;
if (uid) {
$.ajax({
url:'/cgi-bin/index.cgi',
data: "uid=" + uid,
// script call was *not* successful
error: function() {
alert("script call was not successful");
},
// script call was successful
// data should contain the string returned by the Perl script
success: function(data){
alert("Your userid is: " + data)
}
});
}
}
)
my $uid = $cookies{uid}->value;
print $uid;
print <<"HTML_CODE"
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script src="/scripts/test_javascript.js" type="text/javascript"></script>
</head>
<body>
<h2> This is a Demo Login Page of $uid </h2>
</body>
</html>
HTML_CODE
;
Option 2 - assign $cookies{uid}->value to a hidden input and have testjavascript pick it up later
Index.cgi:
print <<"HTML_CODE"
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script src="/scripts/test_javascript.js" type="text/javascript"></script>
</head>
<body>
<h2> This is a Demo Login Page of $uid </h2>
<input id="uid" type="$cookie{uid}->value"/>
</body>
</html>
HTML_CODE
;
$(document).ready(function () {
var uid = $.cookie("uid");
if (uid) {
$.ajax({
url:'/cgi-bin/index.cgi',
data: "uid=" + uid,
// script call was *not* successful
error: function() {
alert("script call was not successful");
},
// script call was successful
// data should contain the string returned by the Perl script
success: function(data){
alert("Your userid is: " + data)
}
});
}
}
)
Related
I have make a simple html file to get my data and add button to post data but however i am returning error 400
My get method are running fine with displaying the backend data out in the html but however post method i am returning some errors 400 due to my query which i not sure why is there any way i can prevent this error 400 ?
<!DOCTYPE html>
<html>
<head>
<title>Add recycables</title>
<!-- Stylesheet -->
<link rel="stylesheet" href="/">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id = "add"></div>
<P>Add recycables</P>
<p>name: <input type="text" id="name"></p>
<p>type:<input type="text" id="type"> </p>
<button id="add">Add</button>
</body>
<script>
$(document).ready(function(){
var $items = $('#add');
var $name = $('#name');
var $type = $('#type');
$.ajax({
url:"https://ecoexchange.dscloud.me:8080/api/get",
method:"GET",
// In this case, we are going to use headers as
headers:{
// The query you're planning to call
// i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
query:"RecyclableGet(0)",
// Gets the apikey from the sessionStorage
apikey:sessionStorage.getItem("apikey")
},
success:function(data, item, xhr,textStatus) {
//console.log(data)
$.each(data, function(i, item){
$items.append('<li>name: '+item.Name +', type: '+ item.RecyclableType + '</li>');
});
},
error:function(xhr,textStatus,err) {
console.log(err);
}
});
$('#add').on('click', function(){
var addRecyclables = {
Name: $name.val,
RecyclableType: $type.val
}
})
$.ajax({
url:"https://ecoexchange.dscloud.me:8080/api/post",
method:"POST",
headers:{
// The query you're planning to call
// i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
query:`RecyclableAdd('${name}','${type}')`,
// Gets the apikey from the sessionStorage
apikey:sessionStorage.getItem("apikey")
},
success:function(data, Newitem, xhr,textStatus){
$items.append('<li>name: '+Newitem.Name +', type: '+ Newitem.RecyclableType + '</li>');
},
error:function(xhr,textStatus,err) {
console.log(err);
}
})
})
</script>
</html>
Json file look like
my html on web
I have a web site that periodically get a message. I put this message in a variable in javascript code (in php file). Then i want to take it in an another php page but doesn't work.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="jquery-1.9.1.js"></script>
<!-- Script to import MQTT -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/paho-mqtt/1.0.1/mqttws31.js" type="text/javascript">
</script>
<script>
....
function onMessageArrived(message) {
console.log("onMessageArrived:" + message.destinationName);
console.log("message.payloadString:" + message.payloadString);
if (message.destinationName == "measure") {
var msg = message.payloadString;
if (msg.includes("temperature")) {
//Splitting up the message for the MAC address value
var MacVal = msg.substring(15,32);
var mac = String(MacVal);
$.ajax({
type: 'POST',
url: 'storeData.php', //url to php file
data: {mac: mac},
success: function(data)
});
}
}
</script>
In storeData.php page i have
$temp = $_POST['mac'];
But this varible is always empty.
Thanks
main.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="jquery-3.1.1.min.js"></script>
<script src="jsfile.js"></script>
</head>
<body>
<button onclick="cart(0)"> hi </button>
<p id="disp"></p>
</body>
</html>
jsfile.js
function cart(id1)
{
var id=id1;
//alert("enterd "+id);
document.getElementById("disp").innerHTML ="hi";
if (window.jQuery) {
// jQuery is available.
// Print the jQuery version, e.g. "1.0.0":
//alert(window.jQuery.fn.jquery);
}
$.ajax({
url:"add.php ",
type:"POST",
data:{
item_id: id,
},
success:function(response) {
document.getElementById("disp").innerHTML =response.value1;
},
error:function(){
alert("error");
}
});
}
add.php
<?php
if(isset($_POST['item_id'])){
//if(count($_POST)>0)
echo json_encode(array("value1" => "hello", "value2" => "hi"));
}
?>
am collection the informaton from add.php to jsfile.js ... I am not able to get information from the json array.. I am trying to get information by respnse.value1. But it returns me undefined.. what might be the error??
You'll have to parse the JSON before using it. Change your success function to this -
success:function(response) {
var res = JSON.parse(response);
document.getElementById("disp").innerHTML = res.value1;
},
So I am able to get my php value into javascript variable but I don't think my script.js is finding it. There of course are alot of files missing for the sake of keeping this question clean but my problem is that script.js get schoolId as undefined instead of the actual value but when I console.log schoolId i get a value of "1"(first page has id 1 so that works).
Header.php :
<?php
//gets current page id
$schoolOfficialId = $specificSchool[0]["id"];
?>
<head>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<input type="hidden" id='schoolOfficialId' value="<?php echo $schoolOfficialId;?>"/>
<script type="text/javascript">
var schoolId = $('#schoolOfficialId').val();
</script>
</body>
script.js: ajax call here NOTE: in the ajax i know the data is having trouble finding schoolId from the header.php to send to php file.
// execute an ajax query to push id of page to load_more.php
$.ajax({
url: 'load_more.php',
type: 'POST',
data: {schoolId:schoolId},
success:function(data){
console.log("working");
}
});
my load_more.php:
if (isset($_POST['schoolId'])) {
echo "yes";
}else {
echo "nope";
}//keeps echoing nope because the schoolId is not received
The problem is that you have the script running before the declaration.
<script type="text/javascript" src="js/script.js"></script> is in head, but var schoolId = $('#schoolOfficialId').val(); is at the bottom of the page.
Include the script after declaring schoolId.
<head>
</head>
<body>
<input type="hidden" id='schoolOfficialId' value="<?php echo $schoolOfficialId;?>"/>
<script type="text/javascript">
var schoolId = $('#schoolOfficialId').val();
</script>
<script type="text/javascript" src="js/script.js"></script>
</body>
P.S. despite other answers, data: {schoolId:schoolId}, is perfectly fine unless the keyname conflicts with a reserved word.
Load ajax code after defining var schoolId and also check source code whether php printing value for schoolId correctly or not and also do not forget to use $(document).ready()
<script type="text/javascript">
$(document).ready(function(){
var schoolId = $('#schoolOfficialId').val();
$.ajax({
url: 'load_more.php',
type: 'POST',
data: {schoolId:schoolId},
success:function(data){
alert(data);
}
});
})
</script>
PHP:
if (isset($_POST['schoolId'])) {
echo $_POST['schoolId'];
}else {
echo "nope";
}
By running the following i can see yes in alert ...
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>stackoverflow</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script>
$(document).ready(function () {
var schoolId = $("#schoolOfficialId").val();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {schoolId: schoolId},
success: function (data) {
alert(data);
}
});
});
</script>
</body>
</html>
Ajax file (ajax.php) :
if (isset($_POST['schoolId'])) {
echo "yes";
} else {
echo "nope";
}
When you press the link text it is supposed to give you an random string from a file, which it does on first click. But second click nothing happens, I need to refresh page before execute it again..
Code:
function randomName() {
$names = file('layout/sub/names.txt', FILE_IGNORE_NEW_LINES);
$array = array_rand($names);
return $names[array_rand($names)];
}
<div class="randomName">
</div>
<button class="aardvark">Pick random name</button>
<script>
$(document).on('click','.aardvark', function(e){
$('.randomName').html('<?php echo randomName(); ?>');
});
</script>
The issue is the age old PHP is server side and and javascript(jQuery) is client side problem, you cant call/run PHP from javascript as its already happened.
You will need to use AJAX to re-request a new name. Here is a copy and paste example, your welcome ;p
<?php
//is ajax
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//is get name
if(isset($_POST['get_name'])){
$names = file('names.txt', FILE_IGNORE_NEW_LINES);
exit(json_encode(array('resp' => $names[array_rand($names)])));
}
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title></title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function(){
//get_name function
$.fn.get_name = function(){
var elm = $(this);
var ajax = $.ajax({
url: "./",
type: "POST",
data: {'get_name':true},
dataType: "json"
});
ajax.done(function(data){
elm.html(data.resp);
});
ajax.fail(function(xhr, status, error){
elm.html("AJAX failed:" + xhr.responseText);
});
return this;
};
//do get_name on page load
$('#randomName').get_name();
//do get_name on button click
$('#aardvark').on('click', function(){
$('#randomName').get_name();
});
});
</script>
</head>
<body>
<div id="randomName"></div>
<button id="aardvark">Pick random name</button>
</body>
</html>