I am having issues figuring out how to submit a form via ajax that has items with the same name(this form is dynamically created and has to use the same names for some fields).
This is the JS code that I have
<script>
var toggle123 = function() {
var chair = document.getElementsByName('chair[]');
var item1 = document.getElementsByName('item[]');
var price = document.getElementsByName('price[]');
var table = document.getElementById('table');
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'table='+table+'';
for(i=0;i<item1.length;i++)
{
dataString += + '& item1[]' + '=' + item1[i];
}
for(i=0;i<chair.length;i++)
{
dataString += + '& chair[]' + '=' + chair[i];
}
for(i=0;i<price.length;i++)
{
dataString += + '& price[]' + '=' + price[i];
}
if (chair == '' || item1 == '') {
}
else {
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "submit.php",
data: dataString,
cache: false,
success: function(html) {
alert(html);
}
});
}
return false;
var mydiv = document.getElementById('table1');
if (mydiv.style.display === 'block' || mydiv.style.display === '')
mydiv.style.display = 'none';
else
mydiv.style.display = 'block'
}
</script>
I want it to submit to submit.php and also to hide the div that is open (table1).
I can get it to go to submit.php but I am not sure if the data is actually getting sent there or if it is just blank. It tells me there was an invalid argument for the foreach loop in submit.php.
Here is submit.php
<?php
include('dbconfig.php');
// Fetching Values From the post method
$table = $_POST['table_id'];
foreach($_POST["item1"] AS $key => $val) {
$chair = $val;
$price = $_POST['price'][$key];
$chair = $_POST['chair'][$key];
$query = mysqli_query($dbconfig,"insert into orders(table_id, price, item, chair) values ('$table', '$price', '$item', '$chair')"); //Insert Query
echo "Form Submitted succesfully";
}
?>
This is the javascript for the dynamic form....each time a button is clicked, this adds onto the form:
listholder.innerHTML += "Chair "+row.chair+"-<input type='hidden' id='chair' name='chair[]' value='"+row.chair+"' /><input type='hidden' id='table' name='table' value='"+row.table_id+"' /><input type='hidden' id='item' name='item[]' value='"+row.item1+"' /><input type='hidden' id='price' name='price[]' value='"+row.item1+"' />" + row.item1 + " - " + row.chair + " (<a href='javascript:void(0);' onclick='deleteCar(" + row.id + ");'>Delete Car</a>)<br>";
I think my main issue is probably forming the datastring that gets passed to submit.php. If anyone could help me figure this out, that would be great!
(P.S. toggle123 is activated via a button click (that works fine)
Related
I loop through some data dynamically via Ajax and than display them in table. As you see I have multiple row or <tr> , HeaderLine and Customerinfo. which I'm interesting in is CustomerInfo and the thing I'm trying do is when button is clicked, check which input fields is Empty or has no value than give an alert and for finding input fields or elements I used jQuery find() and closest() Method, but for some reason it can't find any elements.
Can anyone please help me to solve the issue?
JavaScript for checking Empty input fields before sending to server:
<script>
function AnmodomRMA(e) {
var tr = $(e).closest("table").find(".CustomerInfo");
var email = tr.find('input.Email').val();
var telefon = tr.find('input.Telefonnummer').val();
if (email === "") {
alert("Input is Empty:" + email);
return false;
}
if (telefon === "") {
alert("Input is Empty:" + telefon);
return false;
}
var formdata = $("select, textarea,input").serializeArray();
$.ajax({
"url": '#Url.Action("AutoRMAAnmoding", "User")',
"method": "POST",
"data": formdata,
"dataType": "json",
success: function (data) {
console.log(data);
},
error: function () {
console.log('something went wrong - debug it!');
}
});
}
</script>
JavaScript for Load Data (dynamically into table):
<div class="card-body">
<table class="table">
<tbody id="ResultProduct"></tbody>
</table>
<div id="AppendBtnRMA">
</div>
</div>
<script>
$.ajax({
type: "GET",
url: "/User/serializeItemLineByID" + 1,
dataType: 'json',
success: function (result) {
$.each(result.findclosedorders, function (ii, e) {
var guid = uuidv4();
rows += '<tr class="HeaderLine">';
rows += '<td>some data</td>';
rows += '</tr>';
rows += '<tr class="CustomerInfo">'
rows += '<input type="hidden" name="model.InsertRMALists.Index" value="' + guid + '" />';
rows += '<td><label>Telefonnummer</label><input name="model.InsertRMALists[' + guid + '].Telefonnummer" id="Telefonnummer" type="tel"></td>';
rows += '<td><label>E-mail</label><input name="model.InsertRMALists[' + guid + '].Email" id="Email" type="text"></td>';
rows += '</tr>';
});
var btnAppend = "";
btnAppend += '<button onclick="AnmodomRMA(this);">Create RMA</button>';
$("#AppendBtnRMA").append(btnAppend);
$("#ResultProduct").append(rows);
},
})
</script>
Thanks for all help :)
Here is how did i solve the problems:
- Add a class to input fields.
- beacuse button it was out side the table, i have to select closest element around table and than find <tr> like:
var tr = $(e).closest(".card-body").find("tr.section");
and than loop through that element i want to check if it is Empty:
$(tr).each(function (i, el) {
var t = $(el).find('input.Telefonnummer').val();
if (t ==="") {
alert("empty");
}
});
In the function AnmodomRMA(e) e refers to the event itself and not the clicked button, try to use e.target:
var tr = $(e.target).closest("tr");
So hear me out, I want to do a live search of employees in a database and have them show up in a page of my website. I want their employee data to appear on the screen along with some radio buttons to edit their information. Here are the components of the task I have so far:
Javascript: index.php
`
//Search bar functionality
$(document).ready(function() {
load_data();
function load_data(query) {
$.ajax({
url:"fetchUsers.php",
method:"POST",
data:{query:query},
dataType: 'json',
success:function(data) {
console.log(data);
function ajaxCall2(data){
$.ajax({
url:"showEmployees.php",
method:"POST",
data2:{data:data}
})
}
}
});
}
$('#search_text').keyup(function() {
var search = $(this).val();
if(search != '') {
load_data(search);
} else {
load_data();
}
});
});
</script>`
So the above code is doing the live search, the results are being stored in data. That works.
fetch.php
$db = new PDO('mysql:host=localhost;dbname=user_information;charset=utf8', 'root', 'root');
if(isset($_POST["query"]))
{
$users= $db->prepare("
SELECT * FROM login_information
WHERE user_name LIKE '%".$search."%'
");
$users->execute();
$users = $users->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($users);
}
else
{
return;
}
This is the PHP code that runs in the ajax call for the live search. NOW for each element in my array,$users, I want this code to be run and displayed in index.php:
echo "
<div class=employeeContainter>
<div class=employeeInformation>
<ul>
<li>User Name: " . $row['user_name'] . "</li>
<li>User ID: " . $row['user_id'] . "</li>
<li>User Email: " . $row['user_email'] . "</li>
<form action='editEmployee.php' method='POST'>
<label for='NotEmployed'>Not Employee</label>
<input type='radio' id='NotEmployed' name='Employee'";
if($row['isEmployee']==0) echo "checked='checked'/>";
else echo "/>";
echo "<br><label for='YesEmployed'>Employee</label>
<input type='radio' id='YesEmployed' name='Employee'";
if($row['isEmployee']==1) echo "checked='checked'/>";
else echo "/>";
echo "<br><input type='submit' name=updateButton value='Update User'/>
</form>
</ul>
</div>
</div>
";
https://gyazo.com/16899aa7a6426310e42ee9090eef3158
This is a picture of how I want things to work. I know how each part works individually but I cannot figure out how to get everything to work together. I know this is a long post but any help at all would be appreciated
EDIT:
So I've been recreating the PHP code in javascript here is where I'm at
function generateEmployeeData(employees){
employees.forEach(function(d){
var containerDiv = document.createElement('div');
var informationDiv = document.createElement('div')
var ul = document.createElement('ul');
var br = document.createElement('br');
var br2 = document.createElement('br');
//form
var form = document.createElement('form');
form.setAttribute("action","editEmployee.php");
form.setAttribute("method","POST");
//labels
var yesLabel = document.createElement('label');
var noLabel = document.createElement('label');
yesLabel.setAttribute("for","YesEmployed");
noLabel.setAttribute("for","NotEmployed");
//Radio buttons
//buttons need to have the same name so only one is selected
var yesButton = document.createElement('input');
var noButton = document.createElement('input');
yesButton.setAttribute("type","radio");
yesButton.setAttribute("name","Employee");
yesButton.setAttribute("id","YesEmployed");
noButton.setAttribute("type","radio");
noButton.setAttribute("name","Employee");
noButton.setAttribute("id","NotEmployed");
if(d.isEmployee == 1){
yesButton.setAttribute("checked","checked");
}
else{
noButton.setAttribute("checked","checked");
}
//submit button
var submit = document.createElement('input');
submit.setAttribute("type","submit");
submit.setAttribute("name","updateButton");
submit.setAttribute("name","updateButton");
submit.setAttribute("value","Update User");
containerDiv.setAttribute("id","employeeContainer");
// containerDiv.setAttribute("class","employeeContainer");
informationDiv.setAttribute("id","employeeInformation");
// informationDiv.setAttribute("class","employeeInformation");
document.getElementById('results').appendChild(containerDiv)
document.getElementById('employeeContainer').appendChild(informationDiv)
document.getElementById('employeeInformation').appendChild(ul)
var li = document.createElement('li');
li.innerHTML = "User Name: "
var li2 = document.createElement('li');
li2.innerHTML = "User ID: ";
var li3 = document.createElement('li');
li.innerHTML = "User Email: "
//generating the header for item card
var employeeHeaderDiv = document.createElement("div");
employeeHeaderDiv.setAttribute("class", "employeeHeader");
//generating the name div for the header
var employeeNameDiv = document.createElement("div");
employeeNameDiv.setAttribute("class", "employeeName");
var employeeNameTextNode = document.createTextNode(d.user_name);
var employeeEmail = document.createTextNode(d.user_email);
//prevent issues with display if the name for an item is too long
// if(employeeNameTextNode.length > 15){
// employeeNameTextNode = document.createTextNode(d.employeeName.slice(0,13) + "...");
// }
// employeeNameDiv.appendChild(employeeNameTextNode);
ul.appendChild(li);
ul.appendChild(li2);
ul.appendChild(li3);
li.innerHTML = li.innerHTML+ d.user_name;
li2.innerHTML = li2.innerHTML+ d.user_id;
li3.innerHTML = li3.innerHTML+ d.user_email;
ul.appendChild(form);
form.appendChild(noLabel);
noLabel.innerHTML = "Not Employee";
form.appendChild(noButton);
form.appendChild(br);
form.appendChild(yesLabel);
yesLabel.innerHTML = "Employee";
form.appendChild(yesButton);
form.appendChild(br2)
form.appendChild(submit);
});
}
This is what it looks like so far: https://gyazo.com/c5cb9cd6cae92ccba502a9d0efe82076
So I've made some progress, this function is being called in the success function of my ajax call so essentially on every keyup in the search bar. However, I have a few problems.
I can select both radio buttons but I need to be able to only select one at a time. Solved by giving each radio button the same name
If I continue typing new results are just appended below what I already have instead of updating what I have.
Any ideas?
Alright so I was able to solve my own problem but since someone may run into a similar problem as me one day I'll post my solution. The code in the edit is all set but as for updating the entries I just made another function called removeEmployeeData and placed it into my ajax function before I call generateEmployeeData:
function removeEmployeeData(){
$("div#employeeContainer").remove();
}
So my ajax function now looks like:
$.ajax({
url:"fetchUsers.php",
method:"POST",
data:{query:query},
dataType: 'json',
success:function(data) {
removeEmployeeData();
generateEmployeeData(data);
console.log(data);
}
});
Combine this with the above code and you now have a live search feature like this: https://gyazo.com/5efa11e50845afe8964c5dae6a9597e2
I'm trying to submit a form using Ajax , but it doesn't work here is my Ajax :
$(document).ready(function(){
$("#submit").click(function(event){
var ad1 = $("#ad1").val();
var ad2 = $("ad2").val();
var city = $("city").val();
var state = $("state").val();
var zip = $("zip").val();
var country = $("country").val();
var mm = $("mm").val();
var dd = $("dd").val();
var yy = $("yy").val();
var lname = $("lname").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'name1='+ name + '&ad11='+ ad1 + '&ad21='+ ad2 + '&city1='+ city + '&state1='+ state + '&zip1='+ zip + '&country1='+ country + '&mm1='+ mm + '&yy1='+ yy + '&dd1='+ dd + '&lname1=';
if(name=='')
{
alert("");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
and it's not giving any result just giving data in header
the result is like :
I copied the javascript to the form page it's now working ,but the ajax is returning a blank alert while it should be "Form Submitted Succesfully"
I guess that it's an error of inclusion of the file , but i'm using the right directories.
here is action.php :
<?php
$con = mysqli_connect("server","user","pass","db");
$name=$_POST['name1'];
$ad1=$_POST['ad11'];
$ad2=$_POST['ad21'];
$city=$_POST['city1'];
$state=$_POST['state1'];
$zip=$_POST['zip1'];
$country=$_POST['country1'];
$mm=$_POST['mm1'];
$dd=$_POST['dd1'];
$yy=$_POST['yy1'];
$dob=$dd."/".$mm."/".$yy;
$mm=$_POST['mm1'];
$name=$_POST['name1'];
$lname=$_POST['lname1'];
$r2=rand(10000,90000);
$query = mysqli_query($con,"insert into users values('$r2','$name','$lname','$ad1','$ad2','$city','$state','$zip','$country','$dob')");
mysqli_close($con);
echo "Form Submitted Succesfully";
?>
This name variable is not have defined in ajax file var dataString = 'name1='+ name + so name would be an empty string
=> if(name=='')
{
alert("");
} executed. Please add string into alert and check again :)
I'll try to be as straight to the point as I can. Basically I using jquery and ajax to call a php script and display members from the database. Next to each members name there is a delete button. I want to make it so when you click the delete button, it deletes that user. And that user only. The trouble I am having is trying to click the value of from one delete button only. I'll post my code below. I have tried alot of things, and right now as you can see I am trying to change the hash value in the url to that member and then grap the value from the url. That is not working, the value never changes in the URL. So my question is how would I get the value of the member clicked.
<script type="text/javascript">
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg()
var friends = new Array();
$.ajaxSetup({
cache: false
})
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var $member_friends = $('#user_list');
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
$member_friends.append("<div class='user_container'><table><tr><td style='width:290px;font-size:15px;'>" + data[i].username + "</td><td style='width:290px;font-size:15px;'>" + data[i].email + "</td><td style='width:250px;font-size:15px;'>" + data[i].active + "</td><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showOptions();'>Options</a></td></tr><tr class='options_panel' style='display:none'><td><a href='#" + data[i].username + "' class='user_delete' data-role='none' onclick='showId();'>Delete</a> </td></tr></table></div>");
}
}
});
});
</script>
<script>
function showId() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
}
</script>
IDEAS:
1st: I think it would be easier to concatenate an string an later append it to the DOM element. It's faster.
2nd: on your button you can add an extra attribute with the user id of the database or something and send it on the ajax call. When getting the attribute from the button click, use
$(this).attr('data-id-user');
Why don't you construct the data in the PHP script? then you can put the index (unique variable in the database for each row) in the button onclick event. So the delete button would be:
<button onclick = "delete('indexnumber')">Delete</button>
then you can use that variable to send to another PHP script to remove it from the database.
$('body').on('click', 'a.user_delete', function() {
var url = document.URL;
var id = url.substring(url.lastIndexOf('#') + 1);
alert(id);
alert(url);
});
<?php echo $username ?>
Like wise if you pull down users over json you can encode this attribute like so when you create your markup in the callback function:
'<a href="#'+data[i].username+'" data-user-id="'+ data[i].username + '" class="user_delete" data-role="none" >Options</a>'
So given what you are already doing the whole scenerio should look something like:
$(document).delegate("#user_manage", "pagecreate", function () {
$.mobile.showPageLoadingMsg();
var friends = new Array(),
$member_friends = $('#user_list'),
// lets jsut make the mark up a string template that we can call replace on
// extra lines and concatenation added for readability
deleteUser = function (e) {
var $this = $(this),
userId = $this.attr('data-id-user'),
href = $this.attr('href'),
deleteUrl = '/delete_user.php';
alert(userId);
alert(href);
// your actual clientside code to delete might look like this assuming
// the serverside logic for a delete is in /delete_user.php
$.post(deleteUrl, {username: userId}, function(){
alert('User deleted successfully!');
});
},
showOptions = function (e) {
$(this).closest('tr.options_panel').show();
},
userTmpl = '<div id="__USERNAME__" class="user_container">'
+ '<table>'
+ '<tr>'
+ '<td style="width:290px;font-size:15px;">__USERNAME__</td>'
+ '<td style="width:290px;font-size:15px;">__EMAIL__</td>'
+ '<td style="width:250px;font-size:15px;">__ACTIVE__</td>'
+ '<td>Options</td>'
+ '</tr>'
+ '<tr class="options_panel" style="display:none">'
+ '<td>Delete</td>'
+ '</tr>'
+ <'/table>'
+ '</div>';
$.ajaxSetup({
cache: false
})
$(document).delegate('#user_manage #user_container user_options', 'click.userlookup', showOptions)
.delegate('#user_manage #user_container user_delete', 'click.userlookup', deleteUser);
$.ajax({
url: 'http://example.com/test/www/user_lookup.php',
data: "",
dataType: 'json',
success: function (data) {
$.mobile.hidePageLoadingMsg();
var markup;
$member_friends.empty();
for (var i = 0, len = data.length; i < len; i++) {
markup = userTmpl.replace('__USERNAME__', data[i].username)
.replace('__ACTIVE__', data[i].active)
.replace('__EMAIL__', data[i].email);
$member_friends.append(markup);
}
}
});
});
Here's a really simple change you could make:
Replace this part:
onclick='showId();'>Delete</a>
With this:
onclick='showId("+data[i].id+");'>Delete</a>
And here's the new showId function:
function showId(id) {
alert(id);
}
I've made a javascript to make a list of values for a list box. The values comes from database in SQL Server. when I make some change with the values on database, the values on my list box don't update. It seems that the browser caches the value or something, because when I clear the cache on my browser, the values in the list box update.
here is my javascript (authapp.js):
$(document).ready(function(){
$(window).load(function(){
var loads = '<table>'+
'<tr>'+
'<td align="center" class="label">'+
'<img src="../../../Images/loading.gif" alt="Please wait..."
align="middle" style="width:30px;height:30px;">'+
'</td>'+
'</tr>'+
'<tr>'+
'<td align="center" class="label">'+
'<font color="#FFFFFF" face="Arial, Helvetica, sans-serif">Loading...</font>'+
'</td>'+
'</tr>'+
'</table>';
//load selected customer
$.ajax({
type: "GET",
url: "master/authtpl/queries/get_sel_cust.asp",
data: "cunit="+$('#cunit').val()+"&ccduser="+$('#ccduser').val(),
beforeSend: function(){
$('#load_sel').block({
message: loads,
css: { border: 'none',
top: '10%',
width: '10%',
backgroundColor: '#606060',
opacity: '0.3'
}
});
},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
$('#load_sel').unblock();
if(response==undefined){
alert('List q of Selected Customer is not available!');
} else {
$('#selSelected').empty();
var cust = (typeof response.cust) == 'string' ? eval('(' + response.cust + ')') : response.cust;
// get data from json
var count = 0,strs = '';
lent = cust.length;
do {
strs += '<option value="'+cust[count].ckode+'|'+cust[count].cgrup+'|'+cust[count].cnama+'">'+cust[count].ckode+' - '+cust[count].cnama;
count++;
} while (count < lent);
$('#selSelected').append(strs);
}
}
});
});
});
and here is my query to get that value (get_sel_cust.asp):
<!-- #INCLUDE file = "../../../include/createconnection.asp" -->
<%
dwdb = Application("DWDB")
ccdappl = Application("CCDAPPL")
ckdunitkey = trim(Request.QueryString("cunit"))
ccduser = trim(Request.QueryString("ccduser"))
sql = "select distinct ckdrelasi,ckdgruprelasi,vnamarelasi "&_
"from " & dwdb & ".dwaustasia.dbo.ms_webuser_apprtpl "&_
"where ckdunitkey='"&ckdunitkey&"' and ccduser='"&ccduser&"' and ccdappl='"&ccdappl&"' "&_
"order by ckdrelasi"
objCommand.commandText = sql
'response.write sql
set aloc = objCommand.execute
if NOT aloc.BOF then
aloc.moveFirst
json = "{ ""cust"" : [ "
body_json = ""
temp = ""
WHILE NOT aloc.EOF
temp = "{"&_
"""ckode"":"""&aloc("ckdrelasi")&""","&_
"""cgrup"":"""&aloc("ckdgruprelasi")&""","&_
"""cnama"":"""&aloc("vnamarelasi")&""""&_
"},"
body_json = body_json&temp
aloc.moveNext
WEND
body_json = mid(body_json,1,len(body_json)-1)
json2 = " ] } "
hasil = json&body_json&json2
response.write hasil
end if
set objCommand = nothing
response.end
%>
and this is the list box form (default.asp):
<SELECT name="selSelected" id="selSelected" MULTIPLE SIZE="10" class="label" style="width:250px;">
</SELECT>
I don't know where is the problem comes from. Can you tell me did I make some mistake on my coding? thanks :)
Try disabling the AJAX caching in jQuery:
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});
There are loads of places caching can happen - but it'll be easier to start with the client and work backwards.