Using Jquery .each function in a PHP foreach loop - php

I am quite new to jquery, and i couldn't use .each function in a php foreach function.
I am trying to do a quantity, unit price, total price table.
I don't know how many table rows does user need, therefore used foreach function. Here is an example what i am trying to do:
my deneme2.php file :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width= <script type="text/javascript">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script>deneme5.js</script>
</head>
<body>
<?php
$arr=[1,2];
foreach ($arr as $key=>$val){ ?>
<div>
<input id="tst1"; type="text"; >
<input id="tst2"; type="text"; >
<input id="tst3"; type="text"; > <br><br>
</div>
<?php } ?>
<input id="asd"; type="submit"; value="hesapla">
</body>
</html>
And my deneme5.js file:
$(function(){
$("#asd").click(function(){
$("div").each(function(index){
var a=$("#tst1").val();
var b=$("#tst2").val();
var c= parseInt(a)*parseInt(b);
$("#tst3").val(c);
});
});
});
Can you help me? what am i doing wrong?

You have many syntax errors in your code. I have revised it a bit. Please compare it with yours and see where you have your mistakes.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<!-- here i have added your javascript code directly. You can include it like that: <script src="deneme5.js"></script>-->
<script>
$(function(){
$("#asd").click(function() {
$(".row").each(function(index, element){
var a = $(element).find(".tst1").val();
var b = $(element).find(".tst2").val();
var c = parseInt(a) * parseInt(b);
$(element).find(".tst3").val(c);
});
});
});
</script>
</head>
<body>
<?php
$arr=[1,2];
foreach ($arr as $key=>$val){ ?>
<!-- in the following i have switched your ids into classes because ids have to be unique. Furthermore html attributes do not have to be separated by ';' -->
<div class="row">
<input class="tst1" type="text">
<input class="tst2" type="text">
<input class="tst3" type="text"><br><br>
</div>
<?php } ?>
<input id="asd" type="submit" value="hesapla">
</body>
</html>
One of the things done here was to convert the use of ID's to classes. ID's cannot be duplicated on a page because it will cause problems with JavaScript and CSS.

Related

To print Random no in Php each second

I want to generate random no in php per second and want to display that after clicking the generate button. Below is the code for same
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<head>
<title>Random no Generator</title>
<meta content="text/html; charset=utf-8" http-equiv="content-type" />
</head>
<?php
if(isset($_GET['action'])=='submitfunc') {
submitfunc();
}else
//show form
?>
<body>
<form action="?action=submitfunc" method="post"> <p>
<input type="submit" value="Generate" /></p>
<p>
</form>
</body>
<?php
function submitfunc() {
while(1){
echo rand (5,10)."\n";
sleep(1);
echo rand (25,50)."\n";
sleep(1);
}
}
?>
</html>
Edit:
I want to insert no in database perodicaly so need this to work via php
As said, PHP is a server-side scripting language. This Fiddle may help.
<button id="gen">Generate</button>
<br/>
<div id="content">
</div>
<script type="text/javascript">
var int1 = null;
var int2 = null;
var br = $('<br/>');
$("#gen").on('click', function(){
int1 = setInterval(function(){
var span = $('<span/>').text(~~(Math.random()*5+5));
$("#content").append(span).append($('<br/>'));
},2000);
setTimeout(function(){
int2 = setInterval(function(){
var span = $('<span/>').text(~~(Math.random()*25+25));
$("#content").append(span).append($('<br/>'));
},2000);
},1000);
});
</script>

Can't refresh HTML page

I have a problem. I have made a HTML and PHP page with jQuery, jQuery-ui, jQuery mobile, then kineticjs. When switching to another page, do not refresh the whole page. I also tried using <meta http-equiv="refresh" content="URL=aa.php"> but did not work.
In that page I am also using php to get result from that PHP. Here is the code from my php page :
<?php
if ( isset($_POST['address']) && isset($_POST['prefix']) && isset($_POST['levels']) ) {
require_once 'convert.php';
$network = new Network($ip, $prefix, $levels);
print_html($network);
exit();
}
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="URL=aa.php">
<title>aa</title>
<link rel="stylesheet" href="css/jquery-ui.css" />
<link rel="stylesheet" href="css/jquery.mobile-1.3.0.css" />
<script src="js/jquery-1.9.1.js"></script>
<script src="js/jquery.mobile-1.3.0.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/kinetic-v4.3.2-beta.js"></script>
</head>
<body>
<div data-role="page">
<div data-role="header">
<h3>aa</h3>
</div>
<div data-role="content">
<h3>aa</h3>
<br />
<div>
<label for="address">Address:</label>
<input type="text" id="address">
<select id="prefix">
<?php for ( $i = 49; $i < 64; $i++ ) : ?>
<option value="<?php echo $i; ?>">/<?php echo $i; ?></option>
<?php endfor; ?>
</select>
<label for="subnet">Total Subnets: </label>
<input type="text" id="subnets">
<button class="btn" id="build"> Build It </button>
</div>
<div id="network"></div>
</div>
</div>
<script src="js/jquery.js"></script>
<script type="text/javascript">
$(function(){
$("#build").click(function(){
var subnets = parseInt( $("#subnets").val() );
var address = $("#address").val();
var prefix = $("#prefix").val();
var levels = $("#subnets").val();
$.post("aa.php", {address:address, prefix:prefix, levels:levels}, function(response){
$("#network").html(response);
$("#network > .branch").show();
$("#network .open-children").click(function(){
$(this).text('-');
$(this).parent().children(".branch").toggle();
return false;
});
});
});
});
</script>
</body>
</html>
whether the problem comes from too many javascript?
Meta refresh should work so:
<meta http-equiv="refresh" content="0;url=aa.php">
You can use it without JS.
<noscript><meta http-equiv="refresh" content="0;URL='?nojs=1'"></noscript>
Check if you have any errors in console and remove them. Also you should detect if you have mobile or PC version of browser and include either jquery-1.9.1.js or jquery.mobile-1.3.0.js
you can also use
window.location
with setInterval or setTimeout it'll do the same. But you can't have any JS errors.
you can use this javascript code for refresh your page:
document.location.reload();
or change your location if you want:
document.location = "http://google.com";
Try this,
<meta http-equiv="refresh" content="0;url=aa.php">

