Flag Query PHP to JavaScript - javascript

I have that
JavaScript
flagQuery = session.reponseText;
alert(flagQuery);
flagQuery = JSON.parse(flagQuery);
contentElt.innerHTML = "valeur FLAG" + flagQuery;
My javascript must receive a flag sent from php.
The code above is the treatment of flag when it is received.
In my php I declare the variable flag to true.
I want to treat this with Ajax, if it's possible.
I don't know what to add in the PHP to get the flag in JavaScript?
I should prefer not to have to overload my code with a jQuery bookshop that I will use it for half a score line of code.

I assume want to access php value through ajax request. And you can do that liek below;
PHP: flag.php
<?php
$flag = "Your flag value";
echo $flag;
JS:
$.ajax({
url: "flag.php",
type: "get",
success: function(data){
alert("Flag value is: " + data);
},
error:function(){
alert("Error occured!");
}
});
Pure JS:
<script>
function getFlagValue() {
var xmlHttp;
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState==4 && xmlHttp.status==200) {
alert(xmlHttp.responseText);
}
}
xmlHttp.open("GET","flag.php",true);
xmlHttp.send();
}
</script>

Hello. Try this and see if it's you need.
//PHP File
<?php
echo json_encode(array("one","two"));
?>
//Js File
$.get("page.php", function(data){
alert(data)
})

Related

how to send data to php file then echo a message

I am trying to send data to php file then echo the word "Hello!" when i call a function in javascript, however, no message appear, i guess there is en error in the calling, can you guide me please?
Here is my code:
Javascript:
function asyncpost_deviceprint() {
var xmlhttp = false;
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
else if (!xmlhttp) return false;
xmlhttp.open("POST", "http://localhost/Assignment/insert.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("userAgent" + userAgent()); /* fire and forget */
return true;
}
PHP:
<?php
echo "Hello!";
?>
echo "Hello!";
won't display any message because in Ajax request this function sends a respond to Javascript.
If you want to display sth on the screen with PHP instead of Ajax you should use:
window.location.href="path to your php site"
it will redirect you to php file and display Hello!
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
document.body.innerHTML += xmlhttp.responseText;
}
}
};
Add this before xmlhttp.send
It will literally just stick the php echo text after the last thing in the document.

Session variable can not show in AJAX Function

I am working in php where I am inserting some values to data base. And for that purpose i am using Ajax method.I am calling Ajax function on button click and inside ajax i am calling another php file where insertion occur and session variable update. But when insertion occur and i want to show the updates session variable in Ajax response, it shows old session variable and does not show the updated session vairable.
function showDiv() {
document.getElementById('HelpDiv').style.display = "block";
var value ="<?php echo ''.$_SESSION['user_name']; ?>";
alert(value);
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
// alert("ajax start");
} catch (e) {
alert("Your browser broke!");
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
//alert("start2");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
// alert("start3");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
var qst_id="<?php echo''.$question_id;?>";
// Create a function that will receive data sent from the server and will update div section in the same page.
ajaxRequest.onreadystatechange = function() {
//var value ="<?php echo ''.$_SESSION['user_name']; ?>";
//alert(value);
var t = ajaxRequest.readyState;
if (t == 4) {
document.getElementById("a").innerHTML = "<?php echo ''.$_SESSION['user_name']; ?>";
// alert("ajax received");
var startSession = "<?php session_start(); ?>";
var value = "<?php echo ''.$_SESSION['user_name']; ?>";
alert(value);
}
// if (ajaxRequest.readyState == 4) {
// alet("ajax received");
// }
}
// passing value to the server script, ajax file
var queryString = "?question_id=" + qst_id;
ajaxRequest.open("GET", "ajax-login.php" + queryString, true);
ajaxRequest.send(null);
}
<?php
session_start();
$_SESSION['user_name'] = "asasd3";
echo "".$_SESSION['user_name'];
?>
First understand that $_SESSION variable are different than the HTML session variables :
please read for more info on PHP session variable on https://www.tutorialspoint.com/php/php_sessions.htm
I am using jQuery to ease solution
$.ajax({
method : "POST",
url: "someFileToUpdateTheSession.php",
data: $(this).serialize(),
success: function(data){
// Do what you want to do when the session has been updated
alert(data);
console.log(data);
}
});
PHP Side
<?php
session_start();
$_SESSION["user_name"] = 'anything you want';
echo $_SESSION["user_name"];
die();
?>

