Can't pass list items as session variables in php - javascript

I have an order page. I choose an item then add to the order list with javascript. The list can contain many items. I want to pass these items as session variables into the order confirmation page.
Here is what I did;
This is javascript code to add items to the orderlist, there is no problem in that part. I append the selected item when button clicked.
$('#addToCartButton').click(function(){
var toAdd=$("#chooseItem option:selected").text();
var itemNbr1=$("#itemNbr1").val();
var cupSize=$("#cupSize option:selected").text();
var milkType=$("#milkType option:selected").text();
var cafein="";
if ($("#cafein").is(':checked')==true){
var cafein="Kafeinsiz";
};
if(toAdd !== defaultSelectFormText && itemNbr1 >=1){
$('#defaultText').remove();
$('.orderList').append('<p id="items">' + itemNbr1 + ' Adet ' + cafein + ' ' + cupSize + ' ' + milkType + ' ' + toAdd + '<span class="extra">Sipariş listesinden çıkarmak için tıklayın!</span>' + '</p>');
};
});
This is html part, when I push the firstConfirmButton it works, no problem. But in the php part I can't pass the items as session variables.
<form method="post" action="">
<div class="col-md-5">
<h3 align="center">Sipariş Listesi</h3>
<ul class="orderList" name="orderList"></ul>
</div>
</form>
<form role="form" method="post" action="">
<div id="firstConfirmButton">
<button type="submit" name="firstConfirmButton" class="btn btn- primary btn-lg">Onayla</button>
</div>
</form>
This is php part, I saw "I'm here" . $_SESSION['FirstName'] part but $_SESSION['OrderList'] don't work;
<?php
require("includes/db.php");
require("includes/functions.php");
session_start();
if (isset($_POST['firstConfirmButton'])) {
$_SESSION['OrderList'] = $_POST['orderList'];
echo "I'm here" . $_SESSION['FirstName'] . $_SESSION['OrderList'];
}
?>
What is the problem, I stuck in that point.

Related

