How to empty ajax data before sending it? - javascript

I have a form, when I submit it it creates an ajax function and then creates a table out of the data in the success. But knowing that my page is dynamic (without reloading the page I call the ajax function many times), but each time the data in the success doesn't get removed before generating more data. Is that normal? How can I empty the success data variable before sending the ajax?
Function :
function submitForm() {
if ($.fn.DataTable.isDataTable("#table")) {
$('#table').DataTable().clear();
$('#table').DataTable().destroy();
$('#table').empty();
}
url = $("#form").serialize();
console.log(url);
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: '/api/test?'+url,
'beforeSend': function (request) {
data = {}; // like this maybe?
},
success: function (data) {
//Getting data variable containing
data = data.data;
//the second time I call the function, data contains the new and old stuff at the same time
}
});
}
Form :
<form method="GET" action="" class="form-horizontal" id="form" onsubmit="return false;">
<button type="submit" onclick="submitForm();">Update table</button>
</form>
Table :
<table class="table table-striped display nowrap col-md-12" id="achats_table">
<thead>
<tr style="border-bottom:2px dashed #ccc"></tr>
</thead>
<tbody></tbody>
<tfoot align="right">
<tr></tr>
</tfoot>
</table>

You have to empty the table in beforeSend,
function submitForm() {
url = $("#form").serialize();
console.log(url);
$(document).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: '/api/test?'+url,
'beforeSend': function (request) {
if ($.fn.DataTable.isDataTable("#achats_table")) {
$('#table').DataTable().clear();
$('#table').DataTable().destroy();
$('#table').empty();
}
},
success: function (data) {
//Getting data variable containing
data = data.data;
//the second time I call the function, data contains the new and old stuff at the same time
}
});
}

Related

How to submit dynamic data without form?

I am getting data as form of Java Bean and I am inserting each value into a table.
Values are retrieved as common way at first.
But I added some Javascript source, so that I can modify the value if I click any area near it.
Now I would like to save the data in database as well if there was any change after I modify.
How can I do that?
Here is my HTML code
<table class="bg-light table table-hover" style="overflow:hidden">
<th>Word</th>
<th>Dialogue</th>
<th>Practice</th>
<c:forEach items="${list}" var="engboardVO">
<tr>
<td data-editable>${engboardVO.word}</td>
<td data-editable>${engboardVO.dialogue}</td>
<td data-editable>${engboardVO.practice}</td>
</tr>
</c:forEach>
</table>
And Javascript
$("body").on("click", "[data-editable]", function() {
var $el = $(this);
/* var $input = $('<input style="width:500px; height:100px"/>').val( $el.text() ); */
var $input = $('<textarea rows=5 style="width:500px"/>').val($el.text());
$el.replaceWith($input);
var save = function() {
var $td = $("<td data-editable />").text($input.val());
$input.replaceWith($td);
};
$($input).blur(function() {
save();
})
});
You can use ajax for submitting data without form.
I can see you are using jQuery library. So I am writing code based on this library.
In HTML:
<table class="bg-light table table-hover" style="overflow:hidden">
<th>Word</th>
<th>Dialogue</th>
<th>Practice</th>
<c:forEach items="${list}" var="engboardVO">
<tr>
<td data-name="word" data-editable>${engboardVO.word}</td>
<td data-name="dialogue" data-editable>${engboardVO.dialogue}</td>
<td data-name="practice" data-editable>${engboardVO.practice}</td>
</tr>
</c:forEach>
</table>
In javascript:
$("body").on("click", "[data-editable]", function() {
var $el = $(this);
var $input = $('<textarea rows=5 style="width:500px"/>').val($el.text());
$el.html($input);
var field_name = $el.attr('data-name');
var save = function() {
var $val= $input.val();
$.ajax({
type: "POST",
url: "update-url",
data: {fieldname: field_name, fieldvalue:$input.val()},
dataType: "json",
success: function(msg) {
// do something on success
$el.html($val);
},
error: function(msg){
// do something on error
}
});
};
$($input).blur(function() {
save();
})
});
Then in server side, you can save fieldvalue as value of fieldname in your database.
Basically what we are doing here is:
Added an attribute data-name in td tag, its value can be related to your field name in table.
Get the name of attribute in javascript using var field_name = $el.attr('data-name');.
Using post request in ajax call passed the field_name and and value of this field to server.
$.ajax({
type: "POST",
url: "update-url",
data: {fieldname: field_name, fieldvalue:$input.val()},
dataType: "json",
success: function(msg) {
// do something on success
$el.html($val);
},
error: function(msg){
// do something on error
}
});
Now in server side, you need to fetch this data as you fetch normally for post request in submit of a form and save this data in database.
url is same as action you provide in form tag.
Edit:
Check now. You were replacing the td, whereas you had to replace html inside td.
Don't worry if you don't have a form or can't have it for some reasons
You can still read the inputs of your web page and use them or send them to the server.
See below a simple example:
var inputs = document.getElementsByTagName('input');
var data = []
for (index = 0; index < inputs.length; ++index) {
// deal with inputs[index] element.
data.push(inputs[index].value)
}
var json = JSON2.stringify(data);
$.ajax({
type: "POST",
url: "your-api-url",
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// done code
}
});

