I have to pass variables from javascript to php. My code is given below:
<script>
function getValue(val,val2){
window.a = val;
window.b = val2;
}
function getValue2(val,val2){
window.c = val;
window.d = val2;
}
function sendvar(){
if(window.a === 'undefined'){
window.a = 0;
}
if(window.b === 'undefined'){
window.b = 0;
}
if(window.c === 'undefined'){
window.c = 0;
}
if(window.d === 'undefined'){
window.d = 0;
}
location.href = "count.php?id="+window.a + "&optionname1=" + window.b + "&id=" + window.c + "&optionname1=" + window.d
</script>
<img src="img1.jpg" onclick="getValue('yes','1');">
<img src="img2.jpg" onclick="getValue2('no','1');">
<button onclick="sendvar();">Click me</button>
When getValue function call so only the values of this function pass in href other values should be zero and when getValue2 function call so only the values of this function pass in href other values should be zero. But this is no happening right now.
Please tell me where i am wrong?
window.a would be equal to undefined without the quotes. typeof would be equal to "undefined" with the quotes.
if(typeof a === 'undefined'){
window.a = 0;
}
if(typeof b === 'undefined'){
window.b = 0;
}
if(typeof c === 'undefined'){
window.c = 0;
}
if(typeof d === 'undefined'){
window.d = 0;
}
As a solution to your problem please refer the below code snippet
<script>
var a=0;
var b=0;
var c=0;
var d=0;
function getValue(val,val2)
{
window.a = val;
window.b = val2;
window.c=0;
window.d=0;
}
function getValue2(val,val2)
{
window.c = val;
window.d = val2;
window.a=0;
window.b=0;
}
function sendvar(){
location.href = "count.php?id="+window.a + "&optionname1=" + window.b + "&id=" + window.c + "&optionname1=" + window.d
}
</script>
<img src="img1.jpg" onclick="getValue('yes','1');">
<img src="img2.jpg" onclick="getValue2('no','1');">
<button onclick="sendvar();">Click me</button>
Related
I try to make the php and ajax back button work by using pushState() and popstate(). I got the pushState somehow working, but the popState is not.
for ($i=1; $i<=$lastPage; $i++) {
//$pageLink[] = ''.$i.'';
$pageLink[] = ''.$i.'';
};
java script below.
<script>
function showmerchantitems(str, str2) {
var elements = document.getElementsByClassName("itemwrapper");
if (str.length == 0) {
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = "";
}
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
for (var i = 0; i < elements.length; i++) {
elements[i].innerHTML = this.responseText;
}
}
};
xmlhttp.open("GET", "ajax.php?action=merchantlistpage&merchant_id=" + str + "&p=" + str2, true);
xmlhttp.send();
history.pushState(null, "", "ajax.php?action=merchantlistpage&merchant_id=" + str + "&p=" + str2);
$(window).bind("popstate", function(){
$.getScript(location.href);
});
}
}
</script>
I'm trying to read some output in PhantomJS with PHP, but I didn't find the trick how to deal with it. Anyone did it before? Are there some solutions?
var page = require('webpage').create();
page.open('http....', function(status) {
if (status !== 'success') {
console.log('Unable to access network');
} else {
page.evaluate(function() {
var list = document.querySelectorAll('div.resume');
for (var i = 0; i < list.length; i++){
console.log((i + 1) + ":" + list[i].innerText);
}
});
}
phantom.exit();
});
and in php
$result = shell_exec($cmd...);
print($result);
I currently have a table that is being populated by a MySQL table, in turn i want to take the data from these cells and use them to create a simulated real time update, i have it working however due to having multiple rows im using for loops in the javascript functions and i believe this is causing the other functions not to run and i cannot figure out a way round it.
Javascript Code:
var seconds = 5;
var divid = "status";
var url = "boo.php";
var timeout;
function refreshdiv(){
// The XMLHttpRequest object
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
}
catch (e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
}
catch (e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){
alert("Your browser does not support AJAX.");
return false;
}
}
}
// Timestamp for preventing IE caching the GET request
fetch_unix_timestamp = function()
{
return parseInt(new Date().getTime().toString().substring(0, 10))
}
var timestamp = fetch_unix_timestamp();
var nocacheurl = url+"?t="+timestamp;
// The code...
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4){
document.getElementById(divid).innerHTML=xmlHttp.responseText;
setTimeout('refreshdiv()',seconds*1000);
}
}
xmlHttp.open("GET",nocacheurl,true);
xmlHttp.send(null);
}
// Start the refreshing process
var seconds;
window.onload = function startrefresh(){
setTimeout('refreshdiv()',seconds*1000);
}
function runningtime(int) {
if(int == 0) { //if there is data
console.log("int=0 so no data is present, int: " + int);
} else if(int == 1){
var isRunning = new Array();
isRunning[0] = " ";
for (var i=0; i < 3; i++) {
var bool = 'running' + i;
console.log("Running = " + bool);
running = document.getElementById(bool).innerHTML.substring(10,11);
console.log("running: " + running);
if(isRunning[i] == "1") {
var time = 'Time' + i;
a= document.getElementById(time).innerHTML;
console.log("a= " + a);
hour=a.substring(0,2);
min= a.substring(3,5);
sec= a.substring(6,8);
sec==sec++;
if (min<=9) { min="0"+min; }
if (sec<=9) { sec="0"+sec; }
time = (hour + ":" + min + ":" + sec + " ");
if (document.getElementById) { document.getElementById(time).innerHTML = time; }
else if (document.layers) {
document.layers.theTime.document.write(time);
document.layers.theTime.document.close(); }
} else {
//Do nothing
return;
}
}
timeout = setTimeout("runningtime(1)", 1000);
}
}
function experiencehour(exp) {
if(exp == 0) { //if there is dexphourtexphour
console.log("exp=0 so no data is present, exp: " + exp);
} else if(exp == 1){
var isRunning = new Array();
isRunning[0] = " ";
for (var i=0; i < 3; i++) {
var bool = 'running' + i;
console.log("Running = " + bool);
running = document.getElementById(bool).innerHTML.substring(10,11); //checks if bot running
console.log("running: " + running);
if(isRunning[i] == "1") {
var exph = 'Exph' + i;
var expg = 'Exp' + i;
exphour = document.getElementById(exph).innerHTML; //exphour
currexp = document.getElementById(exp).innerHTML; //current gained exp
exphour =parseInt(exphour);
currexp =parseInt(currexp);
console.log("currexp= " + currexp);
console.log("exphour= " + exphour);
expmin = exphour/60;
console.log("expmin= " + expmin);
expsec = Math.round(expmin/60);
console.log("expsec= " + expsec);
newtotalexp = currexp + expsec;
console.log("newtotalexp= " + newtotalexp);
if (document.getElementById) { document.getElementById(exp).innerHTML = newtotalexp; } //writing new exp
else if (document.lexphouryers) {
document.lexphouryers.theTime.document.write(time);
document.lexphouryers.theTime.document.close(); }
} else {
//Do nothing
return;
}
}
timeout = setTimeout("experiencehour(1)", 1000);
}
}
function variable1hour(var1) {
if(var1 == 0) { //if there is dvar1hourtvar1hour
console.log("var1=0 so no data is present, var1: " + var1);
} else if(var1 == 1){
var isRunning = new Array();
isRunning[0] = " ";
for (var i=0; i < 3; i++) {
var bool = 'running' + i;
console.log("Running = " + bool);
isRunning[i] = document.getElementById(bool).innerHTML.substring(10,11); //checks if bot running
console.log("isRunning = " + isRunning[i]);
if(isRunning[i] == "1") {
var varh = 'Varh' + i;
var varg = 'Var' + i;
console.log("Varh = " + varh);
console.log("Var = " + varg);
var1hour = document.getElementById(varh).innerHTML; //var1hour
currvar1 = document.getElementById(varg).innerHTML; //current gained var1
var1hour =parseInt(var1hour);
currvar1 =parseInt(currvar1);
console.log("currvar1= " + currvar1);
console.log("var1hour= " + var1hour);
var1min = var1hour/60;
console.log("var1min= " + var1min);
var1sec = Math.round(var1min/60);
console.log("var1sec= " + var1sec);
newtotalvar = currvar1 + var1sec;
console.log("newtotalvar= " + newtotalvar);
if (document.getElementById) { document.getElementById(varg).innerHTML = newtotalvar; } //writing new var1
else if (document.lvar1houryers) {
document.lvar1houryers.theTime.document.write(time);
document.lvar1houryers.theTime.document.close();
}
} else {
//Do nothing
return;
}
}
timeout = setTimeout("variable1hour(1)", 1000);
}
}
function stopScript() {
console.log("Stopping script");
clearTimeout(timeout);
}
function startScript(i) {
variable1hour(i);
experiencehour(i);
runningtime(i);
}
Any ideas on how i can get around this so i can get all 3 functions running simultaneously.
I have checked console and im not getting any errors that would stop them from running.
You can't have simultaneously in JS. But you can simulate simultaneous a bit in JS.
Take a look at underscore's defer method.
http://underscorejs.org/#defer
It'd work like this:
Take the loop body and wrap it up in a function
Each iteration through the for loop, make a call to the function using defer
That's basically it. Doing that will allow other functions to "interrupt" any given process (function) and thus "share" the execution thread.
A standard JS implementation w/out defer. I'm trying to simulate the closer of defer. The key takeaway here is that, while the calls still execute in the order that they were queued, all get "started" before any one of them completes. In the case of AJAX async requests, the async response should be able to inject itself between any two loop iterations. You can also set data processing by using slight delays
http://jsfiddle.net/t2z9A/
for(var i = 0; i != 5; ++i)
{
(function(index)
{
document.getElementById('id' + index).innerHTML = 'started...';
setTimeout(function()
{
// kill some time
var str = '';
for(var j = 0; j != 10000000; ++j)
str = str + ' ';
document.getElementById('id' + index).innerHTML = 'Function: 1. Index: ' + index + ' - ' + new Date().getTime();
}, index);
})(i);
}
for(var i = 5; i != 10; ++i)
{
(function(index)
{
document.getElementById('id' + index).innerHTML = 'started...';
setTimeout(function()
{
// kill some time
var str = '';
for(var j = 0; j != 1000000; ++j)
str = str + ' ';
document.getElementById('id' + index).innerHTML = 'Function: 2. Index: ' + index+ ' - ' + new Date().getTime();
}, 1);
})(i);
}
I'm using this chat http://tutorialzine.com/2010/10/ajax-web-chat-php-mysql/ and I tried to turn on the bbcodes but: http://imageshack.us/photo/my-images/827/bbcodes1.png/
I tried to replace in
scripts.js
text : text.replace(/</g,'<').replace(/>/g,'>')
with
text : text.replace(/</g,'<').
replace(/>/g,'>').
replace(/\[b\]((\s|.)+?)\[\/b\]/,'<b>\\1</b>')
This is my bbcode function, you can edit the codes variable to support more bbcode. For now, it support only [b], [i], [u], [url], [img].
[read] is my special bbcode for my website
function bbcode(text){
var codes = {};
codes['url'] = {
params : {
href : ''
},
html: "$text"
};
codes['b'] = {
params : {
},
html : "<b>$text</b>"
};
codes['i'] = {
params : {
},
html : "<i>$text</i>"
};
codes['u'] = {
params : {
},
html : "<u>$text</u>"
};
codes['img'] = {
params : {
},
html : "<img src=\"$text\" />"
};
codes['read'] = {
params : {
},
text : function(text){
for(var x in codes){
text = text.replace(new RegExp('\\[' + x + '\\]','gi'), '').replace(new RegExp('\\[\\/' + x + '\\]','gi'), '');
}
return encodeURIComponent(text);
},
process: function(text){
return text;
},
html : "$text <object type=\"application/x-shockwave-flash\" data=\"" + GLOBALS.baseUrl + "/player_mp3_maxi.swf\" width=\"200\" height=\"20\"><param name=\"movie\" value=\"" + GLOBALS.baseUrl + "/player_mp3_maxi.swf\" /><param name=\"bgcolor\" value=\"#ffffff\" /><param name=\"FlashVars\" value=\"mp3=http://api.ispeech.org/api/rest?apikey%3Ddeveloperdemokeydeveloperdemokey%26action%3Dconvert%26voice%3Dusenglishfemale1%26text%3D$TEXT&width=200&showslider=1\" /></object>"
};
text = text.replace(/\</g, '<').replace(/\>/g, '>');
var nomore = false;
while(!nomore){
var matches = text.match(/\[([^\]]+)\]/gi);
if(matches == null)
return text;
nomore = true;
for(var i = 0; i < matches.length; i++){
var code = matches[i].substring(1, matches[i].length - 1);
var parts = code.split(/\s+/);
if(typeof codes[parts[0]] == 'object'){
//is exist
var obj = {};
//get the params
for(var j = 1; j < parts.length; j++)
{
var temp = parts[j].split('=');
if(typeof codes[parts[0]].params[temp[0]] != 'undefined'){
obj[temp[0]] = (temp.length > 1) ? (temp[1].indexOf('"') == 0 ? temp[1].substring(1, temp[1].length - 1) : temp[1]) : '';
}
}
//find the text
var index = text.indexOf(matches[i]);
var index2 = text.indexOf('[/'+parts[0]+']', index);
if(index2 == -1)
index2 = text.length;
var t = text.substring(index + matches[i].length, index2);
if(typeof codes[parts[0]].process == 'function'){
t = codes[parts[0]].process(t);
}if(typeof codes[parts[0]].text == 'function'){
t2 = codes[parts[0]].text(t);
}
var html = codes[parts[0]].html;
for(var x in obj)
html = html.replace("$" + x, obj[x]);
html = html.replace(/\$text/g, t);
if(typeof codes[parts[0]].text == 'function'){
html = html.replace(/\$TEXT/g, t2);
}
text = text.substr(0, index) + html + text.substr(index2 + parts[0].length + 3);
nomore = false;
}
}
}
text = text.replace(/\n/g, "<br />");
return text;
}
You can use this by:
text: bbcode(text)
Like the str_shuffle() function in PHP, is there a function similar in shuffling the string in javascript ?
Please help !
No such function exist, you'll write one yourself. Here's an example:
function shuffle(string) {
var parts = string.split('');
for (var i = parts.length; i > 0;) {
var random = parseInt(Math.random() * i);
var temp = parts[--i];
parts[i] = parts[random];
parts[random] = temp;
}
return parts.join('');
}
alert(shuffle('abcdef'));
You could use php.js implementation:
http://phpjs.org/functions/str_shuffle:529
No, there is no inbuilt method of String that will randomise the character sequence.
Here's my versinof the php.js function
function str_shuffle (str) {
var newStr = [];
if (arguments.length < 1) {
throw 'str_shuffle : Parameter str not specified';
}
if (typeof str !== 'string') {
throw 'str_shuffle : Parameter str ( = ' + str + ') is not a string';
}
str = str.split ('');
while (str.length) {
newStr.push (str.splice (Math.floor (Math.random () * (str.length - 1)) , 1)[0]);
}
return newStr.join ('');
}
You could also do it as a prototype:
String.prototype.shuffle = function() {
var parts = this.split('');
for (var i = 0, len = parts.length; i < len; i++) {
var j = Math.floor( Math.random() * ( i + 1 ) );
var temp = parts[i];
parts[i] = parts[j];
parts[j] = temp;
}
return parts.join('');
};
Using it like so:
var myString = "Hello";
myString = myString.shuffle();
I would recommend lodash shuffle function.
const result = _.shuffle('my_string');