I am having a series of nested Ajax calls to create and update data into the database as well as calling the updated list once data are successfully submitted.
This is how the code works:
(1) A list of transaction is shown when the page is rendered, each row can be edited by the user.
(2) When clicking a specific row, I run an Ajax call to retrive the form filled with the data to be updated
(3) The form is then submitted via Ajax as well.
(4) If successfully submitted it perform another Ajax call to get the table updated.
First problem: when the table is loaded via Ajax the "edit" button is not working anymore.
Second problem: The form displayed to update and to create is the same, except when updating the form is pre-filled. I would like to avoid duplicating the Ajax call but I had to do it otherwise I wasn't able to submit the form after it was loaded from the first Ajax call (pt 1). Is there a way to make a more clean code?
Here it is the javascript code, server side all works just fine:
$(".edit-transaction").click(function () {
// obtain the object id to load the correct form
const object_id = $(this).data('object-id');
// request the form via AJAX Get request
$.ajax({
type: 'GET',
url: "/transaction/",
data: {
'slug': object_id
},
success: function(response) {
// Get the form for the requested object
$("#display-form").html(response.html); // this code retrive the form
$("#transaction-form").submit(function (e) {
// preventing from page reload and default actions
e.preventDefault();
let serializedData = $(this).serialize();
// Update the form via AJAX
$.ajax({
type: 'POST',
url: "/transaction/",
data: serializedData,
success: function (response) {
console.log('updated successfully')
// load the table with the new content updated
$.ajax({
type: 'GET',
url: "/get-transactions-list/",
success: function (data) {
$("#display-transaction-list").html(data.html);
},
});
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
})
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
});
$("#transaction-form").submit(function (e) {
// preventing from page reload and default actions
e.preventDefault();
let serializedData = $(this).serialize();
// Create a new transaction via AJAX
$.ajax({
type: 'POST',
url: "/transaction/",
data: serializedData,
success: function (response) {
console.log('created successfully')
// load the table with the new content updated
$.ajax({
type: 'GET',
url: "/get-transactions-list/",
success: function (data) {
$("#display-transaction-list").html(data.html);
},
});
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
})
Thanks for any help
Since some of the elements are added asynchronously, this means that the event listeners which were added at runtime will not affect those elements. You should instead listen to events on them via "events delegation".
You can also create a custom event for loading the table content. So to update the table, you just .trigger() your custom event. This is useful when you want to implement other functionalities which will need a table update like, delete, etc.
// custom event for loading the table content
$(document).on('load.table', '#display-transaction-list', function () {
const $table = $(this);
$.ajax({
type: 'GET',
url: "/get-transactions-list/",
success: (data) => $table.html(data.html)
});
});
// edit transaction event
$(document).on('click', '.edit-transaction', function () {
// obtain the object id to load the correct form
const object_id = $(this).data('object-id');
// request the form via AJAX Get request
$.ajax({
type: 'GET',
url: "/transaction/",
data: {
'slug': object_id
},
success: function(response) {
// Get the form for the requested object
$("#display-form").html(response.html); // this code retrive the form
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
});
// save transaction event
$(document).on('submit', '#transaction-form', function (e) {
// preventing from page reload and default actions
e.preventDefault();
let serializedData = $(this).serialize();
// Update the form via AJAX
$.ajax({
type: 'POST',
url: "/transaction/",
data: serializedData,
success: function (response) {
// you can add some data to the response
// to differentiate between created and updated. Eg response.actionType
console.log('created or updated successfully')
// load the table with the new content updated
$("#display-transaction-list").trigger('load.table');
},
error: function (response) {
let error = response ["responseJSON"]["error"];
$.each(error, function (code, message) {
alert('message');
});
}
})
})
Related
I have two select elements both using selec2.js, the first select element has drop down options populated from the database, now what I want to do is to choose an option from select element 1, get the value and send that value via ajax to query the database and return matching results and populate the results in the 2nd select element. unfortunately, I haven't succeeded with returning data back from the server, below is my code and oh I am using laravel.
$('#province').on('change', function (e) {
var data = $("#province option:selected").val();
$.ajax({
url: "{{route('list-townships')}}",
type: 'get',
data: {
province_id: data
},
success: function (response) {
console.log(response);
response.filter(function (response) {
if (response) {
//Append data to the 2nd select element
}
})
},
error: function (err) {}
})
});
Okay, I find the issue here, due to laravel CSRF request protection I had forgotten to define the CSRF Token in the ajax header. the complete code is below.
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#province').on('change', function(e) {
var data = $("#province option:selected").val();
console.log(data);
$.ajax({
url: "{{route('list-townships')}}",
type: 'get',
data: {
province_id: data
},
success: function(response) {
console.log(response);
response.filter(function(response) {
if (response) {
var townships = new Option(response.name, response.id, false, false);
$('#township').append(townships).trigger('open');
}
})
},
error: function(err) {}
})
});
});
For a university homework, I have to create a little e-commerce website.
After the login, the user is redirected to the homepage. In this homepage, the client will recive a JSON object from the server (containing some product to be loaded) to generate the DOM of the homepage dynamically.
Note: I must use AJAX and JSON
I have this client.js file:
$(document).ready(function() {
// AJAX request on submit
$("#login_form").submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "submit.php",
data: {
Email: document.getElementById('login_email').value, // Email in the form
Password: document.getElementById('login_password').value // // Password in the form
},
cache: false,
success: function(){
window.location.href = "home.php"; // load the home.php page in the default folder
}
});
});
});
$(document).ready(function() {
// AJAX request to open a channel between php and client
function (e) {
e.preventDefault();
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
var data = JSON.parse(data);
alert(data); // debug
showProducts(data);
});
});
});
});
function showProducts(data){
alert(data);
// Insert object into the page DOM
}
I don't know why, but I can't access after the login if the second Ajax request (the AJAX request to open a channel between php and client) is not commented, and I don't know why, because the code seems right... Any suggestion?
after login action you need to set to cookie token in response
success: function(response){
console.log(response)
// then set to cookie response.token
window.location.href = "home.php";
}
after set token to cookie, you need to send this token to next ajax request url: "queries.php",
You need to wrap your anonymous function in parenthesis and add () at the end if you want to execute it:
(function (e) {
// I don't know why you need this:
e.preventDefault();
// etc.
})();
You should also check the contents of that function as you seem to have too many closing parentheses and you don't need to parse the returned value if you set the dataType to json.
In the end I think this is about all you need for that function:
(function () {
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
})();
or just:
$.ajax({
type: "GET",
url: "queries.php",
dataType: "json",
success: function(data){
console.log(data); // debug
showProducts(data);
}
});
To get it directly on page load.
I have problems to pass the variables to another file, I already realize the code and I do not find the solution, it sends me error in the function
onclick="limit();javascript:AyudaTipos(2)"/>
function
function limit (){
$.ajax({
url: 'Tipos.php',
type: 'POST', // GET or POST
data: {"acreedor":$("#acreedor").val(),"importe2":$("#importe2").val(),
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert(data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Error! Funcion Limite Anual");
}
}
});
}
Resolved:
$(function(){
$('#help').click(function(){
$.ajax({
url: 'Tipos.php',
type: 'POST', // GET or POST
data: {"acreedor":$("#acreedor").val(),"importe2":$("#importe2").val()},
success: function(data) { // data is the response from your php script
// This function is called if your AJAX query was successful
alert(data);
},
error: function() {
// This callback is called if your AJAX query has failed
alert("Error!nuevo");
}
});
});
});
Thank You
I need to call to function onsubmit in codeigniter.
One for submit and one for Access some id.
I like to know that how to call two function on submit, also i need to know how to submit form by ajax if i have true condition.
My ajax controller:
$(document).ready(function(){
add = function (){
$.ajax({
type: "POST",
url: ajax_url_store,
data: {action: 'store', views: JSON.stringify(thsirtDesigner.getProduct()) },
success: function(data) {
if(parseInt(data) > 0) {
// i need to submit my form here...
}
},
error: function() {
//alert('some error has occured...');
},
start: function() {
//alert('ajax has been started...');
}
});
}
});
jquery you can use :
$("#formId").submit(function(e){
e.preventDefault();
//your code
});
And in javascript
<form action="" method="post" onsubmit="return yourfunction()">
</function>
function yourfunction()
{
//your code
return true;
}
It doesn't matter whether you are using codeigniter or normal php simply use Ajax, Check this link
$('input#submitbuttonid').click( function() {
$.ajax({
url: 'url to post data',
type: 'post',
dataType: 'json',
data: $('form#formid').serialize(),
success: function(data) {
...your data logic comes here
}
});
});
And simple Javascript ,
$('form#formid').submit();
you can handle you form submission by jquery. to do this you can use one of jquery plugin for this purpose. i refer JqueryForm plugin to you.
by this plugin you can do something like this:
$.ajax({
type: "POST",
url: ajax_url_store,
data: {action: 'store', views: JSON.stringify(thsirtDesigner.getProduct()) },
success: function(data) {
if(parseInt(data) > 0) {
var options = {
target: '#message_box_id', // target element(s) to be updated with server response
url: url // override for form's 'action' attribute
type: type // 'get' or 'post', override for form's 'method' attribute
dataType: null // 'xml', 'script', or 'json' (expected server response type)
clearForm: true // clear all form fields after successful submit
resetForm: true // reset the form after successful submit
};
// bind form using 'ajaxForm'
$('#your_form_id').ajaxForm(options);
}
},
error: function() {
//alert('some error has occured...');
},
start: function() {
//alert('ajax has been started...');
}
});
i don't know what exactly you want to do but maybe you can use before submit feature of this plugin to solve you issue. for example you can try this way
$(document).ready(function() {
var options = {
target: '#output1',
beforeSubmit: your_ajax_function,
success: showResponse // post-submit callback
url: url // override for form's 'action' attribute
type: type // 'get' or 'post', override for form's 'method' attribute
clearForm: true // clear all form fields after successful submit
resetForm: true // reset the form after successful submit
};
// bind form using 'ajaxForm'
$('#your_form_id').ajaxForm(options);
your_ajax_function = function(){
$.ajax({
// your ajax body
});
}
});
//stop the form from submitting you can select form by adding a class or id
$('form').submit(function(e){e.preventDefault});
//when a button with id submit is clicked
//fire ajax
$('button#submit').on('click',function(){
// your ajax code
});
I'm trying to send some data by Ajax and this data may contain an image.
I don't have any forms, so I can't submit by the traditional way.
This is my HTML:
<input type="file" accept="image/png,image/jpg,image/jpeg,image/bmp" id="addProduct_image">
Whenever the user changes the file I get that value.
var files;
$(document).on('change', '#addProduct_image', function(e){
prepareUpload(e);
});
function prepareUpload(event){
files = event.target.files;
}
When the OK button is pressed I call an ajax function.
$(document).on('click', '#addProduct_OK', function(e){
var img = new FormData();
$.each(files, function(key, value)
{
img.append(key, value);
});
$.ajax({
url: 'responses/product.php?type=productAdd',
type: 'POST',
data: {title: $("#addProduct_title").val(), description: $("#addProduct_description").val(),
image: img, status: $("#addProduct_status").val()
},
success: function(data){
console.log(data);
}
});
});
I'm currently receiving the error on chrome console
Uncaught TypeError: Illegal invocation
in the ajax line. I'm to far away from how to send an image by ajax with other data also?
You need to sent the FormData as the data for the ajax request, so the additional params also has to be appended to the fomdata
$(document).on('click', '#addProduct_OK', function (e) {
var img = new FormData();
$.each(files, function (key, value) {
img.append(key, value);
});
img.append('title', $("#addProduct_title").val());
img.append('description', $("#addProduct_description").val());
img.append('status', $("#addProduct_status").val());
$.ajax({
url: 'responses/product.php?type=productAdd',
type: 'POST',
data: img,
processData: false,
contentType: false,
success: function (data) {
console.log(data);
}
});
});