Click event in node.js does not work - javascript

I am using Node.js + Express + Jade + Socket.io to set up click events in one browser to trigger a click on a button in another. I am having difficulty getting this to work. The code I have so far is:
Client side (index.jade):
var socket = io.connect('http://localhost:8080');
$('#buttonLeft').tap(function() {
socket.emit('keyLeft');
});
});
Server side:
var sockets = {};
io.sockets.on('connection', function (socket) {
socket.on('keyLeft', function(){
socket.broadcast.emit('keyLeft');
});
});
Another client side (index.php):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<link rel="stylesheet" href="slider-style.css" />
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<body>
<?php
$imagesTotal = 8; // SET TOTAL IMAGES IN GALLERY
?>
<div class="galleryContainer">
<div class="galleryPreviewContainer">
<div class="galleryPreviewImage">
<?php
for ($i = 1; $i <= $imagesTotal; $i++) {
echo '<img class="previewImage' . $i . '" src="images/image' . $i . '.jpg" width="900" height="auto" alt="" />';
}
?>
</div>
<div class="galleryPreviewArrows">
<a id="previousSlideArrow" href="#" class="previousSlideArrow"><</a>
<a id="nextSlideArrow" href="#" class="nextSlideArrow">></a>
</div>
</div>
<script type="text/javascript">
// init variables
var imagesTotal = <?php echo $imagesTotal; ?>;
var currentImage = 1;
var thumbsTotalWidth = 0;
$('a.galleryBullet' + currentImage).addClass("active");
$('a.thumbnailsimage' + currentImage).addClass("active");
$('div.description' + currentImage).addClass("visible");
// PREVIOUS ARROW CODE
$('a.previousSlideArrow').click(function() {
$('img.previewImage' + currentImage).hide();
$('a.galleryBullet' + currentImage).removeClass("active");
$('a.thumbnailsimage' + currentImage).removeClass("active");
$('div.description' + currentImage).removeClass("visible");
currentImage--;
if (currentImage == 0) {
currentImage = imagesTotal;
}
$('a.galleryBullet' + currentImage).addClass("active");
$('a.thumbnailsimage' + currentImage).addClass("active");
$('img.previewImage' + currentImage).show();
$('div.description' + currentImage).addClass("visible");
return false;
});
// ===================
// NEXT ARROW CODE
$('a.nextSlideArrow').click(function() {
$('img.previewImage' + currentImage).hide();
$('a.galleryBullet' + currentImage).removeClass("active");
$('a.thumbnailsimage' + currentImage).removeClass("active");
$('div.description' + currentImage).removeClass("visible");
currentImage++;
if (currentImage == imagesTotal + 1) {
currentImage = 1;
}
$('a.galleryBullet' + currentImage).addClass("active");
$('a.thumbnailsimage' + currentImage).addClass("active");
$('img.previewImage' + currentImage).show();
$('div.description' + currentImage).addClass("visible");
return false;
});
// ===================
</script>
<script src="http://mojoer.kr:8080/socket.io/socket.io.js"></script>
<script src="slide-script.js></script>
</body>
</html>
Any help would be really appreciated. Thanks~

