Not able to set form attribute value after post it - javascript

I've the form and it looks like :
<form method="POST" action="create.php" data-id="0" class="postForm">
<input type="hidden" id="#formId" value="1">
<textarea class="formBodyText"></textarea>
<button type="submit">Post</button>
</form>
The ajax call for this form is as :
$(document).on("submit",".postFrom",function(event){
event.preventDefault();
$.post("create.php",{'formId':$("#formId").val(),'formBodyText':$(this).find('.formBodyText').val()},function(data)
{
console.log("Return : "+data); //working fine , I mean getting expected result
$(this).attr("data-id",data); // want to set the return data as form data-id attribute value
});
});
the problem is with $(this).attr("data-id",data); , it's not setting the new value for the form.
what wrong with this code??

Try,
$(document).on("submit",".postFrom",function(event){
event.preventDefault();
var cache = $(this); // get the form object here and use that inside of $.post
$.post("create.php",
{'formId':$("#formId").val(),
'formBodyText':$(this).find('.formBodyText').val()
},function(data)
{
console.log("Return : "+data); //working fine , I mean getting expected result
cache.attr("data-id",data); // want to set the return data as form data-id attribute value
});
});

this inside the ajax handler does not refer to the submitted form, you can use a closure variable like $form as shown below to fix this.
$(document).on("submit", ".postFrom", function (event) {
event.preventDefault();
var $form = $(this);
$.post("create.php", {
'formId': $("#formId").val(),
'formBodyText': $(this).find('.formBodyText').val()
}, function (data) {
console.log("Return : " + data); //working fine , I mean getting expected result
$form.attr("data-id", data); // want to set the return data as form data-id attribute value
});
});
jQuery.ajax()
The this reference within all callbacks is the object in the context
option passed to $.ajax in the settings; if context is not specified,
this is a reference to the Ajax settings themselves.

Related

How can I query the form that caused ajax call from callback function?

