Submiting only one form with AJAX - javascript

I have several forms in my html view (they displayed by php foreach).
Form example:
<form method="POST" class="like-form-js">
<input type="hidden" name="post_id" value="<?= $post['id'] ?>">
<input type="hidden" name="user_id" value=<?= CoreController::findIndentityId(); ?>">
<i class="far fa-thumbs-up color-grey c-pointer submit-like"></i>
</form>
I have many such forms in my view. My js:
$('.submit-like').click( function() {
$.ajax({
url: 'some-url',
type: 'post',
dataType: 'json',
data: $('.like-form-js').serialize(),
success: function(data) {
console.log('success');
}
});
});
I need to submit only one form on which i clicked, but this forms have similar class and they are all submiting. How to solve this?

You have to specify which form to be submitted
Try this,
$('.submit-like').click(function(){
$(this).parent().submit()
})
$('like-form-js').submit(function(e){
e.preventDefault();
$.ajax({
url: 'some-url',
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function(data) {
console.log('success');
}
});
})

Related

file and form upload with ajax and jquery

How I to for send an image and form with a request ajax?
HTML
<input type="text" class="form-control" id="Name"/>
<input type="file" name="imgClient" class="form-control" id="UploadIMG"/>
</form>
<button id="btnSave">Save</button>
JQuery - AJAX
$("#btnSave").click(function()
{
var Url = 'http://localhost/systemm/public/painel/client';
var Dados = $('#FormClient').serialize();
$.ajax({
type:Type,
url: Url,
dataType: 'JSON',
data: Dados,
success:function(data){
if($.isEmptyObject(data.error))
location.reload();
else
printErrorMsg(data.error);
},
error:function(e){
alert('Ocorreu um erro !');
console.log(e);
},
});
});
When I serialize the data and put in an alert to display I see that the image is not there, how do I send the image along with my form to my server/controller?
Use formData object:
HTML
<form enctype="multipart/form-data">
<input type="text" class="form-control" id="Name" name="Name"/>
<input type="file" name="imgClient" class="form-control" id="UploadIMG"/>
<button id="btnSave">Save</button>
</form>
JS
$("#btnSave").click(function() {
var Url = 'http://localhost/systemm/public/painel/client';
var formData = new FormData(this.form);
$.ajax({
type:'post',
url: Url,
dataType: 'JSON',
data: formData,
...
});
});
Let's try following,
<form id="POST_FORM" method="post" enctype="multipart/form-data" >
<input type="text" class="form-control" id="Name"/>
<input type="file" name="imgClient" class="form-control" id="UploadIMG"/>
<button type="submit" id="btnSave">Save</button>
</form>
$("#POST_FORM").submit(function(){
var data = new FormData(this);
addPOST(data);
return false;
});
function addPOST(formData){
$.ajax({
type:'POST',
url: Url,
data:formData,
dataType:"json",
cache:false,
contentType: false,
processData: false,
success:function(response){
},
error: function(data){
console.log("error");
console.log(data);
}
});
}
Try to change content dataType. Set dataType='false'
$.ajax({
type:Type,
url: Url,
dataType: false,
data: Dados,
success:function(data){
if($.isEmptyObject(data.error))
location.reload();
else
printErrorMsg(data.error);
},
error:function(e){
alert('Ocorreu um erro !');
console.log(e);
},
});
Hope this helps
This is the way i have done it.
var obj = document.getElementById('my_form_id')
var data = new FormData(obj);
$.ajax({
type: 'post',
url: $(obj).parent().attr('action'),
processData: false,
contentType: false,
data: data,
success: function(result){
profile_app.user.foto_url = result.url
},
error: function(error){
console.log("error");
}
});

jQuery Ajax Submit Post not getting success message back