Mystery characters appear when I use insertAdjacentHTML("beforeend" ... to add an element to the DOM

I'm relatively new to javascript and php and I have been doctoring around with this problem for hours with no success.
I am creating a list on a webpage where the list items are retrieved from a database. The php code for the list creation looks like this:
$options = get_option( 'psb_config' );
$n = 0;
echo '<ul id="session-type-list">';
foreach ( $options['type'] as $t ) {
$html = '<li id="' . $t . '-field"><input id="' . $t . '-psb" type="text" class="type-btn" size="20%" value="' . $t . '" name="psb_config[type][' . $n . ']">';
$html .= '<input type="button" class="button" value="remove" onclick="removeTypeButton(&#34' . $t . '-field&#34)"></li>';
echo $html;
$n++;
}
echo '</ul>';
Each entry in this list has text input field and a remove button with an onClick function call onclick="removeTypeButton(&#34' . $t . '-field&#34)">. The removeTypeButton() function is a simple javascript:
function removeTypeButton( id ) {
document.getElementById( id ).remove();
}
and it works fine.
I also want the user to be able to add fields to the list and I have an Add Session Button at the end of the list which calls the following javascript function:
function addTypeButton( n ) {
var node = document.getElementById("session-type-list");
var id = '\"field-' + n + '\"';
var html = '<li id=' + id + '>';
html += '<input id="psb-' + n + '" type="text" class="type-btn" size="20%" placeholder="new shoot type" name="psb_config[type][' + n + ']">';
html += '<input id="btn-' + n + '" type="button" class="button" value="remove" onClick="removeTypeButton(' + id + ')"></li>';
node.insertAdjacentHTML("beforeend", html);
}
This function in general works as expected with one exception: after it inserts the text field and the remove button at the end of the <ul> list the HTML for the remove button becomes scrambled.
My HTML string is:
<input id="btn-' + n + '" type="button" class="button" value="remove" onClick="removeTypeButton(' + id + ')"></li>
and when I inspect the element in the browser the string looks like this:
<input id="btn-10" type="button" class="button" value="remove" onclick="removeTypeButton(" field-10")"="">
The removeTypeButton(" field-10")"=""> argument is screwed up! There are additional quotation marks and an equal sign.
I've been trying to escape the quotation marks and other shenanigans including jQuery but with no success. It appears that the string is interpreted as if the onClick function ends after the ( and the argument is interpreted as another tag.
So my question is: what am I doing wrong? I've been googling this for hours and stackoverflow is my last resort.
Any tips are highly appreciated.
If you view the page source, rather than inspecting the element, you'll find it ends up like this
onClick="removeTypeButton("field-10")">
The double quotes within the double quotes is likely confusing the browser. Convert the inner quotes to singles.
var id = '\'field-' + n + '\'';
This should have the desired effect:
onClick="removeTypeButton('field-10')">

JSON get data using post-method

I want to get a JSON file from another server xyz.com (not writhing here original site name for safety) for my HTML page but the problem is that the website xyz.com only supports HTTP POST requests.
To check if my HTML code is working fine I use HTTP GET method and upload JSON data on another site that supports HTTP GET request. And I found that it is working fine. But when I try for HTTP POST method it is not working. Can you help me?
I am using currently and working fine
<script>
$(function() {
var people = [];
$.get('https://api.myjson.com/bins/c307c',function(data) {
$.each(data.video, function(i, f) {
HTML CODE FOR xyz.com and it also return a .json file
<html>
<head>
<form action="https://www.xyz.php" method="POST" >
<div class="container" style="width:100%;">
<center></center>
</div>
<div class="container" style="width:100%;">
<label for="userId"><b>UserId</b></label>
<input type="number" placeholder="Enter Your User Id" name="userId" autofocus required>
<label for="Passkey"><b>Passkey</b></label>
<input type="number" placeholder="Enter Passkey" name="Passkey" required>
<button type="submit" >GET Json File From Server</button>
</div>
</form>
This is i tried but not working
<script>
$(function() {
var people = [];
$.post('https://xyz.php', usedId=5&passkey=55, function(data) {
$.each(data.video, function(i, f) {
Try this way code
$.post( "https://xyz.php", { usedId: 5, passkey: 55},
function(data) {
//your code
} );
Please make necessery change so that when i click on button it take data from server and show in a table format
<html>
<head>
<form action="https://xyz.php" method="POST" >
<div class="container" style="width:100%;">
<center></center>
</div>
<div class="container" style="width:100%;">
<label for="userId"><b>UserId</b></label>
<input type="number" placeholder="Enter Your User Id" name="userId" autofocus required>
<label for="passKey"><b>Passkey</b></label>
<input type="number" placeholder="Enter Passkey" name="passKey" required>
<button type="submit" >GET DATA</button>
</div>
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function() {
var people = [];
$.post( "xyz.php",function(data) {
$.each(data.video, function(i, f) {
var link = "https://www.youtube.com/embed/"+ f.video;
var tblRows = "<tr>" +
"<td>" + f.videoName + "</td>" + "<td>" + f.date + "</td>" + "<td>" + f.time + "</td>" +
"<td>" + f.videoDuration + "</td>" + "<td>" + f.liveStatus + "</td>" + "<td><a target='_blank' href='"+link+"'>"+link+"</a></td>" + "</tr>";
$(tblRows).appendTo("#userdata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "userdata" width="50%" border="2">
<thead>
<th>VIDEO NAME</th>
<th>DATE</th>
<th>TIME</th>
<th>DURACTION</th>
<th>LIVE STATUS</th>
<th>LINK</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</html>
Some changes I suggest:
Give the form an ID, in this case login seems like an appropriate ID
Standardize your capitalization for form fields
Here's some code to get you started. You'll notice I'm creating your data twice. Decide if you want to build your data by hand or use jQuery's serialization to do it for you. Since this is a simple form, the latter is probably fine.
I'm also getting the AJAX endpoint right from the form so you aren't repeating yourself there.
// when the document has loaded...
$(document).ready(function () {
// if the user is already logging in
var login = false;
// when the form is submitted...
$('#login').on('submit', function (event) {
// block the form if it's already been submitted
if (login) {
event.stopPropagation();
event.preventDefault();
return;
}
// lock the form
login = true;
// get a handle on the form
// I use $ as a prefix to differentiate jQuery objects
// currentTarget is the subject of the event
var $form = $(event.currentTarget);
var url = $form.prop('action');
/*
* MANUAL
*/
// form fields are added to the form object as properties by name attribute
// note that they are not jQuery objects
var data = {
userId: $form.userId.value,
passKey: $form.passKey.value
};
/*
* AUTOMATIC
*/
// uses jQuery's form serialization to automatically create an object mapping names to values
var data = $form.serialize();
$.post(url, data)
// on success
.done(function (data, status, request) {
$.each(data.video, function (i, f) {
var link = "https://www.youtube.com/embed/"+ f.video;
// backslash at the end of a string means to continue the string on the next line
var $row = $('<tr>\
<td>' + f.videoName + '</td>\
<td>' + f.date + '</td>\
<td>' + f.time + '</td>\
<td>' + f.liveStatus + '</td>\
<td><a target="_blank" href="' + link + '">' + link + '</a></td>\
</tr>');
$row.appendTo('#userdata tbody');
})
// on failure
.fail(function (request, status, error) {
window.alert('Failed with a status of ' + status + ': ' + error);
})
// executes after either of the above
// parameters are inconsistent and use either done's or fail's
.always(function () {
// do cleanup, i.e. unlock form submission, close modal dialogs, etc.
login = false
});
// stop default form submission
event.stopPropagation();
event.preventDefault();
});
});

Pass ID of button to a form

I found this pass id to jquery modal form but seeing as I'm not too jQuery-savvy and I don't know PhP I'm not sure how I would implement this in my example.
My goal is to be able to pass the ID of a button, upon being pressed, to a form. Something like this:
<button id="dynamic_id">
<form id="time_form" action="{% url 'event' pk='button_id' %}" method="post">
# Lots of stuff
</form>
The button_id is where I'd like the button's ID to be.
I thought of something like
function getId(button_id) {
document.getElementById('time_form').action = "{" + "%" + "url " + "event" + ' pk="' + button_id + '" %" + "}"';
}
<button id="dynamic_id" onClick="getId(this.id);">
<form id="time_form" action=""> (...)
</form>
But this does not work. I get an error message
400 Bad Request: Your browser semt a request this server cannot understand
UPDATE
I'm not trying this:
function getId(button_id) {
var vk_input = document.CreateElement("input");
vk_input.name = "vk_id";
vk_input.value = button_id;
vk_input.type = "hidden";
document.getElementById("time_form").appendChild(vk_input);
}
But it does not work for some reason. What's wrong with it?
look this:
<script>
$(document).ready(function(){
$('#dynamic_id').click(function(){
var id=$(this).attr('id');
var array_ids = [];
$('.dinamics').each(function(){
//console.log('gdfg');
array_ids.push($(this).attr('id'));
});
for(var i = 0; i < array_ids.length; i++){
$('#time_form').append('<input type="hidden" name="your_button_id_'+i+'" value="'+array_ids[i]+'"/>')
}
$('#time_form').submit();
})
})
</script>
How aboout this with jquery.
<button id="dynamic_id">
<form id="time_form" action="" method="post">
</form>
<script>
$(document).ready(function(){
$('#dynamic_id').click(function(){
var id=$(this).attr('id');
$('#time_form').append('<input type="hidden" name="your_button_id" value="'+id+'"/>')
$('#time_form').submit();
})
})
</script>
Button id passed correctly to getId() but generated string does not seems valid, here is some issue with quotes. See reduced example on jsfiddle
try this:
document.getElementById('time_form').action = "{" + "%" + "url " + "event" + ' pk="' + button_id + '" ' + "%" + "}";
i recommend you to use jquery, is better an clean.
this is what you want?
<button id="dynamic_id" class="dinamics">Lots of stuff</button>
<button id="dynamic_id_1" class="dinamics">1</button>
<button id="dynamic_id_2" class="dinamics">2</button>
<button id="dynamic_id_3" class="dinamics">3</button>
<button id="dynamic_id_4" class="dinamics">3</button>
<button id="dynamic_id_5" class="dinamics">3</button>
<button id="dynamic_id_6" class="dinamics">3</button>
<button id="dynamic_id_7" class="dinamics">3</button>
<form id="time_form" action="" method="post">
</form>
<script>
$(document).ready(function(){
$('#dynamic_id').click(function(){
var array_ids = [];
$('.dinamics').each(function(){
array_ids.push($(this).attr('id'));
});
for(var i = 0; i < array_ids.length; i++){
$('#time_form').append('<input type="hidden" name="your_button_id_'+i+'" value="'+array_ids[i]+'"/>')
}
$('#time_form').submit();
})
})
</script>

Declare a JavaScript variable that will hold place for php variable

I have an app for making questionnaires. Users have index.php page where they create the questions and choose minimum number of answers, then they have process.php page where they can enter their answers or add more answers.
PROBLEM: When user clicks add more button, it creates textarea of the particular question but with the wrong name. The add more button should add a textarea and change its name according to the minimum of the defined textareas. So if you for ex. have 4 defined textareas in question2, the next textareas should be like odg25, odg26, odg27, odg28 etc...
The problem is in variable $k (process.php) - because it is not defined in addmore function, but I don't know how to pass somehow in this part of code to make it happen.
THIS IS THE TESTING LINK
INDEX.PHP
<input id="btntxt" type="submit" value="TEXT" onclick="addtxt();" /><br/><br/>
<form action="process.php" method="post">
Title: <br/><input type="text" name="naslov" size="64" required ><br/>
Maximum characters: <br/><input type="text" name="chars" size="64"><br/><br/>
<div id="brain1"></div><br/>
<input type="submit" name="submit" value="CONFIRM"><br/>
</form>
PROCESS.PHP
<script type="text/javascript">
<?php $chars = $_POST['chars']; ?>
function addmore(index) {
var textarea = document.createElement("textarea");
textarea.name = "odg" + index + //WHAT SHOULD I ADD HERE???;
textarea.rows = 3;
textarea.setAttribute('maxlength',<?php echo $chars ?>);
var div = document.createElement("div");
div.innerHTML = textarea.outerHTML;
document.getElementById("inner"+index).appendChild(div);
}
</script>
<body>
<?php
$bla = "";
$pitanje = $_POST['question'];
$length = count($_POST['question']);
$req = $_POST['req'];
$requiem = '';
$min = $_POST['min'];
$area = array("","","","","","","","","","","","","","","");
for($j=1; $j<$length+1; $j++) {
if($_POST['question'][$j] != "") {
if(($min[$j])!="") {
for($k=1;$k<=$min[$j];$k++) {
$area[$j] .= '<textarea name="odg'.$j.$k.'" rows="3"'.$requiem.' maxlength="'.$chars.'" ></textarea><br/>';}}
if(($min[$j])=="") {
$area[$j] = '<textarea name="odg'.$j.$k.'" rows="3"'.$requiem.' maxlength="'.$chars.'" ></textarea>';}
$addmore = '<input type="button" name="more" value="Add more" onClick="addmore('.$j.');">';
$bla .= $j.') '.$pitanje[$j].'<br/>'.$area[$j].'<div id="inner'.$j.'"></div>'.$addmore.'<br/>';}}
echo $bla;
?>
FNCS.JS
var n = 1;
function addtxt() {
var textarea = document.createElement("textarea");
textarea.name = "question[" + n + "]";
var required = document.createElement("input");
required.type = "checkbox";
required.name = "req[" + n + "]";
var minimum = document.createElement("input");
minimum.type = "text";
minimum.name = "min[" + n + "]";
var div = document.createElement("div");
div.innerHTML = n + ". Question: " + "<br />" + textarea.outerHTML + "<br />" + "Required: " + required.outerHTML + "<br />" + "Min: " + minimum.outerHTML + "<br /><hr/><br/>";
document.getElementById("brain1").appendChild(div);
n++;
}
I did the same kind of dev.
I had a globalized counter (cpt) in the javascript is incremented by 1 each duplication
My variables were duplicated like this id = "foo_" + cpt.
I added a hidden field for the counter <input type="hidden" id = "cpt"> and its value was changed for each replication.
Php side, I recovered the counter and then a loop to iterate through all the duplicate fields.
// For example
$cpt = $_POST['cpt'];
for ($i = 1; $i <= $cpt; $i++) {
$foo[$i] = $_POST['foo_' . $i];
}
I hope it will help.
You're mixing JavaScript and PHP. PHP is doing some part of the question generation and then JavaScript has to pick up where it left off.
The problem with that approach is that you'll find you end up duplicating a lot of functionality.
The answer the quesiton WHAT SHOULD I ADD HERE??? is "odg" + $j + $k
If instead you start by doing:
var questions = <?php echo json_encode($_POST["question"]);?>;
You now have all your question data available in JavaScript. You can move the for loop from PHP to JavaScript and have j and k there.
What you're going to have to do is make $k able to be passed into process.php.
That is accomplished with something like this:
<form action="process.php" method="post">
Title: <br/><input type="text" name="naslov" size="64" required ><br/>
Maximum characters: <br/><input type="text" name="chars" size="64"><br/><br/>
<div id="brain1"></div><br/>
<input id="numRows" type="hidden" name="numRows" value="1"/>
<input type="submit" name="submit" value="CONFIRM"><br/>
</form>
notice I've added a new <input> element with the name "numRows" which will be passed via POST to process.php. I've given it an arbitrary default value of 1, you can set this however you wish.
Now, when a user clicks the "add more" button, within fncs.js do this:
document.getElementById("numRows").value++;
and finally, in your process.php you need to read in the value of this, as $k:
<?php $k = isset($_POST['numRows']) ? urldecode($_POST['numRows']) : 1; ?>
within process.php you may do as you wish, then, with that value $k.
You need to store last text area value in hidden variable and always increment that
first step: At start set value of hidden variable and your counter
'n' same
second step : at each step where you are adding new text area ,
overwrite the hidden value by new counter value of text area
Remember Textarea counter should be always fetched from hidden value
I think this may help you to solve your problem

jquery each loop write data for each div

I hope this makes sense. I have an onclick and I am trying to write this data for each div with this.
jQuery('.circle_counter_div').each(function() {
var tagtext = '[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]';
})
I am cloning items but I can only write the data for one of them. How do I write data for each cloned item?
So with the above example I want tagtext to equal
[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]
[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]
[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]
Full Code
HTML
<div class="sc_options circle_counter_div" id="clone_this" style="display: block;">
<input type="text" class="circle_size"/>
</div>
<div class="sc_options circle_counter_div" id="clone_this" style="display: block;">
<input type="text" class="circle_size"/>
</div>
<div class="sc_options circle_counter_div" id="clone_this" style="display: block;">
<input type="text" class="circle_size"/>
</div>
<input type="submit" class="sc_options circle_counter_div" id="insert" name="insert" value="<?php _e("Insert", 'themedelta'); ?>" onClick="insertcirclecountershortcode();" style="display:none"/>
Script
// Insert the column shortcode
function insertcirclecountershortcode() {
var tagtext;
var start;
var last;
var start = '[circlecounters]';
var last = '[/circlecounters]';
jQuery('.circle_counter_div').each(function() {
var tagtext = '[circlecounter rel="' + jQuery('.circle_size').val() + '"][/circlecounter]';
})
var finish = start + tagtext + last;
if (window.tinyMCE) {
window.tinyMCE.execInstanceCommand(window.tinyMCE.activeEditor.id, 'mceInsertContent', false, finish);
//Peforms a clean up of the current editor HTML.t
//tinyMCEPopup.editor.execCommand('mceCleanup');
//Repaints the editor. Sometimes the browser has graphic glitches.
tinyMCEPopup.editor.execCommand('mceRepaint');
tinyMCEPopup.close();
}
return;
}
Extended Answer: After some more information was provided perhaps you're just missing the index and value properties on the loop. Its hard to tell, since little sample code is provided.
$('.test').each(function(i,v) {
var tagtext = $(v).html();
console.log(tagtext);
})
http://jsfiddle.net/4xKvh/
Original Answer:
Use use classes instead of an Id. Id's are only suposed to be used once on a page.
Since there should only be one occurance jQuery is filtering the result down to 1, even though the markup may have multiple elements with that Id on the page. This is to make use of the built-in browser function getElementById().
For proof checkout this jsFiddle
Using the class attribute is more appropriate for what you're trying to do.
jQuery('.clone_this').each(function() {
var tagtext = '[something][/something]';
})
And the markup:
<div class="clone_this"></div>
This will allow jQuery to return an array of elements like you're looking for
This is what I needed... Finally got it working.
tagtext = ' ';
jQuery('#circle_counter_div .circlecounter').each(function() {
tagtext += '[circlecounter rel="' + jQuery('.circle_size').val() + '" datathickness="' + jQuery('.circle_thickness').val() + '" datafgcolor="' + jQuery('.circle_color').val() + '" text="' + jQuery('.circle_text').val() + '" fontawesome="' + jQuery('.font_awesome_icon').val() + '" fontsize="' + jQuery('.circle_font_size').val() + '"][/circlecounter]';
});
var start = '[circlecounters]';
var last = '[/circlecounters]';
var finish = start + tagtext + last;

Categories

Resources