Problems with ajax post application - javascript

I have the following problem I have a wild <div class="aside_data"></div> which is populated with information via ajax => $('.aside_data').html(data), the information is of many checkboxes: <input type=" checkbox" class="css-checkbox category" id="1" name ="cat" value="cat1">
The problem is that I can't use these generated checkboxes to send data from them via ajax. They are somehow inactive, as if he does not find them at all.
I understand that I am explaining quite confusingly, I will add more information about this, if you still do not understand me, please tell me to explain.
javascript:
$.ajax({
url:"<?php echo $g['url']; ?>aside-cat.php",
method:"POST",
data:{cat:filter},
success:function(data){
$('.aside_data').html(data);
}
});
html:
<div class="aside_data"></div>
after ajax post .aside_data contains:
<input type=" checkbox" class="css-checkbox category" id="1" name="cat" value="cat1">
and after this i try to get informations from this checkboxes with:
function get_filter(class_name) {
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
return filter;
}
But I fail

Related

access a specific input in an input array

<td><input type="text" name="product_code[]" id="product_code1" class="form-control input-sm" /></td>
I have been creating an invoice system ... how can I access a specific input to get its text ( product code ) and load the description from the database???
I know how to access all the elements but cannot access the specific one the user is typing text :(
using the below code trying to get the value returns all the values of the product code text inputs and only works for the first one
$('[name="product_code[]"]').keyup(function() {
var values = $("input[name='product_code[]']")
.map(function(){return $(this).val();}).get();
alert(values);
});
#AlexisGarcia lets say user types product code I want to access the db and retrieve product description for that product code ... how do I get through javascript or jquery the value of the specific input the user is typing???
You have to use AJAX to get that from Database.
First you need to get what the user has typed (input value), and then send it to AJAX. Here is an example:
$('#product_code1').keyup(function(){
var user_text = $(this).val();
$.ajax({
method: 'post',
url: 'link_to_your_controller',
data: {text: user_text},
dataType: 'json',
complete: function(data) {
//..DO SOMETHING WITH RESULT FROM DB
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td>
<input type="text" name="product_code[]" id="product_code1" class="form- control input-sm" />
</td>
You need to learn about AJAX to do what you need.
You can start by reading https://www.w3schools.com/xml/ajax_intro.asp
$('.input-sm').keyup(function() {
var values = $(this).val();
alert(values);
});
Try this code, you will get what you want

Javascript from processor - unable to debug issues

I have a form that I'm trying to submit and process with javascript using the code outlined below:
Form:
<form id="my_form_id" method="POST" action="my_processor_script.php">
<input type="text" id="form_id_1" name="form_field_1">
<input type="text" id="form_id_2" name="form_field_2">
<input type="text" id="form_id_3" name="form_field_3">
<input class="cbp-mc-submit" type="submit" name="save_settings_button" id="save_settings" value="Save Settings" />
</form>
Script:
<script>
$(document).ready(function(){
var $form = $('form');
$form.submit(function(){
$.post($(this).attr('action'), $(this).serialize(), function(response){
// do something here on success
alert("Form Processed");
},'json');
return false;
});
});
</script>
Processor:
<?php if (isset($post_data['save_settings_button']))
{
$form_field_1 = $_POST['form_field_1'];}
$form_field_2 = $_POST['form_field_2'];}
$form_field_3 = $_POST['form_field_3'];}
}
?>
Once I have the variables I then store them in a database.
The form works great if I just post from the form to the processor script without using the javascript however when I use the javascript nothing happens. I'm obviously doing something very wrong but can work this out at all as I cant see what is being received by the processor. Has anyone got any ideas on how i can get this to work?
It would also be great if I can return the data so that I can see what is being passed to the script as this would help me to debug any issues?

Using AJAX to submit form

I have developed a Python API and am now integrating it with a HTML template I have downloaded. It is a simple one page HTML template with a form to accept a album name and artist name. I am looking to process the form using AJAX. So once the form has been successfully submitted, it is replaced with a message returned by the API.
The (simplified) html snippet is:
<div class="form">
<form role="form" action="form.php" id="signup">
<div class="form-group">
<label>Artist Name</label>
<input type="text" name="artist" id="artist">
</div>
<div class="form-group">
<label>Tracking Number</label>
<input type="text" name="album" class="album">
</div>
<button type="submit" class="btn">Submit!</button>
</form>
</div>
Then I have a JS file I import at the beginning of the html file. Below is the JS file.
$(function() {
var form = $('#signup');
var formMessages = $('#form-messages');
$(form).submit(function(e) {
e.preventDefault();
var formData = {
'artist' : $('input[name=artist]').val(),
'album' : $('input[name=album]').val(),
};
// process the form
$.ajax({
type : 'POST',
url : 'form.php',
data : formData,
dataType : 'json'
})
.done(function(data) {
var content = $(data).find('#content');
$("#result").empty().append(content);
});
});
I think the issue is with the .done(function(data)) however, the website I found the code on wasn't clear.
form.php returns a JSON string. At the moment when I use the form, it sends the information to the Python API and the Python API returns a JSON message. But I cannot access the JSON message. It is in contains
'code': X, 'message':'returned messaged...'
ideally I would like to do a if/else statement. So
if code = 1:
display: Success
etc but I have no idea where to start with it in PHP/JS.
I was able to get it working eventually after seeing a few other stack overflow answers and another website.
I added one div to the html file under the button before the end of the form to make:
<form>
...
...
<button type="submit" class="btn">Submit!</button>
<div id="thanks" style="display:none;"></div>
</form>
Then, in the JS file I amended .done(function(data)) to be:
.done(function(data) {
if (data.result == '1') {
$('#thanks').show().text("Success!");
$('input[type="text"],text').val('');
} else if (data.result == '2') {
$('#thanks').show().text("Album and Artist already exists");
} else {
$('#thanks').show().text("Uh Oh. Something has gone wrong. Please try again later or contact me for more help");
}
});

Newbie to Javascript: how to avoid sending data that have not changed?

I'm a newbie Javascript learner and I want to post serialized data of input checkboxes. The data are sent to the server in order to update the corresponding field in SQL table. Later, the user can review the selections he made the first time and deselect some checkboxes. If I understand well, only the selected items will be sent, not the unselected ones. How can I send all the info I need to update the newly selected items and the newly unselected ones?
The only solution I found is to make 2 updates: the first resets to 0 all the rows and the second one sets to 1 the selected items (newly selected or not) that are sent in the serialized array. Is there a more optimal way to do the job? Ideally, I would update only the data that have changed. Is it possible?
Regards,
Patrick
If I understand it correctly you can filter the checkboxes and then you can add the unselected boxes to the parameters too.
I've found the code for that here at SO. See this question.
The demo below and here a jsfiddle is doing a ajax post only if the user changed the data. Not sure if this is what you want.
(The demo at SO is a bit modified because JSONP is required to get no CORS error.)
var data = "";
$('form').submit(function (evt) {
evt.preventDefault();
//console.log($(this).serialize());
var formData = $(this).serialize();
// source from this SO question https://stackoverflow.com/questions/10147149/how-can-i-override-jquerys-serialize-to-include-unchecked-checkboxes
// include unchecked checkboxes. use filter to only include unchecked boxes.
$.each($('form input[type=checkbox]')
.filter(function (idx) {
return $(this).prop('checked') === false
}),
function (idx, el) {
// attach matched element names to the formData with a chosen value.
var emptyVal = "off";
formData += '&' + $(el).attr('name') + '=' + emptyVal;
});
console.log(formData);
if ( data != formData ) { // check if user changed the data.
$.ajax({
url: 'http://jsfiddle.net/echo/jsonp/',
type: 'POST',
//data: formData, // this will work but for jsfiddle echo the code below is required.
dataType: "jsonp",
data: {
json: JSON.stringify({
serialized: formData
}),
delay: 1
},
success: function(res) {
console.log('posted: ', res);
}
});
}
data = formData;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="first">check1</label>
<input name="first" id="first" type="checkbox" />
<label for="second">check2</label>
<input name="second" id="second" type="checkbox" />
<label for="third">check3</label>
<input name="third" id="third" type="checkbox" />
<label for="fourth">check4</label>
<input name="fourth" id="fourth" type="checkbox" />
<input type="submit" value="update" />
</form>

Response from AJAX request is only displayed once

I've got some code that sends an ajax request when a form is being submitted. This works the first time the form is submitted (it's a search module), but only once. I've added an effect to highlight the table when data is returned, and you can only see it once (the data changes only once as well).
When I look at the response in the chrome dev tools, I can see it contains the data of the new search query but this isn't shown. Why can I only display results once?
JS:
$(function () {
// Creates an ajax request upon search form submit
var ajaxFormSubmit = function () {
var $form = $(this);
var options = {
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize()
};
$.ajax(options).done(function (data) {
var $target = $($form.attr("data-nn-target"));
var $newHtml = $(data);
$target.replaceWith($newHtml);
$newHtml.effect("highlight");
});
// Prevent default action
return false;
};
$("form[data-nn-ajax='true']").submit(ajaxFormSubmit);
});
HTML:
<form method="GET" action="#Url.Action("Index", "Show")" data-nn-ajax="true" data-nn-target="#contentlist" class="form-search">
<div class="input-append mysearch">
<input type="search" class="span5 search-query" name="query" data-nn-autocomplete="#Url.Action("AutoComplete")" />
<input type="submit" class="btn" value="Search" />
</div>
</form>
<div id="contentlist">
#Html.Partial("_Shows", Model)
</div>
I think you should use html() instead of replaceWith() method:
$target.html($newHtml);
just an idea... try
$target.html(data);
instead of
$target.replaceWith($newHtml);
By replaceWith, you might actually remove the div that you want to fill your content in. Then, the second time, it doesnt find the div to insert the content into.

Categories