I have a HTML table and Edit - Delete - Save images are associated with each row. Now I want to edit any cell and when I'll click on Save-image it will be displayed on the HTML table with updated values, as well as the associated table in the database will also be changed. I want to do this using Jquery Ajax and PHP but in MVC way. I have tried but somehow database changes are not happening, while HTML table is showing the updated values.
Ajax Code:
function Save()
{
var par = $(this).parent().parent();
var tdCid = par.children("td:nth-child(2)");
var tdCname = par.children("td:nth-child(3)");
var tdCtype = par.children("td:nth-child(4)");
var tdRegno = par.children("td:nth-child(5)");
var tdFare = par.children("td:nth-child(6)");
var tdNightfare = par.children("td:nth-child(7)");
var tdButtons = par.children("td:nth-child(8)");
var Cid = $("#tdCid").val();
var Cname = $("#tdCname").val();
var Ctype = $("#tdCtype").val();
var Regno = $("#tdRegno").val();
var Fare = $("#tdFare").val();
var Nightfare = $("#tdNightfare").val();
$.ajax({
url:"cardetails.php",
type:"POST",
data:{cid:Cid, name:Cname, cartype:Ctype, regno:Regno,fare:Fare, nfare:Nightfare},
success: function(response){
if(response==1){
alert('Data Inserted / Modified Successfully');
}
else
{
alert('Error !! Data Insertion / Modification Failed');
}
}
})
tdCid.html(tdCid.children("input[type=text]").val());
tdCname.html(tdCname.children("input[type=text]").val());
tdCtype.html(tdCtype.children("input[type=text]").val());
tdRegno.html(tdRegno.children("input[type=text]").val());
tdFare.html(tdFare.children("input[type=number]").val());
tdNightfare.html(tdNightfare.children("input[type=number]").val());
tdButtons.html("<img src='delete.png' class='btnDelete'/><img src='edit.png' class='btnEdit'/>");
$(".btnEdit").bind("click", Edit);
$(".btnDelete").bind("click", Delete);
};
cardetails.php script:
include('helper.php');
$car = new Admin;
$r=$car->update($_POST['cid'],$_POST['name'],$_POST['cartype'],$_POST['regno'],$_POST['fare'],$_POST['nfare']);
if($r==1)
return 1;
else
return 0;
helper.php script:
class Admin extends connection
{
var $update;
var $insert;
var $delete;
function update($id,$name,$typ,$rno,$fare,$ncharge)
{
$this->update=mysqli_query($this->con,"UPDATE cars SET cname='$name',ctype='$typ',regno='$rno',fare='$fare',nightcharge='$ncharge' WHERE cid='$id'") or die(mysqli_error($this->con));
if($this->update)
{
return 1;
}
}
}
the path and connection class and all the names and id included within the AJAX query, PHP script and database table has been cross-checked twice.
Related
I am building a form to process text input, multiple check boxes and 4 images. currently I am to process the check boxes using the each function to put all the values of the checkboxes in an array before sending it through ajax. Now the problem is that I can't send the images with ajax too. And also I can't access the images too.
Code:
$(document).ready(function () {
//alert("this page works");
$('#uploadProperty').on('submit',function (e){
e.preventDefault();
var hname = $('#hname').val();
var location = $('#location').val();
var htype = $('#htype').val();
var rooms = $('#rooms').val();
var price = $('#price').val();
var hdetails = $('#hdetails').val();
var feature = [];
$('.feature').each(function() {
if($(this).is(":checked")){
feature.push($(this).val());
}
});
// if (feature.length == 0)
// alert("Select atleast 1 Feature");
// else{
// feature = feature.toString();
// alert(feature);
// }
var file1 = $('#file4').val();
//alert(file1);
$.ajax({
url : 'core/upload.php',
type : 'POST',
data : new FormData(),
contentType : false,
processData : false,
success : function (ep){
alert(ep);
}
});
});
});
You need to upload images first via ajax ( ex: http://hayageek.com/docs/jquery-upload-file.php ) and after make another ajax for the form fields. But you need an ID link between Property and images. you cand add an empty record and remember the mysql_insert_id to make update with the form fields and insert images or update ( depend how is your table structure )
So if i got it right, you want to fill the FormData object. Because currently it's empty.
You can use append method:
var formData = new FormData();
var $myField = $('#myField');
formData.append('myField', $myField.val());
To append file:
var $fileField = $('#fileField');
var myFile = $fileField.get(0).files[0];
formData.append('myFile', myFile);
To append multiplie files you should set the name properly:
formData.append('myFile[]', myFileFirst);
formData.append('myFile[]', myFileSecond);
Check it here: Uploading multiple files using formData()
Also, you can grab the whole form data through constructor:
var form = $('form').get(0);
var formData = new FormData(form);
I have a question that I am designing a webpage to process database. So the idea is,
I have a dropdown
When user click on of the options,
Directly open a new window containing another webpage
On the new page, getting the value from the dropdown on the new page for the database monitoring with $_POST
The problem is, When I click the option, it redirects to that new page but not in the form of a new window.
And how do I send the selected value to be used on the new page with
$newVal = strval($_POST['PROJECT_NAME']);
My code is,
<script>
$(function(){
$('#cd-dropdown').bind('change', function () {
var url = $(this).val(); // get selected value
if (url) { // require a URL
window.location = "monitorIndex.php"; // redirect
}
return false;
});
});
</script>
And the markups:
$projectParse = oci_parse($conn, 'SELECT DISTINCT PROJECT_NAME FROM MASTER_DRAWING '
. 'ORDER BY PROJECT_NAME ASC');
oci_execute($projectParse);
echo '<select name="cd-dropdown "id="cd-dropdown" class="cd-select">';
echo '<OPTION VALUE="">PROJECT SELECT</OPTION>';
while($row = oci_fetch_array($projectParse,OCI_ASSOC)){
$projectName = $row ['PROJECT_NAME'];
echo "<OPTION VALUE='$projectName'>$projectName</OPTION>";
}
echo '</select>';
Try this one.
$('#cd-dropdown').change(function(){
var id = $(this).val();
window.location = 'monitorIndex.php?id=' + id;
});
Try the below code
$('#cd-dropdown').change(function(){
var id = $(this).val();
$.ajax({
type: "POST",
url: "monitorIndex.php",
data: { PROJECT_NAME: id }
})
.done(function( msg ) {
var myWindow = window.open("", "MsgWindow", "width=800, height=800");
myWindow.document.write(msg );
});
});
This method should take you to new window with ProjectName in URL.
$('#dropdown').change(function(){
var id = $(this).val();
window.open ('monitorIndex.php?id=' + id ,'_blank');
});
Or another way is if you are using HTML5 , you can use local storage,
You can basically keep the value on client side localstorage and can access it on any other page.
// Store
localStorage.setItem("projectname", "abc");
// Retrieve
document.getElementById("result").innerHTML = localStorage.getItem("projectname");
I have a database where i'm using php to randomize the information by ID and send it out via xml. My issue is that I only want to grab the xml once and store it for use in at least 2 functions... one function that runs onload to grab the first line of xml, another that will run every time a button is pressed to access the next line of xml until the end. My 2 functions are loadfirst() and loadnext(). loadfirst() works perfectly, but I'm not sure how to pass the xml data to loadnext(). Right now I'm just using loadfirst() on pageload and loadfirst() on button press, but i end up creating new xml from the database each time which causes randomization issues and is incredibly inefficient. Any help would be appreciated.
var places;
var i = 0;
function loadXML(){
downloadUrl("places.php", function(data){
places = data.responseXML;
getFeatured(i);
});
}
function getFeatured(index){
var id = places[index].getAttribute("id");
var name = places[index].getAttribute("name");
var location = places[index].getAttribute("location");
var imgpath = places[index].getAttribute("imgpath");
var tags = places[index].getAttribute("tags");
}
function getPrev() {
i--;
getFeatured(i);
}
function getNext() {
i++;
getFeatured(i);
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
loadnext() will be very similar to loadfirst(), I'm just running into issues with passing the xml data so that i can use it without having to access the database again. Thanks.
Set your xml and i in public scope. Then all you have to do is increment/decrement i and re-read data from XML. Something like this:
var xml;
var xml_idx = 0; // replaces your i counter
function loadXML() {
downloadUrl ("places.php", function(data) {
xml = data.responseXML;
)};
}
function loadItem(index) {
var id = xml[index].getAttribute("id");
var name = xml[index].getAttribute("name");
var location = xml[index].getAttribute("location");
var imgpath = xml[index].getAttribute("imgpath");
var tags = xml[index].getAttribute("tags");
// do something with this data
}
function loadCurrentItem() {
loadItem(xml_idx);
}
function loadNextItem() {
xml_idx++;
loadItem(xml_idx);
}
function loadPreviousItem() {
xml_idx--;
loadItem(xml_idx);
}
// usage
loadXML(); // do this first to populate xml variable
loadItem(xml_idx); // loads first item (i=0)
loadCurrentItem(); // loads i=0
loadNextItem(); // loads i=1
loadNextItem(); // loads i=2
loadPreviousItem(); // loads i=1
If you really want to get fancy (and keep the global namespace cleaner), you could easily make this into a class.
Use global variables (items - items array, iterator - counter) to store data available for all functions.
Try something like this:
items = false;
iterator = 0;
function loadfirst(){
downloadUrl ("places.php", function(data) {
var i = 0;
var xml = data.responseXML;
var places = xml.documentElement.getElementsByTagName("place");
var id = places[i].getAttribute("id");
var name = places[i].getAttribute("name");
var location = places[i].getAttribute("location");
var imgpath = places[i].getAttribute("imgpath");
var tags = places[i].getAttribute("tags");
items = places;
iterator++;
)};
}
function loadnext(){
var i = iterator;
var id = items[i].getAttribute("id");
var name = items[i].getAttribute("name");
var location = items[i].getAttribute("location");
var imgpath = items[i].getAttribute("imgpath");
var tags = items[i].getAttribute("tags");
iterator++;
}
You should wrap all this into a single object to control scope and data state. (Untested code below, which should just illustrate a possible pattern and interface to use.)
function PlacesScroller(url, callback) {
this.url = url;
this.data = null;
this._index = null;
this.length = 0;
var self = this;
downloadURL(this.url, function(result, status) {
if (Math.floor(status/100)===2) {
self.setData(result);
}
if (callback) {
callback(self, result);
}
});
}
PlacesScroller.prototype.setData(xmldom) {
this._index = 0;
// this may require changing; it depends on your xml structure
this.data = [];
var places = xmldom.getElementsByTagName('place');
for (var i=0; i<places.length; i++) {
this.data.push({
id : places[i].getAttribute('id'),
name : places[i].getAttribute('name')
// etc
});
}
}
PlacesScroller.prototype.getPlaceByIndex = function(index) {
if (this.data) {
return this.data[index];
} else {
return null;
}
}
PlacesScroller.prototype.getCurrentFeature = function() {
return this.getPlaceByIndex(this._index);
}
PlacesScroller.prototype.addToIndex(i) {
// This sets the index forward or back
// being careful not to fall off the end of the data
// You can change this to (e.g.) cycle instead
if (this.data===null) {
return null;
}
var newi = i+this._index;
newi = Math.min(newi, this.data.length);
newi = Math.max(0, newi);
this._index = newi;
return this._index;
}
PlacesScroller.prototype.getNextFeature = function() {
this.addToIndex(1);
return this.getCurrentFeature();
}
PlacesScroller.prototype.getPreviousFeature = function() {
this.addToIndex(-1);
return this.getCurrentFeature();
}
Then initialize it and use it like so:
var scroller = new PlacesScroller('places.php', function(scrollerobject, xmlresult){
// put any initialization code for your HTML here, so it can build after
// the scrollerobject gets its data.
// You can also register event handlers here
myNextButton.onclick = function(e){
var placedata = scrollerobject.getNextFeature();
myPictureDisplayingThing.update(placedata);
}
// etc
});
The issue:
I have a timesheet application. It has an SQlite database. I am trying to find a way to present a GUI so that if the user clicks a square(a ) i need to paas the data from the template to the model (paris) so i can save it in theb SQlite database.
There are three tables one for users one for the timesheet and one for the department.
It is a timesheet like application.
The setup:
Slim php
Idiorm/Paris
SQlite3
Does anyone know a good way to make the user click a so that the data is passed on to the model from the view?
Thank you in advance!
Imagine this is your view
<html>
<head>
$(document).ready(function() {
$("#add").on("click", function(e) {
var user_id = $('#user_id').val();
var time = date();
var department = $('#department').val();
var data = {uid:user_id, time:time, dept:department};
$.ajax({
url: "add_into_db.php",
type: 'POST',
data: data,
success: function(msg) {
if(msg=="true"){
alert("Your dats is inserted successfully");
document.location.reload(true);
}
else{
alert("Your data insertion failed");
return false;
}
}
});
e.preventDefault();
});
});
</head>
<body>
// Some html here
// input field for user
// input field for time
// input field for department
// whatever data you want os send on click, include it here
<input id ='add' type= 'submit' value 'Add'/> //Your submit button to add data via AJAX
</body>
Yout php function which will add data into database
function add_into_db(){
$user id = $_POST['user_id'];
$time = $_POST['time'];
$dept = $_POST['department'];
// connect to your db
// run your insert query
If (insertion is successfull) {
$msg = 'true';
echo $msg;
}
else{
$msg = 'false';
echo $msg
}
}
Hope it ill help you
Having trouble using ajax to retrieve info from a database. I was getting the code from here:
http://openenergymonitor.org/emon/node/107
the code from here worked but would only output 1 item
Simple Ajax Jquery script- How can I get information for each of the rows in the table?
I tried to add this to my code but I could not get it to work.
I am getting everything from a table with the following php:
$result = mysql_query("SELECT * FROM voterecords");
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode($data);
which outputs the following if I navigate to that php page:
[["68","1234","0","1234",""],["69","added with ajax","0","this item was added using ajax",""]]
The format of the above is as follows:
id, title, votes, description, owner
I think that bit all works but I cant be sure because i dont know what JSON is supposed to look like.
Ok now here is the jquery which is supposed to retrieve the info from the JSON and put it into the html element #output
$(function ()
{
$.ajax({
url: 'retrieve.php', data: "", dataType: 'json', success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var id = row[0];
var name = row[1];
var votes = row[2];
var info = row[3];
$('#output').append("<b>id: </b>"+id+"<b> name: </b>"+name+"<b> votes: </b>"+votes+"<b> info: </b>"+info)
.append("<hr />");
}
}
});
I was expecting this to output all the info but nothing happens.
Your code is fine except you have a missing closing ) from the callback function.
Also, in JavaScript, it's better to place opening braces on the same line, not on the next, as is common in some other languages.
Corrected/cleaned-up code:
$(function () {
$.ajax({url: 'retrieve.php', dataType: 'json'}).done(function(rows) {
for (var i in rows) {
var row = rows[i];
var id = row[0];
var name = row[1];
var votes = row[2];
var info = row[3];
$('#output')
.append("<b>id: </b>"+id+"<b> name: </b>"+name+"<b> votes: </b>"+votes+"<b> info: </b>"+info)
.append("<hr />");
}
});
});