Script html php - php

In the script below, I currently have a fixed value in the array of $out variable. Example: $out[1]. What I need is for this fixed value (in this case 1), to be replaced by the str value of the function.
str is javascript
$out[1] is php
Someone can help me?
<script>
function teste2(str) {
var xhttp;
if (str == "") {
document.getElementById("cli").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("resimg").innerHTML =
"<img src=" + "<?php echo ("img/base/".$out[1]);?>" + ">"
}
};
xhttp.open("GET", "clique.php?q="+str, true);
xhttp.send();
}
</script>

As mentioned, it doesn't make sense why you are mixing PHP in your JS. If you need data from the server side usable by your client side JS, there are multiple approaches.
The preferred approach is to make an API endpoint you can call and return JSON.
Another approach (not recommended) is to output a JSON object in a script tag on server render and then access it like:
<script>
let data = <?php echo(json_encode($myData)); ?>;
</script>
To answer your question though, you can set the value with JS since the variable you want is client side:
function teste2(str) {
var xhttp;
if (str == "") {
document.getElementById("cli").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let src = 'img/base/' + str;
document.getElementById("resimg").innerHTML = '<img src="' + src + '">';
}
};
xhttp.open("GET", "clique.php?q="+str, true);
xhttp.send();
}

Well, PHP scripts run on the server side, while Javascript ones run on the client's browser.
Therefore, the value of str will only be resolved at runtime, when the function is called on the user's browser. There is no way for your PHP script to know in advance what the value will be, as your PHP script runs before any JS does.
I am sorry, but I believe you should re-imagine your design here.
Edit: I assume your $out is a PHP variable, right?

Related

Display file info?