I tried to reproduce your setup with the following code:
server:
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.get('/', function (req, res) {
res.render('index');
});
io.on('connection', function (socket) {
socket.on('left', function () {
socket.broadcast.emit('leftButtonClicked');
});
socket.on('right', function () {
socket.broadcast.emit('rightButtonClicked');
});
});
http.listen(3000, function(){
console.log('listening on port 3000');
});
jade client:
doctype html
html
body
h1 Testing socket.io
h3(id="status") not connected
buttons
button#leftButton Prev
button#rightButton Next
br
h3 actions:
p#actions
script(src="/socket.io/socket.io.js")
script.
var socket = io();
socket.on('connect', function() {
document.getElementById("status").innerHTML = "connected";
});
document.getElementById("leftButton").addEventListener('click', function () {
socket.emit('left');
document.getElementById("actions").innerHTML += "Prev button click sent<br>";
});
document.getElementById("rightButton").addEventListener('click', function () {
socket.emit('right');
document.getElementById("actions").innerHTML += "Next button click sent<br>";
});
html gallery:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.0.1/socket.io.js"></script>
</head>
<body>
<div>
<div id="preview" style="padding: 5px;"></div>
<div id="fullSize" class="fullgalleryPreviewImage" style="padding: 5px;"></div>
<div style="padding: 5px;">
<button id="previousSlideArrow" style="height: 4em; width=100px;"><</button>
<button id="nextSlideArrow" style="height: 4em; width=100px;">></button>
</div>
</div>
<script type="text/javascript">
// init variables
var imagesTotal = 8;
var currentImage = 1;
for (var i = 1; i <= imagesTotal; i++) {
document.getElementById('preview').innerHTML += '<img class="previewImage' + i + '"src="images/image' + i + '.jpg" + width="200" height="auto" style="margin-left: 2px;" />';
}
document.getElementById('fullSize').innerHTML = '<img src="images/image' + currentImage + '.jpg" + width="800" height="auto" />';
// PREVIOUS ARROW CODE
document.getElementById('previousSlideArrow').addEventListener('click', function () {
currentImage--;
if (currentImage === 0) {
currentImage = imagesTotal;
}
document.getElementById('fullSize').innerHTML = '<img src="images/image' + currentImage + '.jpg" + width="800" height="auto" />';
});
// NEXT ARROW CODE
document.getElementById('nextSlideArrow').addEventListener('click', function () {
currentImage++;
if (currentImage === imagesTotal + 1) {
currentImage = 1;
}
document.getElementById('fullSize').innerHTML = '<img src="images/image' + currentImage + '.jpg" + width="800" height="auto" />';
});
// socket.io
var socket = io("http://localhost:3000");
socket.on('connect', function () {
console.log('connected');
});
socket.on('leftButtonClicked', function () {
document.getElementById('previousSlideArrow').click();
});
socket.on('rightButtonClicked', function () {
document.getElementById('nextSlideArrow').click();
});
</script>
</body>
</html>
It works - when you click buttons in the jade client you can browse the gallery in the html client.
Please move the socket.io loader <script src="http://mojoer.kr:8080/socket.io/socket.io.js"></script> to the <head> section - if you have it at the end of the <body> it is not loaded yet when you execute var socket = io(<server address>); and you should see the error Uncaught ReferenceError: io is not defined in your browser's console.

Related

Why I am getting can not read proprty play of undefined?

<html>
<head>
<title>Doctor Page</title>
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>
<script>
window.onload = function callButtonClickEvent() {
setTimeout(function () { playSound(); }, 2000);
};
$( document ).ready(function() {
$('#source')[0].play();
});
function playSound() {
document.title = "(1) Doctor Page"
var filename = "eventually";
var mp3Source = '<source src="' + filename + '.mp3" type="audio/mpeg">';
var oggSource = '<source src="' + filename + '.ogg" type="audio/ogg">';
var embedSource = '<embed hidden="true" autostart="true" loop="false" src="' + filename + '.mp3">';
document.getElementById("sound").innerHTML = '<audio id="source">' + mp3Source + oggSource + embedSource + '</audio>';
}
</script>
</head>
<body>
<!-- Will try to play bing.mp3 or bing.ogg (depends on browser compatibility) -->
<button id="btnplay" onclick="setTimeout(function(){ playSound(); }, 500);">Play</button>
<div id="sound"></div>
</body>
</html>
You're trying to use <audio id ="source"> before creating it. Move the content of playSound to the document.ready block (before $('#source')[0].play();), and the problem is solved (I hope...).
Sorry for my English if I made mistakes.

