i'm trying to post a form containing an input text, a textarea, and 14 checkbox with ajax. The idea is to insert some data according to the number of checked checkbox into table dbdata.
Here is the script.js :
$(document).on('click', '#save', function(event) {
//action
var url = "aksi.php";
//an input text
var v_id = $('input:text[name=id]').val();
//a textarea
var v_note = $('#note').val();
//some checkboxes
var v_checkbox =[]
$("input[name='checkbox[]']:checked").each(function ()
{
v_checkbox.push(parseInt($(this).val()));
});
//ajax
$.ajax({
url: url,
type: "POST",
data: {id: v_id,note: v_note,checkbox:v_checkbox },
success: function (data, status){
alert("success!")
},
error: function(xhr,err){
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
});
This is the aksi.php :
require "../../config/db.php";
$id=$_POST['id'];
$checkbox= $_POST['checkbox'];
$note=$_POST['note'];
foreach ($checkbox as $key => $check_box) {
mysqli_query($con,"INSERT INTO dbdata(id, checkbox, note) VALUES($id, $check_box, '$note')");
}
The problem is the data never posted. The ajax thrown error (readyState=0, status=0) and data not inserted. The url also changed to :
index.php?checkbox[]=3&checkbox[]=4&checkbox[]=5
depend on which checkbox are checked. Any idea?
Can you put one echo statement at the last in php file for resolving the error issue. like
echo 1;
Update the first line like this if save is the submit button:
$(document).on('click', '#save', function(event) {
event.preventDefault();
.....
});
For resolving the db insertion issue, try include the full path of the required file instead of relative path.
Related
I would like to validate a form with an AJAX request to the server and then swap the form html in the web browser with the form html from the server because this would be an easy implementation in theory. It is proving a nightmare though because the change event is triggered without the user interacting further after the first interaction which triggered the first change event. Consequently an infinite loop of AJAX requests to the server is happening.
The html form sits inside a div which has classes 'container mb-4'. This is the JS code -
var _cont = $('.container.mb-4')
var _form = $('.custom-form')
function ajax_validation(form) {
form.on('change', 'input, select, textarea', function() {
form_data = form.serialize()
$.ajax({
url: "/form/6/",
type: "POST",
data: form_data,
success: function(data) {
if(!(data['success'])) {
_cont.empty()
_cont.append(data['form_html'])
form = _cont.find('form')
ajax_validation(form)
}
},
error: function () {
form.find('.error-message').show()
}
});
})
}
ajax_validation(_form)
The change event I am assuming is triggered because the server returns a form input field with a different csrf token as the value to the previous input field - all other fields are the same. So an obvious solution would be to keep the same csrf token. But I want to understand why the JS code isn't working. I thought destroying the form would destroy the change event bound to it. So am at a loss to explain this infinite loop. How do I change this so I can just swap the form and not trigger another change event until the user really does change something?
It's not a good thing to use events in function no need to do that
Also your event here for input , select , textarea for serialize you need to select the closest() form
Try the next code
var _cont = $('.container.mb-4');
var _form = $('.custom-form');
_cont.on('change', 'form input,form select,form textarea', function() {
var ThisForm = $(this).closest('form');
var form_data = ThisForm.serialize();
$.ajax({
url: "/form/6/",
type: "POST",
data: form_data,
success: function(data) {
if(!(data['success'])) {
_cont.html(data['form_html']);
}
},
error: function () {
ThisForm.find('.error-message').show()
}
});
});
And logically if(!(data['success'])) { should be if(data['success']) {
First let's understand the issue that you have. You have a function called ajax_validation that is defining a change event on the form's elements which, on response will call ajax_validation. So, if any change happens on your elements, then a new request is sent to the server. So, if any value is changed, like a token, the request will be sent again. You could use a semaphore, like this:
var semaphore = true;
function ajax_validation(form) {
form.on('change', 'input, select, textarea', function() {
if (!semaphore) return;
semaphore = false;
form_data = form.serialize()
$.ajax({
url: "/form/6/",
type: "POST",
data: form_data,
success: function(data) {
if(!(data['success'])) {
_cont.empty()
_cont.append(data['form_html'])
form = _cont.find('form')
ajax_validation(form)
}
semaphore = true;
},
error: function () {
form.find('.error-message').show()
}
});
})
}
Something like this should solve your issue for the time being, but you should consider refactoring your code, because what you experience is well-known and is called callback hell.
Turns out the password field was coming back blank from the server - this django must do out of the box if the PasswordInput widget is used. So the form is replaced with a new form which lacks the password input from the before. The browser was then applying the autofill password value to the form which was triggering the change event.
This is my code now. It checks that the form_data about to be sent for validation really is different to before minus the csrf token which will be different.
It is based on Mohamed's answer -
var _cont = $('.container.mb-4');
var _form = $('.custom-form');
var prev_data = undefined
_cont.on('change', 'form input,form select,form textarea', function() {
var ThisForm = $(this).closest('form');
var form_data_wo_csrf = ThisForm.find("input, textarea, select").not("input[type='hidden']").serialize()
if(form_data_wo_csrf == prev_data) {
return
}
var form_data = ThisForm.serialize()
$.ajax({
url: "/form/6/",
type: "POST",
data: form_data,
success: function(data) {
if(!(data['success'])) {
_cont.html(data['form_html']);
prev_data = form_data_wo_csrf
}
},
error: function () {
ThisForm.find('.error-message').show()
}
});
});
I am adding a text area on click of a particular div. It has <form> with textarea. I want to send the jquery variable to my php page when this submit button is pressed. How can this be achievable. I am confused alot with this . Being new to jquery dizzes me for now. Here is my code,
`
<script type="text/javascript">
$(document).ready(function(){
$('.click_notes').on('click',function(){
var tid = $(this).data('question-id');
$(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'><textarea cols ='50' class='span10' name='notes' rows='6'></textarea><br><input class='btn btn-primary' name= 'submit_notes' type='submit' value='Add Notes'><input type='hidden' name='submitValue' value='"+tid+"' /></form><br></div>");
});
});
</script>`
Your code works fine in the fiddle I created here -> https://jsfiddle.net/xe2Lhkpc/
use the name of the inputs as key of $_POST array to get their values.
if(isset($_POST['submitValue'])) { $qid = $_POST['submitValue']; }
if(isset($_POST['notes'])) { $notes = $_POST['notes']; }
You should send your data after form submitted, something like this
:
$(".comment_form form").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
you can assign event after insert your form.
// handling with the promise
$(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'></form><br></div>").promise().done(function () {
// your ajax call
});;
I have an AJAX call, as below. This posts data from a form to JSON. I then take the values and put them back into the div called response so as to not refresh the page.
$("form").on("submit", function(event) { $targetElement = $('#response'); event.preventDefault(); // Perform ajax call // console.log("Sending data: " + $(this).serialize()); $.ajax({
url: '/OAH',
data: $('form').serialize(),
datatype: 'json',
type: 'POST',
success: function(response) {
// Success handler
var TableTing = response["table"];
$("#RearPillarNS").empty();
$("#RearPillarNS").append("Rear Pillar Assembly Part No: " + response["RearPillarNS"]);
$("#TableThing").empty();
$("#TableThing").append(TableTing);
for (key in response) {
if (key == 'myList') {
// Add the new elements from 'myList' to the form
$targetElement.empty();
select = $('<select id="mySelect" class="form-control" onchange="myFunction()"></select>');
response[key].forEach(function(item) {
select.append($('<option>').text(item));
});
$targetElement.html(select);
} else {
// Update existing controls to those of the response.
$(':input[name="' + key + '"]').val(response[key]);
}
}
return myFunction()
// End handler
}
// Proceed with normal submission or new ajax call }) });
This generates a new <select id="mySelect">
I need to now extract the value that has been selected by the newly generated select and amend my JSON array. Again, without refreshing the page.
I was thinking of doing this via a button called CreateDrawing
The JS function for this would be:
> $(function() {
$('a#CreateDrawing').bind('click', function() {
$.getJSON('/Printit',
function(data) {
//do nothing
});
return false;
});
});
This is because I will be using the data from the JSON array in a Python function, via Flask that'll be using the value from the select.
My question is, what is the best way (if someone could do a working example too that'd help me A LOT) to get the value from the select as above, and bring into Python Flask/JSON.
I have an AJAX post method that works in two places both on "Ladder" page, but not another, a "matches" page. This method sets posts the "player ID" which php picks up and sets a session variable
$("form .singles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Working page form:
<form><button type='submit' id='playerInfo' class='singles-player-name' name='viewPlayer' value='",$sglsPlayerID,"'>", $curSGLSRankLName, ", ", $curSGLSRankFName, "</button></form>
Sets session variable
if (!empty($_POST['viewPlayerID'])){
$viewPlayer = isset($_POST['viewPlayerID']) ? $_POST['viewPlayerID'] : 'No data found';
$viewPlayerSql = "SELECT * FROM `PLAYERS` WHERE `ID` LIKE '".$viewPlayer."'";
$viewPlayerQuery = #$conn->query($viewPlayerSql);
$viewPlayerRow=mysqli_fetch_assoc($viewPlayerQuery);
$_SESSION['playerID'] = $viewPlayerRow["ID"];
echo "", $_SESSION['playerID'],"";}
Second working version that lives on the same page as the first but is for doubles players:
$("form .doubles-player-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
//console.log(data);
window.location.href = "Player";
});
});
Form for that ajax method:
<form><button type='submit' id='playerInfo' class='doubles-player-name' name='viewPlayer' value='",$dblsPlayerID,"'>", $curDBLSRankLName, ", ", $curDBLSRankFName, "</button></form>
Then on complete, the ajax methods redirect to the player page and pulls up that players info on that page (ex. https://urlexample.com/Player). This part, from this point-up, works! However, I have another page, the "Matches" page, where I want it to do the same exact thing, and set that session variable, then redirect to the player page, so I have this method below. But for some reason, this one does not work:
$("form .singlesMatch-player1-name").click(function (evt) {
evt.preventDefault();
var viewPlayer = $(this).val();
console.log(viewPlayer);
$.ajax({
url: '',
type: 'POST',
data: {
viewPlayerID: viewPlayer
}
}).done(function (data) {
console.log("Success");
console.log(data);
window.location.href = "Player";
});
});
Not working form:
<form><button type='submit' id='playerInfo' class='singlesMatch-player1-name' name='viewPlayer' value='",$sglsPlayer1ID,"'>", $P1LN, ", ", $P1FN, "</button></form>
For some reason, all this second method does is post it to the URL (ex. https://urlexample.com/WeeklyMatchUps?viewPlayer=1) instead of setting the session variable and redirecting to the player page (ex. https://urlexample.com/Player). All thats different between the 2 is the class name of the button.
$sglsPlayer1ID should probably be $sglsPlayerID.
Also, try adding a success and error condition to your AJAX conditions instead of just using a done operator. This will allow you to dump helpful error codes on a failure to better resolve these kinds of issues in the future.
I had a function being called on the page that was commented out causing an error before jQuery was added in a script at the bottom of the page. removing that function from being called fixed the issue.
S/O to #line88 for the assistance!
I have been trying to solve a simple but, for me, really hard problem.
I have a form and I need to add data from the form to a database, but with form validation. For validation I use the parsley plugin and for some input fields I use select2 plugin.
I try to add form in this way (Comments is in code):
//try to see is zemljiste or vrsta_rada = null to do not add data to database
var zemljiste = $("#parcele").select2("data");
var vrsta_rada = $("#vrsta_rada").select2("data");
//Now when I click on #dodaj I need to chech is zemljiste or vrsta_rada == null to do not start function for adding data but DONT work
$("#dodaj").click(function () {
if (zemljiste == null || vrsta_rada == null) {
alert('PLEASE fill the fields');
} else {
//HERE if zemljiste and vrsta_rada != null start validation and this also dont work
$('#myForm').parsley().subscribe('parsley:form:validate', function (formInstance) {
formInstance.submitEvent.preventDefault(); //stops normal form submit
if (formInstance.isValid() == true) { // check if form valid or not
zemljiste = $("#parcele").select2("data").naziv;
id_parcele = $("#parcele").select2("data").id;
vrsta_rada = $("#vrsta_rada").select2("data").text;
//code for ajax event here
//Here is ajax and when I fill all fields I add data to database but here success and error into ajax dont work???
$.ajax({
url: "insertAkt.php",
type: "POST",
async: true,
data: {
naziv: $("#naziv").val(),
parcele: zemljiste,
vrsta_rada: vrsta_rada,
opis: $("#opis").val(),
pocetak: $("#pocetak").val(),
zavrsetak: $("#zavrsetak").val(),
status: $("#status").val(),
id_parcele: id_parcele,
}, //your form data to post goes here as a json object
dataType: "json",
success: function (data) {
//SO if success I add data but this code below dont work also in error dont work
$('#myModal').modal('hide');
drawVisualization();
console.log('YESSSSSSS');
console.log(data);
},
error: function (data) {
console.log(data);
}
});
}
});
}
});
With this, I have a few problems...
1. When submit code, the page refreshes and I don't want to do that.
2.When I fill in all the fields, I add data to the database but also add all the previous attempts with incorrect information. Why?
3. Why can I not see what return my success and error into .ajax in console.log ???
Look the pictures: