I want to post form's data to php after the user submit.
The question is that the form is created by jquery in ajax.
The form creating looks like:
$.ajax({
type: "POST",
url: "myphp.php",
data: {label: label},
success: function(result) {
for (i = 0; i<result.item.length; i++){
var itemData= result.item[i].itemData;
var div = $("<div class ='detail'></div>");
// the form will not be displayed, until the parent div has been clicked.
var form = $("<form/>", {// create the form
class: 'itemClass',
id: 'itemId',
method: 'POST'
}).append(
// Create <form> Tag and Appending in Div .detail.
$("<p/>").text("item:"),$("<br/>"),
$("<input/>", {
type: 'text',
id: 'itemData',
name: 'itemData',
value: itemData
}),
$("<br/>"),
$("<input/>", {
type: 'submit',
id: 'submit',
value: 'Submit'
}))
div.append(form);
$("#htmlDiv").append(div);
}
},
dataType: "json",
error: function(xhr){
console.log("error");
}
});
});
However, the submitting code is fail. It is not been executing.
$("#itemId").submit(function(e) {
e.preventDefault();
var itemData= $('#itemData').val();
$.ajax({
type: "POST",
url: "target.php",
data: {itemData: itemData},
success: function(result) {
alert(result); //It return a string
},
dataType: "text",
error: function(xhr){
console.log("error");
}
});
Any idea? Why the submitting can not be used?
Use event-delegation as by the time events are attached($("#itemId").submit(function(e){...), target element($("#itemId")) is not present in the DOM
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
Try this:
$('#htmlDiv').on('submit', '#itemId', function(e) {
e.preventDefault();
var itemData = $('#itemData').val();
$.ajax({
type: "POST",
url: "target.php",
data: {
itemData: itemData
},
success: function(result) {
alert(result); //It return a string
},
dataType: "text",
error: function(xhr) {
console.log("error");
}
});
});
Related
I'm trying to figure out the proper way to refetch one single event (when I add an event and when I update an event)
I'm currently using calendar.refetchEvents(); which will refetch all the events after adding/updating an event but it would be better if I could only refetch that single event.
I use events as a function like so
eventSources: [
{
events:function(fetchinfo, successCallback, failureCallback) {
$.ajax({
type:'GET',
url: '/rdv/data',
data:{
start:moment(fetchinfo.start).format('YYYY-MM-DD HH:mm'),
end:moment(fetchinfo.end).format('YYYY-MM-DD HH:mm'),
},
success: function(data) {
let arrayEvents = [];
$.each(data, function (key) {
arrayEvents.push( {
title: "title",
start: data[key].date_debut_rdv,
end: data[key].date_fin_rdv,
extendedProps: {
id: data[key].id,
nom_client: data[key].animal.client.nom_client,
prenom_client: data[key].animal.client.prenom_client,
id_client: data[key].animal.client.id,
nom_animal: data[key].animal.nom_animal,
},
});
});
successCallback(arrayEvents);
},
error: function(data){
//
}
})
}
}
]
Add an event inside a dateClick
$.ajax({
type: "POST",
url: "/rdvs/ajoutRdv",
data: {
_token: "{{ csrf_token() }}",
client_id: client_id,
animal_id: animal_id,
date_debut_rdv: date_debut_rdv,
statut_rdv_id: statut_rdv_id,
prestations: prestations,
tvas: tvas,
supplements: supplements,
},
success: function () {
calendar.refetchEvents();
$('#modalEditRdv').modal('hide');
},
error: function(data) {
//
});
}
})
Update an event inside an eventClick
$.ajax({
type: "POST",
url: "/rdvs/click/"+id,
data: {
_token: "{{ csrf_token() }}",
rdv_id: event.event.extendedProps.id,
client_id: client_id,
animal_id: animal_id,
date_debut_rdv: date_debut_rdv,
statut_rdv_id: statut_rdv_id,
prestations: prestations,
tvas: tvas,
supplements: supplements,
},
success: function (data) {
calendar.refetchEvents();
//I could do something like this without making a request to the server
//but is there another way ?
//event.event.setExtendedProp("nom_animal", data[0].nom_animal);
//event.event.setStart(data[1]);
//event.event.setEnd(data[2]);
$('#modalEditRdv').modal('hide');
},
error: function(data) {
//
}
})
I see there is EventSource::refetch but it would refetch all the events as well if I'm correct ?
A little help would be very appreciated,
Thank you !
I've a website with the post, and when an user comment its I send an Ajax request.
$(document).on('submit', '.theFormComment', function(e){
var data_to_send = $(this).serializeArray(); // convert form to array
data_to_send.push({name: "cs_spotale", value: $.cookie("c_spotale") });
$.ajax({
type: "POST",
url: '/post/addComment',
data: $.param(data_to_send),
dataType: 'json',
success: function(data){
console.log(data);
if(data.user_id !== data.user_to_id) {
$.ajax({
type: "POST",
url: "/notification/addNotification",
data: {
post_id: data.the_post,
user_from_id: data.user_id,
user_to_id: data.user_to_id,
action: data.action,
cs_spotale: $.cookie("c_spotale")
},
dataType: 'json',
success: function(x){
socket.emit('sendNotification', {data: data, type: x.type, image: x.image});
},
error: function(){}
});
}
$('#comment-box-'+ data.the_post).val('');
$("input[id='csrf_prot']").val(data.c);
$(data.html).prependTo("#comment-" + data.the_post);
if(data.own !== data.username){
socket.emit('notify', data.own, data.username);
}
socket.emit('updateComment', {permaRoom: data.the_post, html: data.html});
},
error: function(data){
console.log(data);
}
});
e.preventDefault();
return false;
});
I saw that if I change the input value of my hidden field "post_id", the comment goes to another "post_id". There is a way to prevent this problem? Or any other idea?
I'm using the following code to submit multiple forms via AJAX:
var formData = $(this).closest('.bookroom1, .bookroom2, .bookroom3, .bookroom4, .bookroom5').serializeArray();
formData.push({ name: this.name, value: this.value });
$.ajax({
type: 'POST',
url: AJAX_URL,
data: formData,
dataType: 'json',
success: function(response) {
if (response.status == 'success') {
$('.bookroom1, .bookroom2, .bookroom3, .bookroom4, .bookroom5')[0].reset();
}
$('.booking-main').html(response.content);
$('.booking-side-response').html(response.sidebar);
}
});
I want to add some JavaScript in the success/response function but only for a particular form e.g.
if ( .bookroom5 ) {
// do stuff
}
Does anyone know the best approach to doing this other than creating separate $.ajax functions for each form?
Any help much appreciated!
var $form = $(this).closest('.bookroom1, .bookroom2, .bookroom3, .bookroom4, .bookroom5');
var formData = $form.serializeArray();
formData.push({
name: this.name,
value: this.value
});
$.ajax({
type: 'POST',
url: AJAX_URL,
data: formData,
dataType: 'json',
success: function (response) {
if ($form.hasClass('bookroom5')) {
alert('you have used form bookroom5')
}
}
});
Save the form before then use it later to check the class
Statement below I had used before to focus on 1st element in a form, and it works very well.
$('form:first *:input[type!=hidden]:first').focus();
But now the problem is when I use it in a form that was empty(without any input element), and I create the elements inside that form by using jQuery .html() after some work, it will not focus on any element.
This is my form:
<form id="edit_marks" method="post">
<div id="display">
</div>
</form>
This is my jQuery AJAX:
function getData()
{
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax(
{
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {Semester:Semester, StudentID:StudentID},
dataType: 'text',
success: function(data)
{
$('#display').html(data);
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
}
getData();
$('form:first *:input[type!=hidden]:first').focus();
You are triggering the event before you are adding the form, so you need to trigger event after form get added. Add it inside ajax success. Since ajax is asynchronous it may complete at any time, so before completing it will return from the function.
function getData()
{
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax(
{
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {Semester:Semester, StudentID:StudentID},
dataType: 'text',
success: function(data)
{
$('#display').html(data);
$('form:first *:input[type!=hidden]:first').focus();
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
}
getData();
Move the focus code inside the AJAX success, because AJAX means it is asynchronous call. So in order to make focus work after AJAX is to add it in the success.
function getData() {
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax({
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {
Semester:Semester,
StudentID:StudentID
},
dataType: 'text',
success: function(data) {
$('#display').html(data);
$('form:first *:input[type!=hidden]:first').focus();
},
error: function(ts) {
alert("AJAX Error: \n" + ts.responseText);
}
});
}
getData();
UPDATE: The code if working I has some css issues.
I'm trying to put ajax data into facebox modal box, I have the following code but facebox modal box is not loading. Looking into firebug ajax is returning the correct data but i do not know how to pass that data to facebox.
$('a[rel*=facebox]').live("click", function() {
var ajaxpostID=$(this).parent().attr("id"); //Get entry ID
$.ajax({
url: 'http://www.someurl.com/ajax/facebox-ajax.php',
type: "POST",
data: ({
ajaxpostID: ajaxpostID
}),
success: function(data) {
$.facebox(data);
},
error: function() {
$.facebox('There was an error.');
}
});
});
Something like this worked for me:
//added some id to anchor tag and
$('a[id='some_anchor_id']').live("click", function() {
var ajaxpostID=$(this).parent().attr("id"); //Get entry ID
jQuery.facebox(function() {
var form_data = {
ajaxpostID: ajaxpostID
};
$.ajax({
url: "http://www.someurl.com/ajax/facebox-ajax.php",
type: 'POST',
data: form_data,
success: function(data) {
jQuery.facebox(data);
},
error: function() {
$.facebox('There was an error.');
}
)
});
})
})
Hope it works for you