Saving tinymce textarea content to file

I have been trying to save tinymce editor textarea content to a .txt file for a while but without success yet.
This is my html file code:
<!Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>TinyMCE example</title>
<meta name="description" content="HTML5 Basic template">
<meta name="author" content="R Dickinson">
<link rel="stylesheet" href="css/styles.css?v=1.0">
<script src="js/scripts.js"></script>
<script type="text/javascript" src="jscripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
// General options
mode : "textareas",
});
</script>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<header>
<h1>test tinymce save</h1>
</header>
<nav>
</nav>
<section>
<form method="post" action="test.php">
<p>
<textarea name="content" style="width:50%"></textarea>
<input type="submit" value="Save" />
</p>
</form>
</section>
<aside>
</aside>
<footer>
</footer>
</body>
</html>
Now test.php
<?php
/*
* test.php
*/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>test tiny mce</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 0.21" />
</head>
<body>
<?php
echo(stripslashes($_POST['content']));
?>
<?php
$file = "data.txt";
$fp = fopen($file, 'w');
$data =(stripslashes($_POST['content']));
fwrite($fp, $data);
fclose($fp);
?>
</body>
</html>
I'm grateful for helpful replies to fix this-many thanks :-)
Update
Following the first answer below I have added triggerSave as:
<script language="Javascript">
function submitForm() {
tinyMCE.triggerSave();
document.forms[0].submit();
}
</script>
and
<form method="post" action="test.php">
<p>
<textarea name="content" style="width:50%"></textarea>
<!--<input type="submit" value="Save" />-->
Submit Form
</p>
but still no success...More help gratefully received
UPDATE 2
Here is my jQuery TinyMCE version:
<!Doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Sample WebPage</title>
<meta name="description" content="HTML5 Basic template">
<meta name="author" content="R Dickinson-see sitepoint etc">
<link rel="stylesheet" href="css/styles.css?v=1.0">
<script src="js/scripts.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.3");
</script>
<!-- Load jQuery build -->
<script type="text/javascript" src="jscripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
tinyMCE.init({
mode : "textareas"
});
</script>
<!--[if lt IE 9]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
</head>
<body>
<header>
<h1>Enter the main heading, usually the same as the title.</h1>
</header>
<nav>
</nav>
<section>
<!-- OF COURSE YOU NEED TO ADAPT ACTION TO WHAT PAGE YOU WANT TO LOAD WHEN HITTING "SAVE" -->
<form method="post" action="show.php">
<p>
<textarea name="content" cols="50" rows="15">This is some content that will be editable with TinyMCE.</textarea>
<input type="submit" value="Save" />
</p>
</form>
</section>
<aside>
</aside>
<footer>
</footer>
</body>
</html>
The question itself comes down to :
How to save HTML content of TinyMCE into a file.
Well, first of all, you need:
1) Get content of editor
2) Send this content to PHP script
3) Implement some function that would save that content into a file
Getting content
Make sure you are getting it the way it should work.
For example,
<script type="text/javascript">
window.onload = function(){
var btn = document.getElementById('SubmitBtn');
btn.onclick = function(){
//This MUST alert HTML content of editor.
alert( tinyMCE.activeEditor.getContent() );
}
}
</script>
<input type="button" id="SubmitBtn" value="Get HTML content"/>
Sending content to PHP script
All you need to do is to send value of the method tinyMCE.activeEditor.getContent() to PHP script.
Well, you should use Jquery-AJAX for that.
Assume that you included jquery.js into script tag in the head section, the next step would be sending JavaScript variable to PHP script
It would be similar to this one:
<script type="text/javascript">
$(function(){
var url = "path_to_your_php_script.php";
$("#SomeSubmitButton").click(function(){
//"content" will PHP variable
$.post(url, { "content" : tinyMCE.activeEditor.getContent() }, function(respond){
if ( respond == ){
alert('Content saved to file');
return;
} else {
//Error message assumed
alert(respond);
}
});
});
});
</script>
PHP script
Since we were sending "content" this one will be populated in $_POST superglobal
<?php
if ( isset($_POST['content']) ){
//This is what you want - HTML content from tinyMCE
//just treat this a string
if ( save_html_to_file($_POST['content'], '/some_file.html') ){
//Print 1 and exit script
die(1);
} else {
die('Couldnt write to stream');
}
}
/**
*
* #param string $content HTML content from TinyMCE editor
* #param string $path File you want to write into
* #return boolean TRUE on success
*/
function save_html_to_file($content, $path){
return (bool) file_put_contents($path, $content);
}
So after execution this you should get back alert with message of success.
You should update your TinyMCE instances before submitting your form. Use this javascript:
tinyMCE.triggerSave();
I usually put this in a function and call it on onsubmit event of form.
There is already different questions around this topic in Stackoverflow.