I have several forms on my page with the same structure and classes.
I want to send form data to the server using POST method, and show error message if something went wrong.
So, HTML code for the forms:
<form class="js-form">
<input name="data" type="text" required>
<button type="submit" value="Go">Go Form 1</button>
</form>
<div class="js-alert" style="display:none;">Error Message</div>
<br><br><br>
<form class="js-form">
<input name="data" type="text" required>
<button type="submit" value="Go">Go Form 2</button>
</form>
<div class="js-alert" style="display:none;">Error Message</div>
and the js code:
$(document).ready(function() {
$(".js-form").submit(function(event) {
event.preventDefault();
var data = $(this).find("input[name='data']").val(),
url = "/api/method";
var posting = $.post(url, {data: data});
posting.done(function(res) {
$("input[name='data']").val(''); // empty all inputs in all forms
console.log(res);
});
posting.fail(function(res) {
// here I want to show the alert
// that is next to a form user had interacted with
});
});
I've tried $.proxy and this binding, but the context in posting.fail() is always the same (request context). How could I get to the form context and query closest alert sibling?
You have a few options:
Utilize the event argument to the submit callback (event.target points to the form):
posting.fail(function(res) {
console.log('do something with form', event.target)
});
Capture the context this into a variable outside of your posting.fail callback:
$(document).ready(function() {
$(".js-form").submit(function(event) {
event.preventDefault();
// capture context!
var form = this;
var data = $(this).find("input[name='data']").val(),
url = "/api/method";
var posting = $.post(url, {data: data});
posting.done(function(res) {
$("input[name='data']").val(''); // empty all inputs in all forms
console.log(res);
});
posting.fail(function(res) {
console.log('do something with form', form)
});
});
If you can support ES6, this is much simpler - just use an arrow function:
posting.fail((res) => {
console.log('do something with form', this)
});
You can use $(this) as this will reference the form that was submitted.
However, since the scope of this in your callback will be different you will need to define it outside the callback function.
var that = $(this);
so your code will look like this:
var that = $(this);
//rest of code
posting.fail(function(res) {
$(that).html(res);
});
See complete code snippet below:
$(document).ready(function() {
$(".js-form").submit(function(event) {
var that = $(this); //reference to form submitted on
event.preventDefault();
var data = $(this).find("input[name='data']").val(),
url = "/api/method";
var posting = $.post(url, {
data: data
});
posting.done(function(res) {
$("input[name='data']").val(''); // empty all inputs in all forms
console.log(res);
});
posting.fail(function(res) {
//can now reference the form submitted here
that.html(res);
});
});
You can set the context option of $.ajax() settings to an object, where this should be the same object set at the value for context property within jQuery .then(), .done(), .fail() and other deferred methods. Not sure how code used $.proxy, though that is also an option that can be used.
$.ajax({/* settings, */ context:{} /* set `this` here */})
.then(function() {
// `this` : `this` set at `context`
})
.fail(function() {
// `this` : `this` set at `context`
})

Display value from checkbox in console.log

Well this is probably an easy question but I've been figure this one out. I would like to display the value of a checkbox in the console.log so I can use it to fire a AJAX call. But the values of every checkbox is the same (the first one).
I have spent some time on google and I for what I read there, I should put the checkbox in an array. But I can't seem to get it to work. Here is my code at the moment.
<!-- Custom taxonomy checkboxes -->
<?php
$taxonomy = 'locatie';
$queried_term = get_query_var($taxonomy);
$terms = get_terms($taxonomy, 'slug='.$queried_term);
if ($terms) {
foreach($terms as $term) {
$name = $term->name;
echo "<div class='col-xs-12 col-sm-12 col-md-2 col-lg-2'>
<form id='location'>
<input class='checkIt' type='checkbox' value='".$name."' name='location' id='".$name."_id'> ".$name."
</form>
</div>";
}
}
?>
<!-- /Custom taxonomy checkboxes -->
$('.checkIt').change(function(e) {
var value = $(this).val();
$.post('../wp-content/themes/mysite/includes/search-team-wp.php',{value:value}, function(data){
$('#search_results_team').hide().fadeIn(1100);
$("#search_results_team").html(data);
console.log(value);
});
});
});
Everything works, even the AJAX call, except the console.log output so I can't sent different values trough the AJAX call. Any help would be really nice!
use
var value = $(this).val();
The issue is because you're selecting all .checkIt elements in the selector within the change event. When you call val() on a collection of elements jQuery will only return the value of the first one.
To fix this you only need to get the value of the element that raised the change event. To do that, use the this keyword within the handler:
var value = $(this).val();
Try ajax call as given below,
var value = $(this).val();
$.ajax({
type: "POST",
url:'../wp-content/themes/mysite/includes/search-team.php',
dataType: "json",
data: {
value:value
},
success:function(data){
$('#search_results_team').hide().fadeIn(1100);
$("#search_results_team").html(data);
console.log(value)
}
})
You can use
$('.checkIt').is(':checked')
This will give you the checked box.
Jquery.val() for checkbox always return ... the value you defined, despite of the checked state.
If you want something like when check return value, else return undefined you should do: value = $('.checkIt:checked').val();

Add a dynamic form field after pressing a button

I have a form with a simple button $builder->add('language_switcher', ButtonType::class); which should simply, if pressed, add another field. To do that, I used Symfony's cookbook http://symfony.com/doc/current/form/dynamic_form_modification.html
$builder
->get('language_switcher')
->addEventListener(
FormEvents::POST_SUBMIT,
function () use ($builder, $options) {
$preparedOptions = $this->prepareOptions($options['data']['productCustomizations']);
$builder->add('lang_switcher'), ChoiceType::class, $preparedOptions);
}
);
When now submitting it via AJAX
<script>
var $button = $('#xyz');
$button.click(function() {
var $form = $(this).closest('form');
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
success: function(html) {
console.log(html);
$('#xyz').replaceWith($(html).find('#lang_switcher'));
}
});
});
</script>
I'm getting the error Buttons do not support event listeners. So I tried it out with a hidden field. I added the hidden field to the Form, set the EventListener to it, and added this data to my AJAX request
data[$('#id_of_hidden_field').attr('name')] = 1;
However this did nothing. The example in the cockbook is after submitting a choice field so I don't know how to adapt it to my needs. I couldn't use a SubmitType, because then it would submit the form, right? I just want to have it with a simple button.
The problem is, that, when I do a console.log(html) I don't see the new html element, so it seems like I'm not getting to the EventListener which is weird, because if I dump contents inside the listener I'm getting some data. It just seems like I'm not getting it inside the response
Ok, got it. The problem was that I used the builder inside the POST_SUBMIT event but I had to use a FormInterface. Since I couldn't add it AFTER submit I had to buy the same callback function as in Symfony's cookbook
$formModifier = function (FormInterface $form, $preparedOptions) {
$form->add($this->childIdentifier, ChoiceType::class, $preparedOptions);
};
And then the listener is built like this
$builder
->get('lang_switcher')
->addEventListener(
FormEvents::POST_SUBMIT,
function (FormEvent $event) use ($formModifier, $options) {
$preparedOptions = $this->prepareOptions($options);
$formModifier($event->getForm()->getParent(), $preparedOptions);
}
);
<script type="text/javascript">
function inputBtn(){
var input=document.createElement('input');
input.type="file";
input.name="img[]";
input.multiple="multiple";
//without this next line, you'll get nuthin' on the display
document.getElementById('target_div').appendChild(input);
}
</script>
<button id="ifile" onclick="inputBtn();">create</button>
<form action="test.php" method="post" enctype="multipart/form-data">
<div id="target_div"></div>
<input type="submit">
</form>

POST dynamic HTML table values to jQuery AJAX

I am trying to get all the values present in my dynamic HTML table and POST the values to AJAX.
I have HTML table like this
When i press '+' , I can able to add rows dynamically . When i click save, How to POST array values from this HTML table to AJAX, so that i can meanwhile INSERT those values into MYSQL
I have tried getting the 'text' of each td present in my table
var rows = $("tbody tr",$("#myTable")).map(function() {
return [$("td",this).map(function() {
return this.innerHTML;
}).get()];
}).get();
This is getting me -> <input type="text"> and so on.
you are returning the innerHTML, which is... HTML.
you can get the value of a input element with .val()
how does this work for you?
return $("td input").map(function() {
return $(this).val();
});
Use serialize function using jQuery
<script type="text/javascript">
(function ($) {
$('#formID').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/pathTo/process_form.php',
data: $('#formID').serialize()
});
});
})(jQuery);
</script>
var rows = $("td input",$("#myTable")).map(function() {
return { name : $(this).attr('name'), value :$(this).val()};
});
and you should get :
[
{
name : 'inputname',
value : 'inputval'
},
{ ... }
]
This would return an array like the .serialize() method

How to put alert value to element

in this code i am trying to get the alert value to the element.
brief:
my ajax code checks the database values and gets the new values from database and
displays the fetched values in alert. but i am not able to put that alert values into
element...
How can i do this?
Code:
<script>
$(document).ready(function(){
$("#refresh").click(function(){
var fileId=id;
var rowNum = $(this).parent().parent().index();;
$.ajax({
type:"post",
url:"checkStatusAndNumRecs",
data:{fileId:fileId},
success:function(data)
{
setTimeout(alert(data), 2000);
var allTds = $("#rtable tr:eq('"+rowNum+"')").find('td');
$(allTds)[4].html(data[0]);
$(allTds)[3].html(data[1]);
document.getElementById("#div1").innerHTML=data;
},
error:function(data)
{
document.getElementById("#div1").innerHTML="It was a failure !!!";
}
});
});
});
</script>
HTML code:
<td><div id="div1"><s:property value="%{#m.status}" /></div></td>
In alert(data) i am getting the value.
but when i put same value like this
document.getElementById("#div1").innerHTML=data;
it is not applying the value to element
you don't need # using javascript's getElementById
try this
document.getElementById("div1").innerHTML=data; //notice no `#` in front of div1
or
using jquery that should be
$('#div1').html(data);
try
document.getElementById("div1").innerHTML=data[0];
document.getElementById("div2").innerHTML=data[1];
or
$('#div1').html(data[0]);
$('#div2').html(data[1]);
Pass the actual data inside the object to the HTML element, not the object itself.

Categories

Resources