How to send a javascript array to php [duplicate] - javascript

This question already has answers here:
How to pass data from Javascript to PHP and vice versa? [duplicate]
(7 answers)
Closed 4 years ago.
I have an array named "seat" in my javascript file.It is used to store the seat numbers when a user clicks on a seat in a theater layout.In my function,I've used a window alert to show the user his selected seats,and when he clicks OK button,I want to send these booked seats(values in my array) to a php file named "confirm".
Here is the javascript function.
var init = function (reservedSeat) {
var seat = [], seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 0; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
seat.push('<li class="' + className + '"' +
'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' +
'<a title="' + seatNo + '">' + seatNo + '</a>' +
'</li>');
}
}
$('#place').html(seat.join(''));
};
$('.' + settings.seatCss).click(function () {
if ($(this).hasClass(settings.selectedSeatCss)){
alert('This seat is already reserved!');
}
else{
$(this).toggleClass(settings.selectingSeatCss);
}
});
$('#btnsubmit').click(function() {
var seat = [], item;
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
item = $(this).attr('title');
seat.push(item);
});
window.alert(seat);
$_POST('confirm.php', {seat: seat})
})
<form method="POST" action="confirm.php">
<div align="center"><input type="Submit" id="btnsubmit" value="Submit" /></div>
</form>
And this is my php code.
$seat = "";
if(isset($_POST['seat']))
{
$seat = $_POST["seat"];
print_r($seat);
}
When this is executed I get the window alert,but the values stored in the array does not pass to the php file.Is there something wrong with this code?Please help!I'm stuck here!!!

$_POST isn't a built-in method, and jQuery doesn't provide a method like that either-- you can't just "set" the values into the $_POST array like this.
To post using jQuery, you would do something like the following, including a handler for data returning from the server (if you have any):
$.post("confirm.php", { seat: seat})
.done(function(data){
alert('Received data from server: ' + data);
});

You need to send the data to your PHP script, this does nothing in your JS code:
$_POST('confirm.php', {seat: seat})
use something like jQuery post method or vanilla JS XMLHttpRequest

Related

Razor JQuery Populate Drop Down from Model array