The code works on until I reach the action.php where I post my input. The issue is that the Post never reaches the action.php and all I get is a blank variable.
using: https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js
<script type="text/javascript">
function submitdata()
{
var name=document.getElementById('name');
$.ajax({
type: 'post',
url: 'action.php',
data: {
'name':name
},
cache:false,
success: function (data) {
$('#msg').html(data);
}
});
return false;
}
</script>
<form onsubmit="return submitdata();">
<input type="text" name="name">
<input type="submit" value="Check">
</form>
<p id="msg"></p>
action.php:
<?php
$name=$_POST['name'];
echo "Response: ".$name;
?>
EDIT:
Fixed it by adding:
var name=document.getElementById('name').value;
and
input type="text" id="name" instead of name="name"
Your "name" is DOM object. To get value use:
var name=document.getElementById('name').value;
You now submit not a string, but Object and this may be the reason why it fails.
Try to add the dataType on your ajax request
make it 'text'
$.ajax({
type: 'post',
url: 'action.php',
dataType: 'text',
data: {
'name':name
},
cache:false,
success: function (data) {
$('#msg').html(data);
}
});

How to submit checkbox through jquery ajax?

I have difficulty submitting this form:
<form action="/someurl" method="post">
<input type="hidden" name="token" value="7mLw36HxPTlt4gapxLUKWOpe1GsqA0I5">
<input type="checkbox" class="mychoice" name="name" value="apple"> Apple
<input type="checkbox" class="mychoice" name="name" value="orange"> Orange
<input type="checkbox" class="mychoice" name="name" value="pear"> Pear
</form>
And the jquery bit:
$('.mychoice').click( function() {
$.ajax({
url: '/someurl',
type: 'post',
dataType: 'json',
success: function(data) {
// ... do something with the data...
}
});
});
But nothing happens when I click a checkbox. How can I fix this?
UPDATE: It may worth mentioning that the form is located at a bootstrap modal.
You're missing the data property.
See: JQuery $.ajax() post - data in a java servlet for an example.
If you want to send the contents of the form, then you would use Form.serialize(), but you could put whatever data you want into the property.
$(document).ready(function() {
$('.mychoice').click(function() {
var formData = $('#myForm').serialize();
console.log('Posting the following: ', formData);
$.ajax({
url: '/someurl',
data: formData,
type: 'post',
dataType: 'json',
success: function(data) {
// ... do something with the data...
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="/someurl" method="post" id="myForm">
<input type="hidden" name="token" value="7mLw36HxPTlt4gapxLUKWOpe1GsqA0I5">
<input type="checkbox" class="mychoice" name="name" value="apple">Apple
<input type="checkbox" class="mychoice" name="name" value="orange">Orange
<input type="checkbox" class="mychoice" name="name" value="pear">Pear
</form>
Try this:
$(document).ready(function(){
$('.mychoice').change( function() {
$.ajax({
url: '/someurl',
type: 'post',
dataType: 'json',
success: function(data) {
// ... do something with the data...
}
});
});
});
supply missing data
$(document).ready(function() {
$('.mychoice').click(function() {
$.ajax({
url: '/someurl',
data: $(this).closest('form').serialize(),
type: 'post',
dataType: 'json',
success: function(data) {
// ... do something with the data...
}
});
});
});
if you are trying to receive the data with the csrf token do as below :
var fd = new FormData()
fd.append('csrfmiddlewaretoken', document.getElementsByName('csrfmiddlewaretoken')[0].value)
fd.append('field_name', $("input[name='field_name']").serialize())
will return
['field_name=9&field_name=15&field_name=10']
you will then have to parse the info in your view ( django )
Try 'change' instead of 'click', like this:
$('.mychoice').change(function(){...})

Inserting into Mysql form php with Ajax without reload page

I have this jQuery AJAX code that into Mysql form php. It works without reloading the page. The problem is that it When the user enters something into the form, then clicks submit, I would like to use php and ajax (with jquery). But it do not print the string in alert() . Can someone please show me how this can be achieved?
HTML :
<form id="students" method="post">
<div class="row">
<input name="a[]" value="" type="text" >
<input name="b[]" value="" type="text" >
</div>
<div class="row">
<input name="a[]" value="" type="text" >
<input name="b[]" value="" type="text" >
</div>
<input type="submit" value="submit" id="submitbutton" class="insert"/>
</form>
<script type="text/javascript">
$('#students').submit(function(){
event.preventDefault();
$.ajax({
type: 'POST',
url: 'ajax_insert.php',
data: $('#students').serialize(),
dataType: 'JSON',
success: function(data) {
alert('form has been posted successfully');
}
});
});
</script>
and ajax_insert.php :
$a1=$_POST['a'];
$b1=$_POST['b'];
//$query_values = array();
$index=0;
foreach($a1 as $s){
$sql = "INSERT INTO test_data(a,b) VALUES('$s','".$b1[$index]."')";
$result = mysql_query($sql);
if($result)
{
echo "1";
}
$index++;
}
$('#students').submit(function(event){
event.preventDefault();
$.ajax({
type: 'POST',
url: 'ajax_insert.php',
data: $('#students').serialize(),
dataType: 'JSON',
success: function(data) {
alert('form has been posted successfully');
}
});
check official document here and learn how to use event.preventDefault();
You probably have to event.preventDefault(); in the submit event callback :
$('#students').submit(function(){
event.preventDefault();
$.ajax({
type: 'POST',
url: 'ajax_insert.php',
data: $('#students').serialize(),
dataType: 'JSON',
success: function(data) {
alert('form has been posted successfully');
}
});
});
You need return valid json when use dataType: "json" in $.ajax call
Or you can use dataType: "html" without rewriting php code
Update (examples of code, that should work):
in HTML:
<script type="text/javascript">
$('#students').submit(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'ajax_insert.php',
data: $('#students').serialize(),
dataType: 'JSON',
success: function(data) {
if(data.result == 1) {
alert('form has been posted successfully');
} else {
alert(data.error);
}
}
});
});
</script>
ajax_insert.php
$a1=$_POST['a'];
$b1=$_POST['b'];
//$query_values = array();
$index=0;
$errors = array();
foreach($a1 as $s){
$sql = "INSERT INTO test_data(a,b) VALUES('$s','".$b1[$index]."')";
$result = mysql_query($sql);
if(!$result)
{
$errors[] = "\"$sql\"";
}
$index++;
}
if(!empty($errors)) {
echo json_encode(array('result'=>0,'error'=>"Error executing following queries: \n".implode("\n", $errors)));
} else {
echo json_encode(array('result'=>1));
}

Uploading data and files in one form using Ajax PHP?

I'm using jQuery and Ajax for my forms to submit data and files but I'm not sure how to send both data and files in one form?
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
I was planning to use FormData as below
var formData = new FormData($(this)[0]);
but figured out that it does not work in IE<10 and which is not accepted. Is there any other approach for same?
This block should work for you.
$.ajax({
url: 'url',
type: 'POST',
async: true,
dataType: "json",
data: $('#data').serializeArray(),
error: function (a, b, c) { onError(a, b, c, parameters); },
success: function (data) { onSuccess(data, parameters); }
});
You can do like this in php instead of using form data,
Serialize you form data and send through ajax, like,
$.ajax({
type: 'post',
url: 'post.php',
data: $('#form').serialize(),
success: function () {
}
});
});
using $('#form').serialize() you can send your all form data to php.
I hope it helps,
function savedata(){
var vacancy_desc = CKEDITOR.instances['vacancy_desc'].getData();
var file_data = $('#fileupload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('vacancy_records',vacancy_records);
form_data.append('vacancy_desc',vacancy_desc);
$.ajax({
url:pathname,
method:"POST",
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data:form_data,
cache:false,
success:function(datas){
alert('Updated successfully !');
return false;
}
});
}

Categories

Resources