Thanks to my previous posts, some of yall helped me setting this piece of code right there. :). It lists files in the current folder.
<?php
foreach (glob("*") as $filename) {
echo "<th class=\"icon\"><img src=\"/Home/.res/save.png\"></th><th>{$filename}<th class=\"desc\"><img src=\"/Home/.res/info.png\"></th></tr>";
}
?>
I now want to add an "info" button at the end of every file name. I succeeded. :)
Only thing is, its only able to display static text- I want that info tab to display information about the selected file. I then did some research on AJAX.
I came up with this code:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("info").innerHTML = this.responseText;
}
};
xhttp.open("GET", ".info.php", true);
xhttp.send();
This code successfully loads dynamically a page called ".info.php".
Heres the tricky part: How can I make AJAX transfer a variable (the file name) to .info.php - so that info.php can display information about the selected file?
=======EDIT: Came up with this AJAX code:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("info").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/Home/.info.php?filename=<?php echo "{$filename}" ?>", true);
xhttp.send();
}
Im now able to pass variables! (Thanks Jeff)
Sadly, the passed variable is always setted as the last file in the list, instead of being setted by the selected file. Any tips?
=========EDIT #2===========
My code right now:
First is PHP
<?php
foreach (glob("*") as $filename) {
echo "<th class=\"icon\"><img src=\"/Home/.res/save.png\"></th><th>{$filename}<th class=\"desc\"><img src=\"/Home/.res/info.png\"> </th></tr>";
}
?>
Now for the AJAX:
function loadDoc(filename) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("info").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/Home/.info.php?filename=" + filename, true);
xhttp.send();
}
Cheers.
You need to pass the specific filename as a parameter to your PHP page.
The issue with your first update is that foreach iterates over the array assigning the value to the "temporary" variable.
foreach (glob("*") as $filename) {
After the iteration is complete that variable ($filename, which should be considered temporary) contains only the last value of that array. So your JS function just has a statically defined file name.
The JS call should pass in the filename, and the JS function should take in a value and use it when making the call.
PHP:
onclick=\"loadDoc('{$filename}')\"
JS:
function loadDoc(filename) {
....
xhttp.open("GET", "/Home/.info.php?filename=" + filename, true);

script within a php page not executed when called using ajax

Please read below my scenario…
I have a PHP file wherein I have javascript within it..
<?php
echo ‘<script>’;
echo ‘window.alert(“hi”)’;
echo ‘</script>’;
?>
On execution of this file directly, the content inside the script is executed as expected. But if this same page is being called via ajax from another page, the script part is NOT executed.
Can you please let me know the possible reasons.
(note: I’m in a compulsion to have script within php page).
When you do an AJAX call you just grab the content from that page. JavaScript treats it as a string (not code). You would have to add the content from the page to your DOM in your AJAX callback.
$.get('/alertscript.php', {}, function(results){
$("html").append(results);
});
Make sure you change the code to fit your needs. I'm supposing you use jQuery...
Edited version
load('/alertscript.php', function(xhr) {
var result = xhr.responseText;
// Execute the code
eval( result );
});
function load(url, callback) {
var xhr;
if(typeof XMLHttpRequest !== 'undefined') xhr = new XMLHttpRequest();
else {
var versions = ["MSXML2.XmlHttp.5.0",
"MSXML2.XmlHttp.4.0",
"MSXML2.XmlHttp.3.0",
"MSXML2.XmlHttp.2.0",
"Microsoft.XmlHttp"]
for(var i = 0, len = versions.length; i < len; i++) {
try {
xhr = new ActiveXObject(versions[i]);
break;
}
catch(e){}
} // end for
}
xhr.onreadystatechange = ensureReadiness;
function ensureReadiness() {
if(xhr.readyState < 4) {
return;
}
if(xhr.status !== 200) {
return;
}
// all is well
if(xhr.readyState === 4) {
callback(xhr);
}
}
xhr.open('GET', url, true);
xhr.send('');
}

Jquery Ajaxing in Processmaker

I am using a web app called ProcessMaker.
They do not have support for jquery. So I had to figure out how to integrate it myself. There were lots of people on their forums trying to get it done, so thankfully it now has been documented. If anyone would like to do so here is the link where I have detailed the process: jQuery with ProcessMaker
My question is now using the jquery ajax request.
In order to use jquery with processmaker I had to overcome 2 problems. The first the Smarty filtering since processmaker uses templating langauge. And the second the Maborak lib doesn't allow certain things.
So now I believe it to be a maborak issue, but I do not know for certain. All I know when I try to run my code, the error console (firefox 4.x) gives me the following error: jqXHR[i] is not a function.
This is happening at line 7323 of my jquery lib that I included (version 1.6.2).
I have Googled, and all I have come up with so far is that people are saying it can possibly be a befreSend issue and that disabling it fixes it.
Maybe I don't know how to disable it properly, but it isnt working still.
If anyone can help me with this, it would be very greatly appreciated.
Thanks,
Zedd
In Processmaker exist a library "makorak" this library generate problems with other libraries.. hence you Should use jquery as follows...
var $JQ = jQuery.noConflict();
$JQ("#myField").value = 'cochalo';
hope I've helped
Try this:
$.noConflict();
jQuery(document).ready(function($)){
$("button").click.function(){
$("p").text("jquery is still working");
}
}
before:
you need declare this:
var $j = jQuery.noConflict();
and... you must don't use $() any more
instead:
use $j()
example:
// Use jQuery via $j(...)
$j(document).ready(function() {
$j("div").hide();
});
that's all
read new documentation about ajax in dynaform in this
or
Write this function
function ajax(url, callback, error, method, cache, async) {
async = async || true;
//alert(cache);
if (typeof(cache) == 'undefined') {
cache = false;
}
if (typeof(method) == 'undefined') {
method = 'GET';
}
if (window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari
{
xmlhttp = new XMLHttpRequest();
} else // code for IE5, IE6
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
if (typeof(callback) == 'function') {
callback(xmlhttp.responseText);
}
} else {
if (typeof(error) == 'function') {
error(xmlhttp.status);
} else {
alert('خطا : لطفا مجددا تلاش کنید.');
}
}
}
}
var d = new Date();
var n = d.getTime();
var getExplode = url.split("?");
scriptName = url;
param = '';
if (getExplode.length > 1) {
scriptName = getExplode[0];
param = getExplode[1];
if (cache == false) {
param = param + "&n=" + n;
}
} else {
if (cache == false) {
param = param + "n=" + n;
}
}
if (method.toLowerCase() == 'post') {
xmlhttp.open("POST", scriptName, async);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(param);
} else {
xmlhttp.open("GET", scriptName + '?' + param, async);
xmlhttp.send();
}
}
and use it like this
var url = ajaxUrl + "OperationRenovation.php?Command=GetDetail&IdDarkhast=" + ID + "&Code=" + Code + "&Mabna=" + Mabna;
ajax(url, function(Response) {
alert(response);
}, function() {
alert('مشکل در برقراری ارتباط با سرور');
}, 'post');