JavaScript Not Returning Data But No Error Either

I am calling a php file that queries my database and returns a result. I have verified that the php file accurately returns the data as needed, but my calling page is not updated from the JavaScript.
What do I need to alter in my syntax below so that the returned value is returned on page?
<script type="text/javascript">
function boostion()
{
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "QueryDB.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("data").innerHTML = xhr.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
}
</script>
EDIT
I have also opened Developer Options in Chrome and checked the Console and there are no errors or issues displayed, everything is a success!
Edit 2
I tried to use the JQuery approach below and used this syntax - but I get the error
Uncaught TypeError: $(...).load is not a function
Syntax:
<script src="https://code.jquery.com/jquery-3.1.1.slim.js"
integrity="sha256-5i/mQ300M779N2OVDrl16lbohwXNUdzL/R2aVUXyXWA="
crossorigin="anonymous" type="text/javascript"></script>
<script type="text/javascript">
$(window).load(function(){
$.get("QueryDB.php", function(data, status){
document.getElementById("data").innerHTML = data;
});
});
</script>
Edit 3
This is my php syntax that runs the sql syntax and echo result that I want to have returned from the javascript
<?php
$option = array();
$option['driver'] = 'mssql';
$option['host'] = 'host';
$option['user'] = 'user';
$option['password'] = 'password';
$option['database'] = 'database';
$option['prefix'] = '';
$db = JDatabase::getInstance( $option );
$result = $db->getQuery(true);
$result->select($db->quoteName(array('trackandfieldresults')));
$result->from($db->quoteName('[TrackData]'));
$db->setQuery($result);
$row = $db->loadRowList();
echo $row['0']
?>
Use xhr.send();
If it is a GET request, you have to apply the query string in in xhr.open and you dont have to set Content-type:application/x-www-form-urlencoded
first, the scripts should be inside the HTML before the ending body tag. then you open another file and write your code in it. JQUERY does not have script tag. Sp you are creating an external javascript file for the script. No script tag needed. Now use this format.
$(window).on('load', function(e){
e.preventDefault();
var dat = //the content you are trying to load
$.get('middleware.php', dat, function(data){
$('#selector').html(data)
});
})
I have a faster approach using JQuery.
$(window).load(function(){
$.get("QueryDB.php", function(data, status){
//Do whatever you want here
});
});
This should do the Job. Your approach is old and kind of complicated to debug
Try this
function boostion(){
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET", "QueryDB.php", true);
xhr.send();
xhr.onreadystatechange = function(){
console.log(xhr);
if (xhr.readyState == 4 && xhr.status==200) {
document.getElementById("data").innerHTML = xhr.responseText;
}
}
}
<div id="data"></div>
<button onclick="boostion();">Load</button>

Data not getting passed via Ajax to PHP script