how to view the data when searching without submitting | angularjs

in order to make the search process faster, my client requested to view the data when just the search box is filled without even submitting, my code works fine at submitting, what should i change with my code so i can get the desired result. this is my first project with angular js, i am very new to this technology. Many thanks in advance.
HTML View:
<input id="searchInput" type="text"/> // search box where
// the function below "getSearchResults()" will get results when submitting
<input ng-click="getSearchResults()" type="submit"/>
<table>
<thead>
<tr>
<th>NOM</th>
<th>TELEPHONE</th>
<th>LOCATION</th>
<th>CODE</th>
</tr>
</thead>
<tbody >
//view the data
<tr ng-repeat="c in clients">
<td>{{c.firstname}} {{c.lastname}}</td>
<td>{{c.telephone}}</td>
<td>{{c.location}}</td>
<td>{{c.code}}</td>
</tr>
</tbody>
</table>
Js source:
var app = angular.module('DMDGroup', []);
$scope.clients;
app.controller('ClientALL', function($scope, $http) {
/* the function put all results in the scope variable (client) in a json
form and the results viewed with the ng-repeat on the tr tag*/
$scope.getSearchResults=function(){
var searchKeyWord=$("#searchInput").val();
var url = '../php/clients.php';
var data = {"function":"getClients",
"searchKeyWord":searchKeyWord};
var options={
type : "get",
url : url,
data: data,
dataType: 'json',
async : false,
cache : false,
success : function(response,status) {
$scope.clients = response;
$scope.$apply();
},
error:function(request,response,error){
alert("Error: " + error + ". Please contact developer");
}
};
$.ajax(options);
}
}
i want the to directly change the data in the table depends on the search results, i'll attach an image of my view
put ng-change instead of ng-click
<input ng-change="getSearchResults(searchVal)" ng-model="searchVal" class="searchClientBtn" type="submit"/>
in controller function
$scope.getSearchResults=function(value){
var url = '../php/clients.php';
var data = {"function":"getClients",
"searchKeyWord": value};
var options={
type : "get",
url : url,
data: data,
dataType: 'json',
async : false,
cache : false,
success : function(response,status) {
$scope.clients = response;
$scope.$apply();
},
error:function(request,response,error){
alert("Error: " + error + ". Please contact developer");
}
};
$.ajax(options);
}

How can i post data and file by using ajax on event onclick

HTML here.
<form id="myForm">
<input type="text" name="name">
<input type="file" name="userImage">
<button onclick="post('./example.php')" type="button">Save</button>
</form>
Now i want to post it by using post() function
Java-script:
Function post(url){
$.ajax({
url:url,
type: 'POST',
data: $("#myform").serialize(),
success: function (data) {
alert("successfully posted.");
}
});
}
But not serialized file
My advice is: try to have apart html and js defining the event callback on "attacheventlistener" function or "on" jquery's function (this way is easier).
Your problem is that you are passing the string "url" when you need pass a valid url, so write the url directly on ajax url field or define a data attribute on your form tag, e.g. data-url="http://whatever", and catch this value from the event.
If you use jquery's "on" function is extremly easy, you could to get it data's value via jquery's "data" function over "this" var.
Something like ...
$("#myForm").on("click",
function() {
post(this.data("url"));
});
But probably you do not need url being a var.
If I understand correctly, the problem is that nothing is being posted.
The thing is is that you are trying to do a file upload via ajax, this is not wrong but it needs to be done differently shown here:
jQuery Ajax File Upload
You can add extra data with form data
use serializeArray and add the additional data:
var data = $('#myForm').serializeArray();
data.push({name: 'tienn2t', value: 'love'});
$.ajax({
type: "POST",
url: "your url.php",
data: data,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
});
First of all i need to say that, if you want to upload file, i mean if your form have file input then add the form attribute enctype="multipart/form-data" according to RFC-7578. you can also see the uses http://www.w3schools.com/tags/att_form_enctype.asp.
Then move to the html part again. Suppose you have a form input like
<form action="some_domain/example.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="fileId"/>
<input type="text" name="firstName" id="name">
<button onclick="post('some_domain/example.php')" type="button">Save</button>
</form>
Now post the file data using ajax:
function post(url){
$.ajax({
url:url,
type: 'POST',
processData:false,
contentType:false,
data: $('#fileId')[0].files[0],
success: function (data) {
alert("successfully posted.");
}
});
}
I think this should be worked fine.
UPDATE:
if you want to post text data as well then you should use FormData object.
function post(url){
var formData = new FormData();
var files = document.getElementById("fileId").files;
for (var i = 0; i < files.length; i++) {
var file = files[i];
formData.append('files[]', file, file.name);
}
formData.append('firstName',$('#name').val());
$.ajax({
url:url,
type: 'POST',
processData:false,
contentType:false,
data: formData,
success: function (data) {
alert("successfully posted.");
}
});
}

How do I use AJAX to print out data inside a div?

I have two files. One file is named index.php and another file is named process.php.
I have a form that submits to process.php in index.php:
<form class="form" action="process.php" method="POST" name="checkaddress" id="checkaddress">
<table>
<tr class="element">
<td><label>Address</label></td>
<td class="input"><input type="text" name="address" /></td>
</tr>
</table>
<input type="submit" id="submit" value="Submit"/>
</form>
<div class="done"></div>
I also have a process in process.php to echo some data based off of the input. How would I be able to use AJAX to submit the form without leaving the page?
Is it something like:
$.ajax({
url: "process.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
$('.done').fadeIn('slow');
}
});
What page would I put the above code on if it was right?
Also, how do I change the above code to say what the process.php outputted? For example, if I echo "Hello" on process.php, how do I make it say it in the done div?
I have seen many responses regarding AJAX, but they all rely on data that is pre-made like APIs. I need to do a database query and fetch the data dependent on the address entered and print the data out.
You need to collect the data in the form so that you can submit them to the process page, and you need to run your code when submitting the form (and cancel the default form submission)
$('#checkaddress').on('submit', function(e){
// get formdata in a variable that is passed to the ajax request
var dataToPassToAjax = $(this).serialize();
$.ajax({
url: "process.php",
type: "GET",
data: dataToPassToAjax,
cache: false,
success: function (resultHtml) {
// add the returned data to the .done element
$('.done').html( resultHtml ).fadeIn('slow');
}
});
// cancel the default form submit
return false;
});
[update]
If you want to modify the data before submitting them, you will have to manually create the parameters to pass to the ajax
$('#checkaddress').on('submit', function(e){
// get formdata in a variable that is passed to the ajax request
var dataToPassToAjax = {};
var address = $('input[name="address"]', this).val();
// alter address here
address = 'something else';
dataToPassToAjax.address = address;
$.ajax({
url: "process.php",
type: "GET",
data: dataToPassToAjax,
cache: false,
success: function (resultHtml ) {
// add the returned data to the .done element
$('.done').html(resultHtml ).fadeIn('slow');
}
});
// cancel the default form submit
return false;
});
You could use the jQuery form plugin: http://jquery.malsup.com/form/
Let me know if you want example code.

