I want to populate a table with PHP script data using jQuery. I am trying as
<script type="text/javascript" src="js/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function(){
$("#button").click(function(){
$.ajax({
url: "http://localhost/test.php",
type:"POST",
async:true,
data:{
"done":1,
"searchDat" : searchDat,
},
success: function(data){
//alert( JSON.parse(data));
var array = JSON.parse(data);
var trHTML = '';
$.each(array, function(ind,value) {
console.log(value);
trHTML += '<tr><td>' + value + '</td><td>' + value+ '</td></tr>';
});
$('#Table').append(trHTML);
}
});
});
});
</script>
HTML
<table id="Table">
<tbody>
<tr><td>ID</td></tr>
<tr><td>ID2</td></tr>
</tbody>
</table>
Button
<form>
<input type="submit" value="Search" id ="button" style="width:50%;border-radius:8px;padding: 15px 4px;"/>
</form>
The problem is that the table is populated for 1 second and then disappears in the webpage. What am I doing wrong?
Edit 1
<script type="text/javascript">
$("form").on('submit', function(e){
e.preventDefault();
$.ajax({
url: "http://localhost/bbcprg/getPrograms.php",
type:"POST",
data: {
"done": 1,
},
success: function(data){
//alert( JSON.parse(data));
var arrayData = JSON.parse(data);
var trHTML = '';
$.each(arrayData, function(ind,value) {
console.log(value);
trHTML += '<tr><td>' + value + '</td><td>' + value+ '</td></tr>';
});
$('#Table').append(trHTML);
}
});
});
</script>
The issue is because you've attached the event to the click of the button. This means that while your AJAX request works, the form is still being submit, and hence the page gets refreshed.
To fix this, hook to the submit event of the form instead, and call preventDefault() on the event passed to the handler. Try this:
$("form").on('submit', function(e){
e.preventDefault();
$.ajax({
url: "http://localhost/test.php",
type:"POST",
data: {
done: 1,
searchDat: searchDat,
},
dataType: 'json',
success: function(data) {
var html = data.map(d => '<tr><td>' + d + '</td><td>' + d + '</td></tr>').join('');
$('#Table tbody').append(html);
}
});
});
Also note that you can simplify the logic which builds the HTML to append by using map() on the data array. You also don't need to manually call JSON.parse() if you specify the correct dataType on the $.ajax request. I've also assumed that searchDat is defined outside the function.
Finally I'd suggest you place an id on the form to make the selector less generic, and also you should move the inline style rules in to an external stylesheet.
change
<input type="submit" value="Search" id ="button" style="width:50%;border-radius:8px;padding: 15px 4px;"/>
to this
<input type="button" value="Search" id ="button" style="width:50%;border-radius:8px;padding: 15px 4px;"/>
Related
I'm trying to update the paragraph tag in foreach with jquery selector in my second ajax call. I made the id tag unique by setting it to id="spots_,+item.id" but don't know how to access the dynamic id tag outside the foreach loop. I keep getting "id is not defined" error. Thought maybe a global variable would work but no success.
//ajax form the get available times to play
$('#form').submit(function(){
$.ajax({
url: $('#form').attr('action'),
type: 'POST',
data : $('#form').serialize(),
success: function(response){
$.each(JSON.parse(response), function(i, item) {
var jdate = $('#date').val();
$('<tr>').html("<td>" + item.time + "</td><td>" + '<form class="insideForm" action="/reservations/getSpots" accept-charset="utf-8" method="">' + '<input type="text" name="jtime" value="' + item.time + '"' + "/>" + '<input type="text" name="jdate" value="' + jdate + '"' + ">" + '<input type="submit" class="btn btn-primary" value="Spots">' + '</form>' + "</td><td>" + "Spots:" + '<p class="spots" id="spots_' + id + '"'+ ">" + '<div id="spots"></div>' + '</p>' + "</td>").appendTo('#availableTimes');
});//end loop
//ajax form the get available spots/seats
$('.insideForm').submit(function(){
var form = $(this).closest('form');
$.ajax({
url: $(this).attr('action'),
type: 'POST',
data : $(this).serialize(),
success: function(response){
$('#spots_'+id).html(response);
}//end success
});
return false;
});
}//end success
});
return false;
});//end ajax time form
In your .insideForm object you only have one .spots classed paragraph.
Try using the jQuery selector inside the form:
$('.insideForm').submit(function () {
var form = $(this).closest('form');
$.ajax({
url: form.attr('action'),
type: 'POST',
data: form.serialize(),
success: function (response) {
$('.spots', form).html(response);
}//end success
});
return false;
});
In your $.ajax call change url: $(this).attr('action') to url: form.attr('action'). Inside the callback, $(this) refers to the jqXHR object of the ajax call, not the element the event handler was bound to.
EDIT
I also changed $(this).serialize() to form.serialize() for the same reason above.
//ajax form the get available spots/seats
$('.insideForm').submit(function() {
var form = $(this).closest('form');
$.ajax({
url: form.attr('action'),
type: 'POST',
data: form.serialize(),
success: function(response) {
$('#spots_' + id).html(response);
} //end success
});
return false;
});
I am following some online ajax tutorials, the example is about calling a webapi using GET method, here is the script section on the page
<script type="text/javascript">
$(document).ready(function () {
var ulEmployees = $('#ulEmployees');
$('#btn').click(function () {
$.ajax({
type: 'GET',
url: "http://localhost:35468/api/employee",
dataType: 'json',
async: true,
success: function (data) {
ulEmployees.empty();
$.each(data, function (index, value) {
var fullName = value.FirstName + ' ' + value.LastName;
ulEmployees.append('<li>' + fullName + '</li>');
});
}
});
});
$('#btnClear').click(function () {
ulEmployees.empty();
});
});
</script>
It should render the emoloyee first and last name within a list item in the .
<div>
<input id="btn" type="button" value="Get All Employees" />
<input id="btnClear" type="button" value="Clear" />
<ul id="ulEmployees">
</ul>
</div>
the each function iterates the on the object but it displays undefined in the html
does anyone know a solution to this ?
Solved
the problem was because the field names FirstName and LastName was incorrect,
correct field names are firstName and lastName thats why the object was not populating them in a correct manner.
I hope I can explain my issue clearly.
I am running a function to get values from a database using ajax, and adding each result as a row in a table. This is so the user can delete or edit any row they want. I'm adding IDs dynamically to the columns and also the edit and delete buttons which are generated. So it looks like this:
My code:
function getstationdata(){
var taildata1 = $('#tailnumber2').val();
var uid = $('#uid').val();
$.ajax({
// give your form the method POST
type: "POST",
// give your action attribute the value ajaxadd.php
url: "ajaxgetstationdata.php",
data: {tailnumber:taildata1, uid:uid},
dataType: 'json',
cache: false,
})
.success(function(response) {
// remove all errors
$('input').removeClass('error').next('.errormessage').html('');
// if there are no errors and there is a result
if(!response.errors && response.result) {
var trHTML = '';
$.each(response.result, function( index, value) {
trHTML += '<tr><td><input type="text" value="' + value[2] + '"></td><td><input type="text" class="weightinputclass"value="' + value[3] + '"></td><td><input type="text" class="arminputclass"value="' + value[4] + '"></td><td><input type="text" class="momentinputclass" value="' + value[5] + '"></td><td><button id="updatecgbtn" onclick="updatecg()"class="editbuttonclass">Edit</button></td><td><button id="deletecgbtn" class="deletebuttonclass"">Delete</button></td></tr>';
});
$('#mbtbody').html('');
$('#mbtbody').html(trHTML);
var ID = 0;
$('.weightinputclass').each(function() {
ID++;
$(this).attr('id', 'weightinputboxID'+ID);
});
var ID = 0;
$('.arminputclass').each(function() {
ID++;
$(this).attr('id', 'arminputboxID'+ID);
});
var ID = 0;
$('.momentinputclass').each(function() {
ID++;
$(this).attr('id', 'momentinputboxID'+ID);
});
var ID = 0;
$('.editbuttonclass').each(function() {
ID++;
$(this).attr('id', 'editbutton'+ID);
});
var ID = 0;
$('.deletebuttonclass').each(function() {
ID++;
$(this).attr('id', 'deletebutton'+ID);
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
}
The code I have when adding the info is in a form and it looks like this:
$('#addstations').on('submit', function(e){
e.preventDefault();
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'json',
cache: false,
})
.success(function(response) {
$('input').removeClass('error').next('.errormessage').html('');
if(!response.errors && response.result) {
$.each(response.result, function( index, value) {
chartdata4=(tailnumber3.value)
});
} else {
// append the error to the form
$.each(response.errors, function( index, value) {
// add error classes
$('input[name*='+index+']').addClass('error').after('<div class="errormessage">'+value+'</div>')
});
}
});
});
I searched a bit on the internet and found out that I can't add a form inside my table for each row which would have been easy to do and I can reuse my code which I use when adding new info.
So, can someone please point me in the right direction?
Here is the direction you could go
$('#formTable').on('click',"button" function(e){
var $row = $(this).closest("tr"), $form = $("#addstations");
var data = {
passenger:$row.find("passengerClass").val(),
weight :$row.find("weightClass").val()
} // no comma on the last item
data["type"]=this.className=="deletebuttonclass"?"delete":"edit";
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
dataType: 'json',
cache: false,
})
...
I assume that the problem is that you want to add a form as a child of a table / tbody element to wrap your row. You cannot do that and the browser will most likely strip the form tags, leaving you with nothing to serialize.
There are different solutions for that, for example:
Build the data object manually in javascript when a button on a row is clicked;
Use a non-form grid solution for your layout.
Add each row in its own table and have the form wrap that table
The third solution is a bit of a hack, I would use the first or the second myself.
I am getting xml file content using jquery and binding in to textbox, if anybody change the value in the text box , same has to be reflected in the source xml file, how to do that, i am new to xml.
Here is the code i am using to get the data from xml file.
<html><head>
<link rel="stylesheet" type="text/css" media="all" href="style.css" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "GET",
url: "employees.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('Employee').each(function() {
var id = $(this).attr('id');
var name = $(this).find('Name').text();
var designation= $(this).find('Designation').text();
// alert(id + '|' + name + '|' + designation);
$('<div class="items" id="' + id + '"></div>').html('<input type="text" value="' + name + '">').appendTo('#page-wrap');
});
}
});
});
function saveXMLFiles() {
$("#page-wrap").find('id').each(function() {
var description = $(this).find('Designation').text();
alert(description);
});
}
</script>
</head>
<body>
<div id="page-wrap">
<h1>
Employees</h1>
</div>
<input type="button" value="Save" onclick="saveXMLFiles();" />
First create a web method for updating the XML in your server side.
Again you have to write an ajax request for updating the XML.
This is purely depends on your server-side.
Keep these things in mind:
You have to take the value of xml in a variable that is accessible to all the functions so that you can change it when somebody change the value in text box
Pass the value of updated xml to the server;
So do like this;
<script type="text/javascript">
$(document).ready(function() {
var globalXML = null;
$.ajax({
type: "GET",
url: "employees.xml",
dataType: "xml",
success: function(xml) {
globalXML = xml;//this is going to set in global variable
$(xml).find('Employee').each(function() {
var id = $(this).attr('id');
var name = $(this).find('Name').text();
var designation= $(this).find('Designation').text();
// alert(id + '|' + name + '|' + designation);
$('<div class="items" id="' + id + '"></div>').html('<input type="text" value="' + name + '">').appendTo('#page-wrap');
});
}
});
});
function saveXMLFiles() {
$("#page-wrap").find('id').each(function() {
var description = $(this).find('Designation').text();
//change to globalXML;
//and send it to server;
$.ajax({
type: "POST",
url: "saveEmployeesToXML",//path to post
data: globalXML,
success: function(response) {
alert(response);
}
});
}
});
alert(description);
});
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: "XML/Website.xml",
dataType: "xml",
success: function (xml) {
var arr = new Array();
$(xml).find("board").each(function () {
var option = $(this).find('brand').text();
if ($.inArray(option, arr) > -1) {
// Do nothing
}
else {
$('#dropdown').append('<option>' + option + '</option>');
arr.push(option);
}
});
}
});
});
</script>
<form>
<select id="dropdown">
<option></option>
</select>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: "XML/Website.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('board').each(function () {
var image = $(this).find('image').text();
var name = $(this).find('name').text();
var brand = $(this).find('size').text();
var brand = $(this).find('camber').text();
var price = $(this).find('price').text();
$('#table').append('<tr><td><img width="250px" src="' + image + '"/></td><td>' + name + '</td><td>' + brand + '</td><td>' + price + '</td></tr>');
});
}
});
});
</script>
<table id="table" border="1" cellspacing="5" cellpadding="20" class="center">
<tr><td></td><th>Name</th><th>Camber</th><th>Price</th><th>Size</th></tr>
</table>
</body>
</html>
My XML data is being displayed on the page, but when I use the drop down to select what specifics I want to be selected, It will not change anything. I do not know what I am doing wrong.
My XML tags are all correct I have made sure of it.
In the code you have posted, I don't see where you ask it to change anything when you select something in the drop down.What do you expect it to do? You will need to add a change listener to the drop down, and tell it what to do when it is changed, like this...
$("#dropdown").change(function() {
//Do what you want to do when the drop down is changed.
//You can get the text of the drop down like this...
var selected = $("#dropdown option:selected").text();
});
Also, as a side note, try refactoring your code so you only make the ajax call once, and use the output for both. Looks like your calling the same service twice for the same data which is extra work for no reason.