How to get the values from html form into ajax - javascript

I am doing a project in django which is a car rental/sale web app, the search query works, but when i am trying to submit my form in ajax it seems like it never reaches into ajax.
<div class="container">
<div class="card-header bg-info text-white">
<h4>
<i class="fas fa-car"></i> Search Car </h4>
</div>
<form method="get" id="search-form">
<div class="input-field">
<label for="from">Number:</label>
<input type="number" class="form-control" id="from-place" placeholder="Any" name="number" />
</div>
<section>
<label for="class">Car Type:</label>
<select class="cs-select cs-skin-border input-half">
<option value="" disabled selected>Any</option>
<option value="1">Sedan</option>
<option value="2">Saloon</option>
</select>
</section>
<section>
<label for="class">Price:</label>
<div class="wide">
<select class="cs-select cs-select-half cs-skin-border input-half" name="price">
<option value="" disabled selected>any</option>
<option value="1000">1.000</option>
<option value="2000">2.000</option>
<option value="3000">3.000</option>
</div>
</section>
<div class="col-xxs-12 col-xs-12 text-center">
<input type="hidden" name="search_filter" value="true">
<input type="submit" id="search-apa" value="Search">
</div>
</form>
</div>
and this ajax code:
$(document).ready(function() {
$('#search-form').on('submit', function(e) {
e.preventDefault();
var searchText = $('#search-form').val();
$.ajax({
url: '/cars/search_car/?search_filter=' + searchText,
type: 'GET',
success: function(resp) {
var newHtml = resp.data.map(d => {
return `<div class="cars">
<a href="/cars/${d.id}">
<h4>${d.type}</h4>
<p>${d.price}</p>
</a>
</div>`
});
$('.cars-index').html(newHtml.join(''));
$('.search-form').val( '');
},
error: function(xhr, ststus, error) {
console.log(error);
}
})
});
});
I am trying to get the values from the form into ajax, but when i click search it says undefined. I printed searchText and i does not print anything, it seems like it never reaches the ajax, is something wrong with my form or my i am not calling properly in ajax?
The error that shows is
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
search_car.js:25 Internal Server Error

The $('#search-form') doesn't have any value, because it's a form. You need the <input />'s value. If you need to send the whole form's data, you need to use:
data: $('#search-form').serialize(),
In your AJAX call, please change this way:
$(document).ready(function() {
$('#search-form').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: '/cars/search_car/?search_filter=' + searchText,
type: 'GET',
data: $('#search-form').serialize(),
success: function(resp) {
var newHtml = resp.data.map(d => {
return `<div class="cars">
<a href="/cars/${d.id}">
<h4>${d.type}</h4>
<p>${d.price}</p>
</a>
</div>`
});
$('.cars-index').html(newHtml.join(''));
$('.search-form').val( '');
},
error: function(xhr, ststus, error) {
console.log(error);
}
})
});
});
And make sure you have name attribute for everything and it gets matched in the backend too.

I think what's wrong with the code is this var searchText = $('#search-form').val();
You should get the value of each field by their own selector, you can not just get all the values from form with the form selector. Try console logging the searchText and see if it actually has any value

You are accessing form value with. Val() function. Which is incorrect As form contains multiple child elements it won't return you a value. If you have to access search text then it must be an input control like $('#from-place').val().

The line
var searchText = $('#search-form').val();
asigns searchText an empty string value. What you want is:
let formString = $("#search-form").serialize();

Related

AJAX how to serialize and post all form elements from within an element