loading a element of same file through jquery

I have a file data.php, when a user clicks update the database is updated in background with jquery but in response i want to reload the particular table whose data was updated.
my html:
<div id="divContainer">
<table id="tableContainer" cellspacing='0' cellpadding='5' border='0'>
<tr>
<td>No.</td>
<td>Username</td>
<td>Password</td>
<td>Usage Left</td>
<td>%</td>
</tr><!-- Multiple rows with different data (This is head of table) -->
my jquery:
$('#UpdateAll').click(function() {
$.ajax({
type: 'post',
url: 'update.php',
data: 'action=updateAll',
success: function(response) {
$('#response').fadeOut('500').empty().fadeIn('500').append(response);
$('<div id="divContainer" />').slideUp('500').empty().load('data.php #tableContainer', function() {
$(this).hide().appendTo('#divContainer').slideDown('1000');
});
}
});
});
Everything is working fine the database is getting updated and in success #response is getting loaded with success message but the table is not refreshing.
You already have a div with an id of divContainer but you are creating this element again
$('<div id="divContainer " />').slideUp....
you need
$('#divContainer')
.slideUp('500')
.empty()
.load('data.php #tableContainer', function() {
$(this).slideDown('1000');
});
$('#UpdateAll').click(function () {
$.ajax({
type: 'post',
url: 'update.php',
data: 'action=updateAll',
success: function (response) {
$('#response').fadeOut('500').empty().fadeIn('500').append(response);
$('#divContainer').slideUp('1000').load('data.php #tableContainer', function () {
$(this).hide().appendTo('#tableContainer').slideDown('1000');
});
}
});
});

Categories