How to call multiple AJAX functions (to PHP) without repeating code

I have a little script which uses AJAX and PHP to display an image. You can see below that if I call the function mom() it looks in the PHP file index.php?i=mom and displays the image I'm looking for.
But I need the javascript to be lighter as I have 30 images and for each one I have to modify and copy the script below. Is there not a simpler way to have the functions be different and still call a different page?
<script type="text/javascript">
function mom()
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
function HandleResponse(response)
{
document.getElementById('mom').innerHTML = response;
}
</script>
My Trigger is this
<a href="#" onclick='mom();' />Mom</a>
<div id='mom'></div>
You could modify your function so it takes a parameter :
// The function receives the value it should pass to the server
function my_func(param)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
// Pass the received value to the handler
HandleResponse(param, xmlHttp.responseText);
}
}
// Send to the server the value that was passed as a parameter
xmlHttp.open("GET", "index.php?i=" + param, true);
xmlHttp.send(null);
}
And, of course, use that parameter in the second function :
function HandleResponse(param, response)
{
// The handler gets the param too -- and, so, knows where to inject the response
document.getElementById(param).innerHTML = response;
}
And modify your HTML so the function is called with the right parameter :
<!-- for this first call, you'll want the function to work on 'mom' -->
<a href="#" onclick="my_func('mom');" />Mom</a>
<div id='mom'></div>
<!-- for this secondcall, you'll want the function to work on 'blah' -->
<a href="#" onclick="my_func('blah');" />Blah</a>
<div id='blah'></div>
This should work (if I understand correctly)
<script type="text/javascript">
function func(imgName)
{
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
document.getElementById(imgName).innerHTML =
}
}
xmlHttp.open("GET", "index.php?i=mom", true);
xmlHttp.send(null);
}
</script>
MARTIN's solution will work perfectly.
By the way you should use some javascript framework for Ajax handling like jQuery.
It will make your life easy.
If you are having light weight images you preload the images on your page.
I solved this by making an array of in your case xmlHttp and a global variable, so it increments for each request. Then if you repeatedly make calls to the same thing (eg it returns online users, or, whatever) then you can actually resubmit using the same element of the array too.
Added example code:
To convert it to a reoccuring event, make a copy of these 2, and in the got data call, just resubmit using reget
var req_fifo=Array();
var eleID=Array();
var i=0;
function GetAsyncData(myid,url) {
eleID[i]=myid;
if (window.XMLHttpRequest)
{
req_fifo[i] = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
req_fifo[i] = new ActiveXObject("Microsoft.XMLHTTP");
}
req_fifo[i].abort();
req_fifo[i].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(i);
req_fifo[i].open("GET", url, true);
req_fifo[i].send(null);
i++;
}
function GotAsyncData(id) {
if (req_fifo[id].readyState != 4 || req_fifo[id].status != 200) {
return;
}
document.getElementById(eleID[id]).innerHTML=
req_fifo[id].responseText;
req_fifo[id]=null;
eleID[id]=null;
return;
}
function reget(id) {
myid=eleID[id];
url=urlID[id];
req_fifo[id].abort();
req_fifo[id].onreadystatechange = function(index){ return function() { GotAsyncData(index); }; }(id);
req_fifo[id].open("GET", url, true);
req_fifo[id].send(null);
}
The suggestions to parameterize your function are correct and would allow you to avoid repeating code.
the jQuery library is also worth considering. http://jquery.com
If you use jQuery, each ajax call would literally be this easy.
$('#mom').load('/index.php?i=mom');
And you could wrap it up as follows if you'd like, since you say you'll be using it many times (and that you want it done when a link is clicked)
function doAjax(imgForAjax) { $('#'+imgForAjax).load('/index.php&i='+imgForAjax);}
doAjax('mom');
It makes the oft-repeated ajax patterns much simpler, and handles the issues between different browsers just as I presume your getXMLhttp function does.
At the website I linked above you can download the library's single 29kb file so you can use it on your pages with a simple <script src='jquery.min.js'></script> There is also a lot of great documentaiton. jQuery is pretty popular and you'll see it has a lot of questions and stuff on SO. ajax is just one of many things that jQuery library/framework (idk the preferred term) can help with.