I'm trying to serialize and post all form elements that may come from either witin a <form> element, or from within any other elements (div, tr, etc.).
In short, my form will come from either:
<form id="frm1">
Name: <input ...>
Gender: <select ...>
<input type="button" value="Submit" onClick="submitFormData('frm1')"/>
</form>
and sometimes, I have html TABLE so cannot have a <form> in them, therefor I use:
<table>
<tr id="frm1">
<td><input type...></td>
<td><select...></td>
<td><input type="button" value="Submit" onClick="submitFormData('frm1')"/></td>
</tr>
<tr id="frm2">
<td><input type...></td>
<td><select...></td>
<td><input type="button" value="Submit" onClick="submitFormData('frm2')"/></td>
</tr>
</table>
I can't seem to figure out how to pull out and serialize all form elements (inputs, selects, etc.) FROM within a given element.
My code so far :
const ERROR_TYPE_FATALERROR = 1;
const ERROR_TYPE_INPUTERROR = 2;
const ERROR_TYPE_GLOBALMESSAGE = 3;
function submitFormData(formid) {
var formNode = document.getElementById(formid);
$.ajax({
type: 'POST',
url: $(location).attr('href'),
// data: jQuery('#' + formid + ' input').serialize(), // this works, but will only get <INPUT...>s
data: formNode.serialize(), // this doesn't work
dataType : "json",
}).done(function(response) {
// If we have response, then it's PHP that returned an error!
if(response) {
// error type
switch (response.type) {
case ERROR_TYPE_GLOBALMESSAGE:
// unhide informational box (i.e. "Data saved!")
$('#globalMessage').addClass('d-block');
$('#globalMessagePH').empty();
$('#globalMessagePH').append(response.message);
break;
case ERROR_TYPE_FATALERROR:
// unhide form fatal error message box showing response.message
$('#fatalError').addClass('d-block');
$('#fatalErrorMessagePH').empty();
$('#fatalErrorMessagePH').append(response.message);
break;
case ERROR_TYPE_INPUTERROR:
// unhide form input error messages based on response.field
break;
default:
// ...
}
}
// Successful post, but not response came back !?
else {
console.error("Post sent, but no response came back!?");
}
}).fail(function(response) {
console.error("Unknown Error!"); // not sure yet how I'd get here... ?
});
}
I had also tried adding a "data2post" class to all form elements in order get all the elements needed for post and serialize them:
var formNode = document.getElementById(formid);
var formData = formNode.getElementsByClassName('data2post');
...
data: formData.serialize()
...
but it doesn't work: formData.serialize is not a function
As you can see from my JS snippet, I know having just
data: jQuery('#' + formid + ' input').serialize()
works, but this will only get the <INPUT...>. I need to be able to get all form elements regardless of type (inputs, select, textarea, etc.)
And even for the sake of it, might I ask at the same time, considering you folks see what I'm using this ajax for, in good practice, should I be getting the response.type, etc more in the .fail() section ? Not sure how I to do this yet in PHP, meaning trigger a failure. All I know is if I die() my script with JSON data, it'll be sent as the response...
Thanks a million for your help.
Cheers, Pat
EDIT: here is an example of my SELECT inputs:
<tr id="row_1">
<!-- STATUS -->
<td class="text-nowrap">
<select name="isActive" id="isActive" class="form-control pl-2" aria-label="Account Status" aria-describedby="isActiveReq" required>
<option value="1" selected>Enabled</option>
<option value="0" >Disabled</option>
</select>
<!-- missing field: add 'is-invalid' to the <input>'s classes to show OR 'was-validated' to the form's classes -->
<div id="isActiveReq" class="pl-1 invalid-feedback">
This field is required!
</div>
</td>
<td><input type="button" name="btnSave" value="Save" onClick="submitFormData('row_1')"></td>
</tr>
try use $('#frm1').serialize();
var data = $('#frm1').serialize();
$.ajax({
type: "POST",
url: url,
data: data,
success: function(response){
console.log(response);
}
});
Its OK if you don't have form element,
Clone specified id element, either its div or anything:
$('#myDiv').clone()
Append into a form element:
$('<form>').append($('#myDiv').clone()).serialize();
Below is working example, almost type of element included:
function getSerialize(id){
let element = $("#"+id);
// if you are using form element
if( element.prop("tagName") === "FORM" ){
var data = element.serialize();
}
// if your are using another elements
else{
var myInputs = element.clone();
// this is the bug getting select box selected value when clone, so we have selected value in clone using this hack.
element.find('select').each(function(i) {
myInputs.find('select').eq(i).val($(this).val())
})
var data = $('<form>').append(myInputs).serialize();
}
// you can return 'data' variable from here.
console.log(data);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Div Serialize</h1>
<div id="myDiv">
<input type="text" name="name" placeholder="Name"><br><br>
<select name="age" placeholder="Age">
<option value="">Age</option>
<option value="18+">18+</option>
</select><br><br>
<textarea name="about" placeholder="About"></textarea><br><br>
<button onClick="getSerialize('myDiv')">Get Serialize</button>
</div>
<h1>Form Serialize</h1>
<form id="myDivForm" action="" onSubmit="return false;">
<input type="text" name="name" placeholder="Name"><br><br>
<select name="age" placeholder="Age">
<option value="">Age</option>
<option value="18+">18+</option>
</select><br><br>
<textarea name="about" placeholder="About"></textarea><br><br>
<button onClick="getSerialize('myDivForm')">Get Serialize Form</button>
</form>
Hope this help.

POST not grabbing all form variables

Trying to figure out why my code does not send over all POST data. The code is used on main page to get request information stored in db and used on separate page to post status updates made by me to DB. Its basically the same, except variable names.
Note: I have searched here a lot. Ive used var_dump that shows only 'content' data in the array. Im not fully comfortable with js but can follow some of it. Hence the code below is a template that Ive edited and tested on one page before trying to expand to another. Thats where the issue is. I am not sure why it works for one and not the other. Apologies if this is considered duplicate of anything, but I didnt find a good answer in similar post that would explain why.
admin.php:
<form action="insert.php" method="post" enctype="multipart/form-data">
<div class="share">
<div class="arrow"></div>
<div class="panel panel-default">
<div class="panel-body">
<div class="">
<img src="../logo.png" style="height:60px; width:60px; float:left; margin-right:3px;" />
<textarea name="content1" id="content1" cols="40" rows="10" class="form-control message" style="height: 60px; width:450px; overflow: hidden;"></textarea>
</div>
</div>
<div class="panel-footer">
<div class="row">
<div class="col-md-7">
<div class="form-group">
<div class="btn-group">
<select name="avatar" id="avatar" class="form-control-issue-avatar"> <----whats not sending
<option value="0" selected="selected">Author</option>
<option value="per1">P</option>
<option value="per2">W</option>
</select>
</div>
</div>
</div>
<div class="col-md-5">
<input type="submit" value="Post" class="post_button">
</div>
</div>
</div>
</div>
</form>
Here is the insert.php:
if(isSet($_POST['content1'], $_POST['avatar']))
{
$content1=$_POST['content1'];
$avatar=$_POST['avatar']; // <--- comes back NULL
$sql_in= mysqli_query($con,"SELECT comment,comment_id,status_time FROM comments order by comment_id desc");
$r=mysqli_fetch_array($sql_in);
}
and lastly the post.js that calls it:
$(function() {
$(".post_button").click(function() {
var element = $(this);
var test = $("#content1").val();
var dataString = 'content1='+ test;
if(test=='')
{
alert("Please Enter Some Text");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="loading">Loading Comment...</span>');
$.ajax({
type: "POST",
url: "insert.php",
data: dataString,
cache: false,
success: function(html){
$("#display").after(html);
document.getElementById('content1').value='';
$("#flash").hide();
}
});
}
return false;
});
});
the var_dump etc:
Array ( [content1] => sass )
C:\wamp64\www\post\insert.php:32:
array (size=1)
'content1' => string 'sass' (length=4)
Add id attribute to the form and then use serialize() on the form to get all data from the form to pass via ajax to php
<form id='formid'>
$.ajax({
data: $('#formid').serialize(),
//other Ajax stuff
});

Custom value JSON with select2 v4 ajax

I want to grab data other than id or text when an element is selected. The data is retrieved from some source when user puts in some values. All the data fetching and populating works properly. Previously just to get it working, I have just concatenated the "custom" value with some delimiter into the id then later parsed it out, but for the specs of what I want to do, I can't do that anymore. This is basically the code I have so far:
JS:
function convertResult(result) {
return {
id: result.p0,
text: result.p1,
custom: result.p2
};
}
searchBox.select2({
width: '100%',
minimumInputLength: 3,
placeholder: 'Search',
ajax: {
url: {someUrl},
delay: 350,
dataType: 'json',
data: function data(params) {
return { q: params.term }
},
processResults: function processResults(data) {
return { results: $.map(data.results, convertResult); }
}
}
});
searchBox.on("change", function (e) {
var selVal = $(this).val(); //this gets me the id
var selText = $(this).text(); //this gets me the text
// grab the "custom" property from the selected element
}
(cs)HTML:
<div class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label> Dropdown </label>
<div class="col-sm-10">
<select data-url='#Url.Action("get")' class="form-control ">
<option value="" selected="selected"> </option>
</select>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"> Readonly Textfield</label>
<div class="col-sm-10">
<input type="text" class="form-control custom" style="width: 100%;" readonly="readonly">
</div>
</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<button type="submit" class="btn btn-primary">
Submit
</button>
</div>
</div>
</div>
So what I want to do is once an element is selected from the select2 dropdown, populate the readonly textfield with the value saved in custom. When I look at the developer window for my browser I can't seem to find the value on the page. But when debugging, I can see the Json Object with custom value. I have considered scanning through the JSON to find the information I need, but I want to avoid that if possible. How do I go about extracting this information otherwise?

Add HTML form on button click

I have an HTML form in my website/application.
The form has lots of fields of input text, select, and PHP code, as well, to fill drop down values.
Is there any way I can clone/create the same form when the user clicks on the Add button? Let's say, if the user clicks 5 times, it would have five forms on the UI.
HTML
<form id = "buyerForm" role="form" method="POST" enctype="multipart/form-data" style="margin-top:30px;">
<span class="customerno" style="font-size: 22px;">Buyer 1 (Form 2)</span>
<div class="form-group">
<label>APPLICANT DETAILS</label>
</div>
<div class="form-group">
<label>Mr. / Mrs</label>
<select class="form-control" name="jnameTitle" id="jnameTitle">
<option>Please Select One</option>
<option value="Mr">Mr</option>
<option value="Mrs">Mrs</option>
<option value="MS">MS</option>
</select>
</div>
// similar fields are omitted to reduce the complexity
<div class="form-group">
<label>Address</label>
<textarea name="jaddress" id="jaddress" class="form-control" cols="80" rows="5" ></textarea>
</div>
<button type="submit" name="jointCustomers" id="jointCustomers" class="btn btn-success btn-lg btn-flat">Save</button>
<button type="reset" class="btn btn-default btn-lg">Reset</button>
</form>
if you're using jQuery (or dont mind using it) you could just use clone to add the form again to the parent container
$("#youButton").click(function(){
$("#buyerForm").clone().appendTo("#yourParentWrapper");
});
see this fiddle
Yes, there is a way.
Lets say you have the main page -> mainPage.php, where you can have a list and the button (addForm).
Then you will have your myform.php page that will generate a form it self.
The process is very simple.
You press the btn AddForm
You make a request using AJAX against your function that generate the form in the myform.php page.
Inside your AJAX code, you will add your form inside the list object.
Note: This is only a basic idea. You must adapt the code to your needs.
//Your main page, will contain a list.mainPage.php
<ul id="myFORMS">
<li><button id="idBtnElement" type="button">AddForm</button></li>
</ul>
//Your php code to create the form. You can create a function if you want
$arrToJSON = array(
"myFormHtml"=>"You will put your HTML form code here"
);
return json_encode(array($arrToJSON));
//Your javaScript code
$(document).on("event", "#idBtnElement", function(){
//Data you want to send to php evaluate
var dt={
ObjEvn:"btn_ADDFORM"
};
//Ajax
var request =$.ajax({//http://api.jquery.com/jQuery.ajax/
url: "myFormGenerator.php",
type: "POST",
data: dt,
dataType: "json"
});
//Ajax Done catch JSON from PHP
request.done(function(dataset){
for (var index in dataset){
formStrHtml=dataset[index].myFormHtml;
}
//JavaScript
//Here you can grab formStrHtml in apped at the end of the list in your main page.
$("#myFORMS ul").append('<li>'+formStrHtml+'</li>');
});
//Ajax Fail
request.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}

Getting the value of the child of sibling jquery/ajax?

I'm currently trying to make a ajax comment function work once a user clicks "open comments".
Currently I'm getting data back from my php script and the status of the ajax call is "200 OK" so it definetely works but I'm just unable to get the correct value for the current comment which has been clicked on in order to post it to the php script.
What I'm asking is how do I get the value of the ".posted_comment_id" class and then how do I load the data which is returned into the ".commentView" class?
jQuery/AJAX:
$(".closedComment").click(function(){
var $this = $(this);
$this.hide().siblings('.openComment').show();
$this.siblings().next(".commentBox").slideToggle();
$.ajax({
type: "POST",
url: "http://example.dev/comments/get_timeline_comments",
data: {post_id: $this.siblings().next(".commentBox").find(".posted_comment_id").val()},
dataType: "text",
cache:false,
success:
function(data){
$this.closest(".commentView").load(data);
}
});
return false;
});
HTML:
<div class="interactContainer">
<div class="closedComment" style="display: none;">
open comments
</div>
<div class="openComment" style="display: block;">
close comments
</div>
<div class="commentBox floatLeft" style="display: block;">
<form action="http://example.com/comments/post_comment" method="post" accept-charset="utf-8">
<textarea name="comment" class="inputField"></textarea>
<input type="hidden" name="post" value="13">
<input type="hidden" name="from" value="5">
<input type="hidden" name="to" value="3">
<input type="submit" name="submit" class="submitButton">
</form>
<div class="commentView"></div>
<div class="posted_comment_id" style="display:none;">13</div>
</div>
</div>
Replace .val by .html or .text. This will return the innerHTML of the element.
data: {
post_id: $this.siblings().next(".commentBox").find(".posted_comment_id").text()
}
You might need to convert the string to an integer to make it work.
If the query selector fails, this selector might do the job instead:
$this.parent().find(".posted_comment_id")
To add the returned data on your webpage, use the success handler. Here's an example of how it's done:
success: function(json) {
// Parse your data here. I don't know what you get back, I assume JSON
var data = JSON.parse(json),
content = data.whatever_you_want_to_print;
// Assuming your selector works, you put in in the element using .html
$this.closest(".commentView").html(content);
}
});
You probably want to do something like:
$(this).parents('.interactContainer').find(".posted_comment_id").text()

Categories

Resources