I am using a WebGrid to allow CRUD on my database (using MVC and EF entities). The grid works and filters they way I want it to. There are two columns that use dropdowns to display a value tied to another table (Projects and People) and these both work well for edits/ updates. I am using JQuery for an add new row and want the new row to have select fields like the grid does (so that the user can just find the person by name instead of having to enter the ID for example). I am referencing this post from another similar question, but when I implement the code I get a syntax error that I'm having trouble understanding.
Here is my scripting on the view side that shows my failed attempt. I'm creating an array from the project repository (Text is the name of the project and Value is the ID field), and populating it with the model values: Model.Projects, and then in the add row function I want to loop through the array to add in the options.
<script type="text/javascript">
var ProjectArray = new Array();
#foreach (var proj in Model.projects)
{
#:ProjectArray.push(Text: "#proj.Text", Value: "#proj.Value");
}
</script>
<script type="text/javascript">
$(function ()
{
$('body').on("click", ".add", function () {
var SelectedProject = "#Model.ProjectID";
var newRow = $('.save').length;
console.log('newRow = ' + newRow);
if (newRow == 0) {
var index = "new"+$("#meetingList tbody tr").length + 1;
var ProjectID = "ProjectID_" + index;
var Date = "Date_" + index;
var Attendees = "Attendees_" + index;
var Phase = "Phase_" + index;
var PeopleID = "PeopleID_" + index;
var Save = "Save _" + index;
var Cancel = "Cancel_" + index;
var tr = '<tr class="alternate-row"><td><span> <input id="' + ProjectID + '" type="select"/></span></td>' +
#* This is where I use the array to add the options to the select box*#
ProjectArray.forEach(function (item) {
if (item.Value == SelectedProject) { '<option selected="selected" value="' + item.Value + '">' + item.Text + '</option>' }
else { '<option value="' + item.Value + '">' + item.Text + '</option>' }
+
});
---remaining script omitted----
'<td><span> <input id="' + PeopleID + '" type="text" /></span></td>' +
'<td><span> <input id="' + Date + '" type="date" /></span></td>' +
'<td><span> <input id="' + Attendees + '" type="text" /></span></td>' +
'<td><span> <input id="' + Phase + '" type="text" /></span></td>' +
'<td> SaveCancel</td>' +
'</tr>';
console.log(tr);
$("#meetingList tbody").append(tr);
}
});
I am not sure how to parse the error, but the page source looks like this when creating my client side array:
var ProjectArray = new Array();
ProjectArray.push(Text: "Select Project", Value: ""); //<-- ERROR HERE:
ProjectArray.push(Text: "010111.00", Value: "74");
ProjectArray.push(Text: "013138.00", Value: "2");
So the model getting into the client side works (the text and value pairs are correct), but the error I get is for the first array.push line: missing ) after the argument list. I have played with moving this code block around, putting it in a separate <script> tag and the error likewise follows it around, always on the first array.push line. And regardless of where it is, the rest of my script functions no longer work. I think it must be something silly but I just am not seeing what I'm doing wrong.
The option list does not populate into something I can ever see, it just renders out on the page source as the javascript loop:
var tr = '<tr class="alternate-row"><td><span> <input id="' + ProjectID + '" type="select"/></span></td>' +
ProjectArray.forEach(function (item) {
if (item.Value == SelectedProject) { '<option selected="selected" value="' + item.Value + '">' + item.Text + '</option>' }
else { '<option value="' + item.Value + '">' + item.Text + '</option>' }
+
}); //-- Unexpected token here
And with the push array in its separate script block I get a second error that the last } is an unexpected token. This is some javascripting error I'm sure. But where it is an how to do this are beyond me right now.
I'm not used to javascript, and poor syntax leads to the vague errors I was getting. The first problem was fixed by adding the { . . . } around the array values. Then I created a function to create the arrays I need for people and projects as well as a function to take an array and create the option list to clean up the view code:
function createProjectArray() {
var ProjectArray = new Array();
#foreach (var proj in Model.projects)
{
if (proj.Value != "") {
#:ProjectArray.push({ Text: "#proj.Text", Value: "#proj.Value" });
}
}
return ProjectArray;
}
function createPeopleArray() {
var PeopleArray = new Array();
#foreach (var person in Model.people)
{
if (person.Value != "") {
#:PeopleArray.push({ Text: "#person.Text", Value: "#person.Value" });
}
}
return PeopleArray;
}
function SelectOptionsString(MyArray, SelectedValue) {
console.log(MyArray);
var OptionsList = "";
MyArray.forEach(item => {
if (item.Value == SelectedValue) { OptionsList += '<option
selected="selected" value="' + item.Value + '">' + item.Text + '</option>'; }
else { OptionsList += '<option value="' + item.Value + '">' + item.Text
+ '</option>'; }
})
return OptionsList;
}
Taking this approach allowed me to more easily parse the code and find the syntax errors. The Array.forEach syntax was an interesting hurdle, and this site helped me test out my syntax to eventually get it working as above.
So the server creates the javascript lines to create the array, and then I use the array to create my dropdown options list. This cleans up the add row function code nicely:
$('body').on("click",".addrow", function() {
var SelectedProject = "#Model.ProjectID";
var ProjectArray = createProjectArray();
var ProjectOptions = "";
ProjectOptions = SelectOptionsString(ProjectArray, SelectedProject);
var PeopleArray = createPeopleArray();
var PeopleOptions = "";
PeopleOptions = SelectOptionsString(PeopleArray, "");
var tr = '<tr class="alternate-row"><td><span> <select id="' +
ProjectID + '>' + ProjectOptions + '</select></span></td>' +
'<td><span> <select id="' + PeopleID + '>' + PeopleOptions +
'</select></span></td>' + '</tr>'
$("#myWebGrid tbody").append(tr);
});
And it also allows for some potential code reuse.

Add new line using jQuery concat

Through ajax response I'm passing array data from controller to blade.
On Ajax success I'm looping through array with 2 elements and concatenating string to display later on in my bootstrap popover.
success: function (data) {
var content = "";
var num = 1;
for (var i = 0; i < data.length; i++) {
content = content.concat(num + "." + " " + data[i]);
num++;
}
$("#content").popover({content: content});
}
Result:
I would like to add new line, so that each item or "artikel" would be displayed in new line e.g. :
1.Artikel...
2.Artikel...
I tried to add "\n" (as below) or html break but nothing works, it only appends as string.
content = content.concat(num + "." + " " + data[i] + "\n");
Use this:
content.concat(num + "." + " " + data[i] + "<br/>");
And this:
$("#content").popover({ html:true, content: content });

Uncaught syntaxerror: Unexpected Identifier (Javascript, asp.net mvc, cshtml)

So the error I am receiving is when I click the remove button on the dynamically created html, which is meant to call the remove method at the bottom and pass the arguments. The passing of the object as an argument is where I am running into the problems..
function addMarkerToList(args) {
var object = args;
var camera = args.id;
var test = selectedCameras.indexOf(args.id);
var noOfCamerasAllowed = #Model.usersName.CamerasSelectable;
if (selectedCameras.length < noOfCamerasAllowed) {
if (test > -1) {
alert("Camera already in list");
} else
{
selectedCameras.push(args.id);
var outputString = "";
for (i = 0; i<selectedCameras.length; i++) {
outputString += selectedCameras[i] + ",";
}
//$("#cameraSelectedList").append("<p id=" + args.id + ">" + args.id + "</p>");
$("#cameraSelectedList").append(
"<div id = " + camera + " class=\"col-md-12\">" +
"<div class=\"col-lg-3 col-md-4 col-sm-6 col-xs-12 user-item\">" +
"<div class=\"user-container\">" +
"<a class=\"user-avatar\"><i class=\"glyphicon glyphicon-facetime-video\" style=\"color: #ed1c24; font-size: 36px;\"></i></a>" +
"<p class=\"user-name\">" +
"<span>Camera</span>" +
This is where I think the issue is being caused:
"<input type=\"button\" value=\"Remove\" onclick=\"removeMarkerFromList(" + object + ")\"/>" +
"</p>" +
"</div>" +
"</div>");
The directly above section is where the error is being caused, I think by how I am passing the args called (object) in the input button back the the remove method below..
if (check === 0) {
$("#cameraModelPassThrough").append("<input id=" +
camera + ".2" + " class=\"form- control text- box single- line valid hidden\" name=\"selectedCameraList\" placeholder=\"Selected Camera ID\" type=\"text\" value=\"" +
outputString +
"\" aria-required=\"true\" aria-describedby=\"footageRequest_Incident_Location- error\" aria-invalid=\"false\">");
check = 1;
lastAddedId = (camera + ".2");
} else {
//alert("This is the last added id: " + lastAddedId);
document.getElementById(lastAddedId).remove();
$("#cameraModelPassThrough").append("<input id=" +
camera + ".2" + " class=\"form- control text- box single- line valid hidden\" name=\"selectedCameraList\" placeholder=\"Selected Camera ID\" type=\"text\" value=\"" +
outputString +
"\" aria-required=\"true\" aria-describedby=\"footageRequest_Incident_Location- error\" aria-invalid=\"false\">");
check = 0;
lastAddedId = (camera + ".2");
}
}
} else {
alert("You have added the maximum number of cameras");
}
}
//Removing objects by right clicking the marker
function removeMarkerFromList(args) {
var camera = args.id;
alert(camera);
var test = selectedCameras.indexOf(camera);
if (test > -1) {
document.getElementById(camera).remove();
selectedCameras.splice(test, 1);
alert("Camera removed from list");
} else {
alert("Camera not in list");
}
var outputString = "";
for (i = 0; i<selectedCameras.length; i++) {
outputString += selectedCameras[i] + ",";
}
document.getElementById(lastAddedId).remove();
$("#cameraModelPassThrough").append("<input id=" +
camera + ".2" + " class=\"form- control text- box single- line valid hidden\" name=\"selectedCameraList\" placeholder=\"Selected Camera ID\" type=\"text\" value=\"" +
outputString +
"\" aria-required=\"true\" aria-describedby=\"footageRequest_Incident_Location- error\" aria-invalid=\"false\">");
check = 1;
lastAddedId = (camera + ".2");
}
You're concatenating your object into a string, which probably gives you something like
onclick="removeMarkerFromList([Object object])"
You can use an id (string or number) instead and retrieve your object afterwards:
"onclick=\"removeMarkerFromList(" + object.id + ")\"/>"
You can also stringify your object:
"onclick=\"removeMarkerFromList(" + JSON.stringify(object) + ")\"/>"
I managed to solve the issue by using object manipulation before passing the object to my method.
Thank you everyone for your assistance!
In ASP.NET/MVC/.NET Core project if you are facing this issue, sometimes this might be due to cache storage refresh not happening. In my instance, I had a Redis server running and it needed a manual restart. Go to Task Manager-> Services tab and see the server you are running and restart it manually( Redis server: Memurai in case if you are using windows).

How to toggleClass with SignalR hub.server?

I am currently learning SignalR with .Net MVC and following a tutorial to work on a simple app. Right now it is working alright, but I am having trouble understanding some part and also if possible, want to sort of enhance it.
Plane Seats Tutorial link
Right now the app is working as when a user clicks on a seat, it reserves it. And there is no going back. I want to implement like a toggle, where if the user wants to change seat, he gets to unreserve his selected seat, and then be free to reserve another one. I am not being able to do it with myHub.server.selectSeat(userId, $(this).toggleClass(settings.selectingSeatCss));. Whenever I click on a seat, it gives me this error in the Dev tools
Uncaught: Converting circular structure to JSON
var settings = {
rows: 5,
cols: 15,
rowCssPrefix: 'row-',
colCssPrefix: 'col-',
seatWidth: 35,
seatHeight: 35,
seatCss: 'seat',
selectedSeatCss: 'selectedSeat',
selectingSeatCss: 'selectingSeat'
};
$(function() {
//// Start the hub
window.hubReady = $.connection.hub.start();
});
$.connection.hub.start().done(function() {
// Call the server side function AFTER the connection has been started
myHub.server.createUser();
//invoke for the user data
myHub.server.populateSeatData();
});
// Seat selection
$('.' + settings.seatCss).click(function() {
if ($(this).hasClass(settings.selectedSeatCss)) {
alert('Sorry, this seat has been already reserved');
} else {
//$(this).toggleClass(settings.selectingSeatCss);
//myHub.server.selectSeat(userId, $(this).toggleClass(settings.selectingSeatCss));
myHub.server.selectSeat(userId, $(this)[0].innerText);
}
});
// Client method to broadcast the message
myHub.client.createUser = function(message) {
userId = message;
};
//get seats data
myHub.client.populateSeatData = function(message) {
var parsedSeatsData = JSON.parse(message);
$('li.seat').removeClass(settings.selectedSeatCss);
$.each(parsedSeatsData, function(index, value) {
$("a:contains('" + value.seatnumber + "')").parent("li").toggleClass(settings.selectedSeatCss);
});
};
// Client method to broadcast the message as user selected the seat
myHub.client.selectSeat = function(message) {
var parsedSeatData = JSON.parse(message);
$("a:contains('" + parsedSeatData.seatnumber + "')").parent("li").toggleClass(settings.selectedSeatCss);
};
And can anyone please briefly explain what is str.push doing in this block of code? What is it exactly pushing into the array?
var init = function(reservedSeat) {
var str = [],
seatNo, className;
for (i = 0; i < settings.rows; i++) {
for (j = 2; j < settings.cols; j++) {
seatNo = (i + j * settings.rows + 1);
className = settings.seatCss + ' ' + settings.rowCssPrefix + i.toString() + ' ' + settings.colCssPrefix + j.toString();
if ($.isArray(reservedSeat) && $.inArray(seatNo, reservedSeat) != -1) {
className += ' ' + settings.selectedSeatCss;
}
str.push('<li class="' + className + '"' + 'style="top:' + (i * settings.seatHeight).toString() + 'px;left:' + (j * settings.seatWidth).toString() + 'px">' + '<a title="' + seatNo + '">' + seatNo + '</a>' + '</li>');
}
}
$('#place').html(str.join(''));
};
I had to use a toggleSeat() function instead of just using toggleClass.
public void toggleSeat(int userId, int seatNumber)
{
PlaneSeatArrangment mySeat = allSeats.Where(s => s.SeatNumber == seatNumber).FirstOrDefault();
var retunData = JsonConvert.SerializeObject(mySeat);
if (mySeat != null && userId == mySeat.UserId)
..............
}

Adding a table from database with javascript

I am seeking help trying to add a new table in my third function called ingredients. I am not very familiar with javascript so I tried to duplicate code from newDosage which is similar to what I need to do. Unfortunately, right now all I see is 0, 1, or 2 and not the actual text from the ingredient table. If anyone can help me correctly call the table, it would be greatly appreciated. Thank you.
Below is my code. The first function pulls the database, the second function uses the results and the third function is where I have tried to add the ingredient table.
function listTreatmentDb(tx) {
var category = getUrlVars().category;
var mainsymptom = getUrlVars().mainsymptom;
var addsymptom = getUrlVars().addsymptom;
tx.executeSql('SELECT * FROM `Main Database` WHERE Category="' + category +
'" AND Main_Symptom="' + mainsymptom + '" AND Add_Symptom="' + addsymptom + '"',[],txSuccessListTreatment);
}
function txSuccessListTreatment(tx,results) {
var tubeDest = "#products";
var len = results.rows.length;
var treat;
for (var i=0; i < len; i = i + 1) {
treat = results.rows.item(i);
$("#warning").append("<li class='treatment'>" + treat.Tips + "</li>");
$("#warning-text").text(treat.Tips);
$('#warning').listview('refresh');
//console.log("Specialty Product #1: " + treat.Specialty1);
if(treat.Specialty1){
$("#products").append(formatProductDisplay('specialty1', treat.Specialty1, treat.PurposeSpecialty1, treat.DosageSpecialty1, '1'));
}
if(treat.Specialty2){
$("#products").append(formatProductDisplay('specialty2', treat.Specialty2, treat.PurposeSpecialty2, treat.DosageSpecialty2, '0'));
}
}
}
function formatProductDisplay(type, productName, productPurpose, productDosage, Ingredients, aster){
var newDosage = productDosage.replace(/"\n"/g, "");
if(aster=='1'){ productHTML += "*" }
productHTML+= "</div>" +
"</div>" +
"<div class='productdose'><div class='label'>dosage:</div>" + newDosage + "</div>" +
"<div class='productdose'><div class='label'>ingredients:</div>" + Ingredients +
"</div></li>"
return productHTML;
}
You are missing an argument when you call formatProductDisplay(). You forgot to pass in treat.Ingredient.
Change:
$("#products").append(formatProductDisplay('specialty1', treat.Specialty1, treat.PurposeSpecialty1, treat.DosageSpecialty1, '1'));
To:
$("#products").append(formatProductDisplay('specialty1', treat.Specialty1, treat.PurposeSpecialty1, treat.DosageSpecialty1, treat.Ingredients, '1'));
Also do the same thing to the similar 'Specialty2' line right below it.

Categories

Resources