AJAX To Call and Run PHP Script

I have a working PHP script on my server and a HTML page with JavaScript and AJAX which I would like to call and run the PHP script. However, the AJAX responseText is displaying all the PHP code rather than running it. What do I need to do to only get the results of the PHP? Other examples I looked at used the responseText and it seemed to work out well, but not for me :(
Thanks,
elshae
My AJAX code is below...my PHP works fine, it has been tested :)
function ahah(url) {
//document.getElementById(target).innerHTML = ' Fetching data...';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {ahahDone(url);};
req.open("GET", url, true);
req.send("");
}
}
function ahahDone(url) {
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
var div = document.createElement('DIV');
div.innerHTML = req.responseText;
document.getElementById('chicken_contentDiv').appendChild(div);
} else {
" <div> AHAH Error:\n"+ req.status + "\n" +req.statusText + "</div>";
}
}
}
function load(name) {
ahah(name);
return false;
}
<div> + load('./getFiles.php') + </div> //called in a div
Ok here is the new code:
//Some stuff happens here, IMO think it's irrelevant to this issue...
//This is where the AJAX/JQuery calls the php
var info = new OpenLayers.Control.WMSGetFeatureInfo({
url: 'http://localhost:8080/geoserver/wms',
title: 'Identify features by clicking',
queryVisible: true,
eventListeners: {
getfeatureinfo: function(event){
map.addPopup( new OpenLayers.Popup.AnchoredBubble(
"chicken",
map.getLonLatFromPixel(event.xy),
null,
event.text + '<div> Hello Tibet :)</div>' + $('#chicken_contentDiv').load('http://localhost/mapScripts/getFiles.php'), //have also tried localhost:80, no diff
null,
true
));
}
}
});
map.addControl(info);
info.activate();
});
To your apache config or .htaccess file add this line AddType application/x-httpd-php .html so html files will be parsed with php interpreter.
Are you missing the <?php at the beginning of your getFiles.php file?
If the response contains actual PHP code, then it is not being processed by the PHP interpreter. Where are you running this? It is obvious that the web server is not properly configured to process PHP files.
EDIT:
The line you have:
event.text + '<div> Hello Tibet :)</div>' + $('#chicken_contentDiv').load('http://localhost/mapScripts/getFiles.php'),
is incorrect.. you don't want to append the outcome of the jQuery function. The output would always be an object. You just want to run that script, which would populate a DIV with an ID of chicken_contentDiv. (is that really the right DIV to put the details in?)
It should be at the end, after your var info declaration is closed and done.

Categories