I'm trying to send the value of a variable number via ajax to a PHP script. But the PHP script is not printing the desired output on opening on a browser. Tried but couldn't find whats wrong here.
Any pointers ?
index.html
<button type="submit" class="btn btn-success" id = 'first' onclick='process();'>Submit</button>
<script>
var number = 0;
function process()
{
number++;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "num=" + number;
xhr.open("POST", "index.php", true);
xhr.send(data);
}
</script>
index.php
<?php
session_start();
$number = $_POST['num'];
$_SESSION['numb'] = $number;
echo $_SESSION['numb'] ;
?>
Editing my long winded lame answer since you fixed the close curly bracket... but bloodyKnuckles is right you also need something in your 'process' function to take the response from your PHP page and output it... or whatever you want to do. You can basically use the method 'onreadystatechange' in the XMLHttpRequest object and then look for a 'readyState' property value of 4 which means everything is done. Here is a simple example of that just outputting the results to the console (which you can view using developer tools in your browser of choice).
<script>
var number = 0;
function process()
{
number++;
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = "num=" + number;
xhr.onreadystatechange = function(){
if (xhr.readyState==4 && xhr.status==200){
console.log('xhr.readyState=',xhr.readyState);
console.log('xhr.status=',xhr.status);
console.log('response=',xhr.responseText);
}
else if (xhr.readyState == 1 ){
xhr.send(data)
}
};
xhr.open("POST", "ajax-test.php", true);
}
</script>
As you go further you may want to update your PHP page to only update the session when the POST value is there.
<?php
//ini_set('display_errors',1);
//ini_set('display_startup_errors',1);
//error_reporting(-1);
if(isset($_POST['num'])){
session_start();
$_SESSION['numb'] = $_POST['num'];
echo $_SESSION['numb'];
}
?>
You can uncomment those ini_set and error_reporting lines to try to figure out what is going on with your PHP script.
This is because you are not sending header information with request...
Append this code
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", data.length);
xhr.setRequestHeader("Connection", "close");
after
xhr.open("POST", "index.php", true);

Getting variable from php file called by ajax request

I have main file index.php. Where user perform login I load url.php in <div> inside index.php through ajax request.
Now on url.php, on button click event I submit the form and post data to data.php file. As url.php is loaded into index.php, button click event on url.php will call function in section of index.php.
I am getting two variable $x and $y as a result on data.php.
On index.php I have JS function where I want to use $x and $y. How can I retrieve?
index.php
<script type="text/javascript">
//------------------script 2 starts ---------
function showUser(form, e) {
//alert(myid);
e.preventDefault();
e.returnValue=false;
var xmlhttp;
var sent = form.elements['sent'].value;
//var sent2 = form.elements['sent2'].value;
//alert(sent2);
//var divElements = document.getElementById('d1').innerHTML;
var text1 = document.getElementById('previewUrl').innerText || document.getElementById('previewUrl').textContent;
var text2 = document.getElementById('previewTitle').innerText || document.getElementById('previewTitle').textContent;
var text3 = document.getElementById('previewDescription').innerText || document.getElementById('previewDescription').textContent;
//alert(text3);
console.log(sent);
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(e) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open(form.method, form.action, true);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
sent = encodeURIComponent(sent);
text1 = encodeURIComponent(text1);
text2 = encodeURIComponent(text2);
text3 = encodeURIComponent(text3);
xmlhttp.send('sent=' + sent + '&text1=' + text1 + '&text2=' + text2 + '&text3=' + text3);
}
</script>
+
$.ajax({
url:'url.php'
,async: true
,type : 'POST'
,cache: false
,data : 'myid=' + myid
,dataType: 'html'
,success: function(data){
$('body').html(data);
FB.XFBML.parse();
}
}
);
url.php
<form action="data.php" method="POST" onsubmit="showUser(this, event)">
data.php
if (preg_match_all('/[^=]*=([^;#]*)/', shell_exec("/home/technoworld/Desktop/test/b '$test'"), $matches)){ //Values stored in ma.
echo "hi";
$x = (int) $matches[1][0]; //optionally cast to int
$y = (int) $matches[1][1];
this x and y I want to fetch in index.php.
I know this is not impossible. But complex to thing for me!
My preferred method of sending data back from the server side is responding with JSON response..
$data['x'] = $x;
$data['y'] = $y;
header('Content-Type: application/json');
echo json_encode($data);
That should give a response to your ajax callback, so you could use it like this:
$.post('data.php', { "myid": id }, function(data) {
console.log(data.x); //data.x = $x
console.log(data.y); //data.y = $y
});
I didn't test the code to see if it actually works, but it should give an idea of what to do. Let me know if it makes sense :)
If you want to retrieve only two value.
Simplest solution just like boiling a egg is:
just print both value in with separating value like ':'
echo $x.':'.$y;
and when you getting response. separate value with ':' and then you can use them..
or JSON response is also good practice for this.

Categories

Resources