AJAX/PHP simple code fails to work

I was following a tutorial to understand how AJAX/PHP works but i'm having an issue.
Let me start with the code.
escalationTest.php:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<form>
<input type="text" id="name" placeholder="Enter Name.." /> <br>
<input type="text" id="age" placeholder="Enter Name.." />
<input type="button" value="Submit" onClick="post();" />
</form>
<div id="result"></div>
<script type="text/javascript">
function post()
{
var name= $('#name').val();
var age= $('#age').val();
$.post('escalation.php',{postname:name,postage:age},
function(data)
{
$('#result').html(data);
});
}
</script>
</body>
</html>
escalation.php:
<?php
echo "working";
?>
I've typed the code exactly how its in the tut. From its output when i click the submit button i should "working" in the result div which is not happening.
What am i doing wrong here..?
Thanks.
<script type="text/javascript" src="jquery.min.js"></script>
Download a version of jQuery and then link to it with this script tag.
While you can link to an online version, it's not ideal for eventual production use and you should definitely get a local copy.
add the folowing line to your head tag
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
This is a pretty simple fix - you're missing jQuery. Add the following:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
in your head element.

google custom search can't work

Here is the test.html file code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-hans" xml:lang="zh-hans">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>
</head>
<body>
<div class="fr_search">
<form action="cse.php" accept-charset="UTF-8" method="post"
id="search-theme-form">
<input type="text" maxlength="128" name="search_theme_form"
id="edit-search-theme-form-1" size="15" value="" class="form-text" />
<input type="image" name="submit" id="edit-submit"
class="form-submit" src="images/search_btn_top.gif" /></div>
</form>
</div>
</body>
</html>
I put the code which generated by the http://www.google.com/cse/manage/create?hl=en. The
"Sites to search" I entered that was http://stackoverflow.com. When I put the generated code into the cse.php. Then put the cse.php and test.html into my local php enviroment. When I entered the text "php" into the search textbox and click the search button. But there is no any result on my search result page. What's wrong with my steps and code? thank you.
Here is the cse.php file code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>test search</title>
</head>
<body>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
google.load('search', '1', {language : 'en'});
google.setOnLoadCallback(function()
{
var customSearchControl = new google.search.CustomSearchControl ('011247711644571852159:xe2ytn1hwsa');
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
customSearchControl.draw('cse');
}, true);
</script>
<link rel="stylesheet" href="http://www.google.com/cse/style/look/default.css"
type="text/css" />
<?php echo 'test'; ?>
</body>
</html>
I'm not sure where to start with your code, but with a fresh code snippet from the Custom Search code generator, you can pass a query string to the CustomSearchControl. With code borrowed from here, something like this should work:
<div id="cse">Loading…</div>
<script src="http://www.google.com/jsapi"></script>
<script>
// Extract user's query from the URL
function getQuery() {
var url = '' + window.location;
var queryStart = url.indexOf('?') + 1;
if (queryStart > 0) {
var parts = url.substr(queryStart).split('&');
for (var i = 0; i < parts.length; i++) {
if (parts[i].length > 2 && parts[i].substr(0, 2) == 'q=') {
return decodeURIComponent(parts[i].split('=')[1].replace(/\+/g, ' '));
}
}
}
return '';
}
google.load('search', '1', {language:'en' });
google.setOnLoadCallback(function() {
var cseControl = new google.search.CustomSearchControl('ID_GOES_HERE');
cseControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
cseControl.draw('cse');
// Execute a query based on the query string
cseControl.execute(getQuery());
}, true);
</script>
So, for example that would go in your cse.php page (although there's no PHP in there at this stage) and your initial page's form something like:
<form action="cse.php" method="get">
<input name="q"> <input type="submit">
</form>
Get rid of the http:// in the sites to search bit.

Categories