jQuery Button only works once cannot change fahrenheit to celsius [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
<!DOCTYPE html>
<html>
<head>
<title>Local Weather</title>
<script
src="http://code.jquery.com/jquery-3.2.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/weather-icons/2.0.10/css/weather-icons-wind.css">
<link rel="stylesheet" type="text/css" href="Local Weather.css">
</head>
<body>
<script type="text/javascript" src="Local Weather.js"></script>
<div class="container">
<center>
<h1 id="degree"></h1>
<h1 id="name"></h1>
<h1 id="description"></h1>
</center>
</div>
</body>
</html>
var latitude, longitude, url, btn, temp;
var test = true;
$(document).ready(function()
{
$.getJSON("https://freegeoip.net/json/", function(data)
{
latitude = data.latitude;
longitude = data.longitude;
url = "https://fcc-weather-api.glitch.me/api/current?lat="+latitude+"&lon="+longitude;
$.getJSON(url, function(data2)
{
temp = data2.main.temp;
$("#degree").html(temp + '<button id="corf">℃</button>');
$("#name").html(data2.name);
$("#description").html(data2.weather[0].description + '<img id="icon" src='+ data2.weather[0].icon + '/>');
btn = $("#corf");
btn.click(function ()
{
if(test)
{
temp = (temp * 1.8) + 32;
$("#degree").html(temp + '<button id="corf">℉</button>');
test = false;
}
else
{
temp = (temp * 0.5556) - 32;
$("#degree").html(temp + '<button id="corf">℃</button>');
test = true;
}
});
});
});
});
Cannot change Celsius to Fahrenheit multiple times, what's wrong?
You are trying to bind the click event to the element which doesn't exists in the DOM. To make sure your events binding is proper you can use Event Delegation. Just add event to the parent element and check for the event.target. If event.target is the button, the do the proper calculation.
var latitude, longitude, url, btn, temp;
var test = true;
$(document).ready(function() {
$.getJSON("https://freegeoip.net/json/", function(data) {
latitude = data.latitude;
longitude = data.longitude;
url = "https://fcc-weather-api.glitch.me/api/current?lat=" + latitude + "&lon=" + longitude;
$.getJSON(url, function(data2) {
temp = data2.main.temp;
$("#degree").html(temp + '<button id="corf">℃</button>');
$("#name").html(data2.name);
$("#description").html(data2.weather[0].description + '<img id="icon" src=' + data2.weather[0].icon + '/>');
$('#degree').click(function(e) {
if (e.target.id === 'corf') {
var newTemp = 0;
if (test) {
newTemp = (temp * 1.8) + 32;
$("#degree").html(newTemp + '<button id="corf">℉</button>');
test = false;
} else {
newTemp = temp;
$("#degree").html(newTemp + '<button id="corf">℃</button>');
test = true;
}
}
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<script type="text/javascript" src="Local Weather.js"></script>
<div class="container">
<center>
<h1 id="degree"></h1>
<h1 id="name"></h1>
<h1 id="description"></h1>
</center>
</div>
</body>
Try this:
var latitude, longitude, url, btn, temp;
var test = true;
$(document).ready(function()
{
$.getJSON("https://freegeoip.net/json/", function(data)
{
latitude = data.latitude;
longitude = data.longitude;
url = "https://fcc-weather-api.glitch.me/api/current?lat="+latitude+"&lon="+longitude;
$.getJSON(url, function(data2)
{
temp = data2.main.temp;
$("#degree").html(temp + '<button id="corf">℃</button>');
$("#name").html(data2.name);
$("#description").html(data2.weather[0].description + '<img id="icon" src='+ data2.weather[0].icon + '/>');
btn = $("#corf");
$(document).on('click',btn,function ()
{
if(test)
{
temp = (temp * 1.8) + 32;
$("#degree").html(temp + '<button id="corf">℉</button>');
test = false;
}
else
{
temp = (temp - 32) / 1.8;
$("#degree").html(temp + '<button id="corf">℃</button>');
test = true;
}
});
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<script type="text/javascript" src="Local Weather.js"></script>
<div class="container">
<center>
<h1 id="degree"></h1>
<h1 id="name"></h1>
<h1 id="description"></h1>
</center>
</div>
</body>

localhost load xml file with js

ok i have my files on apache so i can read it localhost i have one issue cause iam new and i really cant understand how to load xml files with js i see all the topics in stuck overflow and iam stuck .....
i have the main htm file . should i change the path to var indexFile and var xmlFile to my localhost like this var indexFile="file:///C:/Apache24/htdocs/data/index.xml"; ??
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var direction=1;
var titleis="Loading.........";
function showLoading(){
//if (window.status.charAt(0)=="O"){direction=0}
//if (window.status.charAt(titleis.length-1)=="O"){direction=1}
if (direction==0){
window.status=window.status.charAt(titleis.length-1)+window.status.substr(0,titleis.length-1);
}else{
window.status=window.status.substr(1,titleis.length-1)+window.status.charAt(0);
}
}
window.status=titleis;
var timeID=setInterval("showLoading();", 100);
</script>
<script Src="scripts/config.js" language=jscript></script>
<script Src="scripts/general.js" language=jscript></script>
<script Src="inc/header.js" language=jscript></script>
<script src="scripts/grid.js"></script>
<script src="scripts/xml.js"></script>
<SCRIPT LANGUAGE="JavaScript">
// this page should never load inside of another frame
window.onerror = handleError;
var xmlHttp = new Active.XML.Table;
var xmlLoaded=false;
var xmlData;
var indexFile="data/Index.xml";
var xmlIndex =CreateXMLObj(false);
var hasOrders=false;
var idxLoaded=false;
var HtmlIdx;
var xmlFile="data/Catalogue.xml";
var RootTag = "CATALOGUE";
var RecordTag = "PART";
function InitSync()
{
if( "object" == typeof( top.deeptree ) && "unknown" == typeof( top.deeptree.Sync ) )
{
top.deeptree.Sync();
}
}
function SetTitle(name){
_Title = name
document.title =_Title;
}
function SetAsterisc(){
document.title =_Title + '*';
}
function loaddata(){
if (!xmlLoaded) {
if (!xmlHttp.isReady()){
window.status="Φόρτωση δεδομένων...";
xmlHttp.defineProperty("async",false);
xmlHttp.setURL(xmlFile);// provide data URL
xmlHttp.request();// start asyncronous data retrieval
window.status="Done";
}
xmlData=xmlHttp.getXML();
if (xmlHttp.isReady() && !xmlHttp.getAsync()){
xmlLoaded=true;
}else{
xmlLoaded=true;
}
}
return xmlLoaded;
}
function loadIndexes(){
if (!idxLoaded) {
window.status="Φόρτωση δεδομένων...";
if(xmlIndex.load(indexFile)){
idxLoaded=true;
}else{
idxLoaded=false;
alert( 'parseError : ' + xmlIndex.parseError.reason + '\n' +
'Code : ' + xmlIndex.parseError.errorCode + '\n' +
'Line : ' + xmlIndex.parseError.line + '\n' +
'Source : ' + xmlIndex.parseError.srcText + '\n' +
'Pos : ' + xmlIndex.parseError.linepos + '\n' +
'filepos : ' + xmlIndex.parseError.filepos + '\n'
,1,document.title);
}
window.status="Done";
}
return idxLoaded;
}
function strnull(value,_default){
if (value==null || value==""){
return _default;
}
return value;
}
function getNameID(AID){
if(AID<0){return}
return new String(getsafeData(xmlData,"//" + RecordTag + "[AID=" + AID + "]/NameID"));
}
function getPictureNo(AID){
if(AID<0){return}
return new String(getsafeData(xmlData,"//" + RecordTag + "[AID=" + AID + "]/PictureNo"));
}
function getOrder(AID){
if(AID<0){return}
return parseInt(getsafeData(xmlData,"//" + RecordTag + "[AID=" + AID + "]/Order"));
}
function getPicName(PicNo){
return getsafeData(xmlIndex,"//menuItem" + "[#id=" + PicNo + "]/#name");
}
function SetOrder(AID,value){
if(AID<0){return false;}
xmlData.selectSingleNode("//" + RecordTag+ "[AID=" + AID + "]/Order").text=value;
hasOrders=true;
return true;
}
function ClearOrder(AID){
if(AID<0){return false;}
return SetOrder(AID,"");
}
function ClearOrders(){
var StrQuery = "//" + RecordTag + "[Order>0]";
var xmlNodeLst = xmlData.selectNodes(StrQuery);
for(var i=0;i<xmlNodeLst.length;i++){
xmlNodeLst(i).selectSingleNode("Order").text="";
var id=xmlNodeLst(i).selectSingleNode("AID").text;
SetOrder(id,"");
}
hasOrders=false;
return true;
}
function InputOrder(AID){
if(AID>=0){
var oldvalue=getOrder(AID);
if(isNaN(oldvalue)){oldvalue=0};
var value=window.prompt("Εισάγετε ποσότητα για το αντ/κό με Αρ.Ονομαστικου :'" + getNameID(AID) +"'.",oldvalue);
if (value!=null){
if(isNaN(value)){value=0};
if (value!=oldvalue){
if (value > 0) {
SetOrder(AID,value);
return value;
}
}
}
}else{
return null;
}
}
</SCRIPT>
</HEAD>
<SCRIPT ID=clientEventHandlersJS LANGUAGE=javascript>
function window_onbeforeunload() {
if (hasOrders){
window.event.returnValue="\n---------------------------------------------------------------------\nΑν φύγετε από τη σελίδα θα χαθούν οι καταχωρήσεις σας.\n---------------------------------------------------------------------\nΠΑΤΗΣΤΕ OK για να φύγετε.\nΠΑΤΗΣΤΕ CANCEL για να παραμείνετε.\n\n";
}
}
</SCRIPT>
<SCRIPT LANGUAGE=javascript FOR=document EVENT=onreadystatechange>
document_onreadystatechange();
</SCRIPT>
<SCRIPT ID=clientEventHandlersJS LANGUAGE=javascript>
function document_onreadystatechange(){
if (document.readyState == "complete") {
clearInterval(timeID);
//window.showModelessDialog("logo1st.htm",self,'dialogwidth: 558px; DialogHeight:430px;status: no; resizable:no;help:no;maximize:no;minimize:no;');
window.status="Done";
}
}
</SCRIPT>
<SCRIPT LANGUAGE=javascript FOR=window EVENT=onbeforeunload>
window_onbeforeunload();
</SCRIPT>
<!---->
<script language=javascript>
var urlIs=QueryString('url')
if (urlIs==null || urlIs==''){urlIs='logo1st.htm';}
document.write('<FRAMESET name="FrmSet" onload="" rows="36,*" border="1" FRAMESPACING="0" TOPMARGIN="0" LEFTMARGIN="0" MARGINHEIGHT="0" MARGINWIDTH="0">');
document.write('<FRAME name="fraTop" src="top.htm" scrolling="no" border="0" frameborder="no" noresize TOPMARGIN="0" LEFTMARGIN="0" MARGINHEIGHT="0" MARGINWIDTH="0"></FRAME>');
document.write('<FRAMESET name="fstMain" cols="1,*" border="1" frameborder="1" FRAMESPACING="2" TOPMARGIN="0" LEFTMARGIN="0" MARGINHEIGHT="0" MARGINWIDTH="0">');
document.write('<FRAME name="fraLeftFrame" src="Left.htm?frame=true&selection=' + QueryString('selection') + '"scrolling="no" noresize TOPMARGIN="0" LEFTMARGIN="0" MARGINHEIGHT="0" MARGINWIDTH="0" FRAMEBORDER="1" BORDER="1"></FRAME>');
document.write('<FRAME name="fraRightFrame" src="' + urlIs + '?frame=true&hidetoc=false&selection=' + QueryString('selection') + '" FRAMEBORDER="no" BORDER="0" BORDERCOLOR="#b1c3c0"></FRAME>');
document.write('</FRAMESET>');
document.write('</FRAMESET>');
</script>
</HTML>
this code works on IE 5 I THINK BUT not ON latest browsers what i have to change for make it work my xml docs are in apache C:\Apache24\htdocs\data

How do I see what data AJAX is passing

I want to be able to see if the data that AJAX is passing is the correct data at the function sendToServer.
When the user submits the data that s/he wants, the submit function sends it to next.php. I want to see what next.php is receiving, how do I do this? It should be receiving the same as here:
$("#result").html(JSON.stringify(arr));
So that I can insert the data into a MySQL database.
next.php:
<?php
$data = json_decode(stripslashes($_POST['arr']));
foreach($data as $item){
echo $item;
// insert to db
}
?>
The code that I have so far is in the code snippet:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr);
$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
Your js is sending a post request therefore you should receive the sent data just as you receive a normal html form post.
try var_dump($_POST); to see under what index names are your data then you can use those index names to manipulate your data as you want.

AJAX is not passing data via POST to its intended URL

I want to pass an array through AJAX but I am not getting any feed back on what it is I am sending. I tried to do a var_dump($_POST); on the PHP side (next.php) but nothing is showing up. I'm guessing there is something wrong with my code.
function sendToServer(data) {
$.ajax({
type: "POST",
data: { arr: JSON.stringify(data) },
url: "next.php",
success: function() {}
});
}
next.php:
<?php
var_dump($_POST);
$data = json_decode(stripslashes($_POST['arr']));
foreach ($data as $item) {
echo $item;
// insert to db
}
?>
Full snippet of my code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style type="text/css">
<!-- #main {
max-width: 800px;
margin: 0 auto;
}
-->
</style>
</head>
<body>
<div id="main">
<h1>Add or Remove text boxes with jQuery</h1>
<div class="my-form">
<!-- <form action="next.php" method="post">-->
<button onclick="addAuthor()">Add Author</button>
<br>
<br>
<div id="addAuth"></div>
<br>
<br>
<button onclick="submit()">Submit</button>
<!-- </form>-->
</div>
<div id="result"></div>
</div>
<script type="text/javascript">
var authors = 0;
function addAuthor() {
authors++;
var str = '<br/>' + '<div id="auth' + authors + '">' + '<input type="text" name="author" id="author' + authors + '" placeholder="Author Name:"/>' + '<br/>' + '<button onclick="addMore(\'auth' + authors + '\')" >Add Book</button>' + '</div>';
$("#addAuth").append(str);
}
var count = 0;
function addMore(id) {
count++;
var str =
'<div id="bookDiv' + count + '">' + '<input class="' + id + '" type="text" name="book' + id + '" placeholder="Book Name"/>' + '<span onclick="removeDiv(\'bookDiv' + count + '\')">Remove</span>' + '</div>';
$("#" + id).append(str);
}
function removeDiv(id) {
$("#" + id).slideUp(function() {
$("#" + id).remove();
});
}
function submit() {
var arr = [];
for (i = 1; i <= authors; i++) {
var obj = {};
obj.name = $("#author" + i).val();
obj.books = [];
$(".auth" + i).each(function() {
var data = $(this).val();
obj.books.push(data);
});
arr.push(obj);
}
sendToServer(arr);
//$("#result").html(JSON.stringify(arr));
}
function sendToServer(data) {
$.ajax({
type: "POST",
data: {
arr: JSON.stringify(data)
},
url: "next.php",
success: function() {
}
});
}
</script>
</body>
</html>
The problem is when you try to echo the item. As $item is an object (stdClass), and the echo command expects a string, the echo command fails with "stdClass could not be converted to a string". You can either change to:
echo print_r($item, true);
or:
var_dump($item);

Categories