I have a form where I have countries list in checkbox format to be inserted into database. Say for example:
<input type="checkbox" name="country[]" value="Afghanistan" checked>Afghanistan<br>
<input type="checkbox" name="country[]" value="Albania" checked>Albania<br>
<input type="checkbox" name="country[]" value="Algeria" checked>Algeria<br>
<input type="checkbox" name="country[]" value="American Samoa" checked>American Samoa<br>
<input type="checkbox" name="country[]" value="Andorra" checked>Andorra<br>
<input type="checkbox" name="country[]" value="Angola" checked>Angola<br>
<input type="checkbox" name="country[]" value="Anguilla" checked>Anguilla<br>
I want to insert this into database using ajax. I could have easily done this through normal same page PHP post. But when sending data with ajax to other page for processing I am confused on how to send. Once it sends all the selected checkbox values perfectly then all the rest is onto me.
My AJAX script
$("#submit").click(function() {
var dataString = {
clicks: $("#clicks option:selected").data("value"),
country: $("input[name=country").data("value") // tried using this and input[name=country[]] but they did not work.
};
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to purchase this advertisement?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
dataType : "json",
url: "add-ptc-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading-rent").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$('#mywallet').html('$' + json.deduct);
$("#loading-rent").hide();
$("#submit").show();
},1000);
}
});
},
cancel: function () {
$.alert('<span style="font-size: 23px">Purchase Cancelled!</span>');
}
}
});
return false;
});
});
I have put a check on the processing page where if the country value is empty return error like:
if($country == ''){
echo "No countries selected. Please select at least one country.";
}
No matter if I select one or all countries still I get this error response back. What should I do to send these checkbox data with ajax?
Try
var countries = {};
$('input[name^="country"]').each(function(){
countries[$(this).attr('value')] = $(this).is(":checked");
});
then post it to ajax data: countries or change the code to send only checked elements
Your PHP will receive an array so you can check
if(is_array($_POST['countries'])){
foreach($_POST['countries'] AS $country_name => $is_checked){
//do something...
}
}
You will want to switch your .data() to .val() on your input capture. Also change the name of the inputs to input[name=country\\[\\]]:checked.
# Use "e" as the event
$("#submit").click(function(e) {
# Use this function to stop the form
e.preventDefault();
# You could make a quick function to save all the countries
# You can actually feed other selectors into this as well, so
# it can do all your value retrievals, not just for countries
function getCountries(checkboxes)
{
var getVals = [];
$.each($(checkboxes),function(k,v) {
getVals.push($(v).val());
});
return getVals;
}
var dataString = {
clicks: $("#clicks option:selected").val(),
# Run the function to gather
# Note the name (escaped [] with :checked)
country: getCountries("input[name=country\\[\\]]:checked")
};
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to purchase this advertisement?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
dataType: "json",
url: "add-ptc-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$("#submit").hide();
$("#loading-rent").show();
$(".message").hide();
},
success: function(json){
setTimeout(function(){
$(".message").html(json.status).fadeIn();
$('#mywallet').html('$' + json.deduct);
$("#loading-rent").hide();
$("#submit").show();
},1000);
}
});
},
cancel: function () {
$.alert('<span style="font-size: 23px">Purchase Cancelled!</span>');
}
}
});
});
Related
Hello guys im currently learning on how to send data from HTML to Django backend using Ajax.
I have this HTML
<div class="form-row">
<input type="checkbox" name="car-checkbox[]" value="Audi" id="chck1">
<input type="checkbox" name="car-checkbox[]" value="BMW" id="chck2">
<input type="checkbox" name="car-checkbox[]" value="Lambo" id="chck2">
<input id="submit-car" type="button" value="Submit">
</div>
and then to send the data i use this code (Ajax)
$('#submit-car').click(function () {
const data = {user_id: user_id}
$.ajax({
type: 'POST',
url: '/submit-car/',
data: data,
beforeSend: function (request) {
request.setRequestHeader("X-CSRFToken", csrftoken);
},
success: function (data) {
$('#submit-form-field').prop('disabled', true);
location.reload();
alert("Submit OK!");
}
});
});
and then on the Django side i try to get the checked checkbox
def insert_car_to_db(self, request):
cars = request.POST.getlist('car-checkbox[]')
print(cars)
Weirdly enough when i try to get the checked data, i keep getting [] value,
where did i miss ? am i misunderstand something?
P.S
i followed this post
How to get array of values from checkbox form Django
$('#submit-car').click(function () {
const car_checkbox = [];
const user_id = "Some test UserId";
const csrftoken = "Provided CSRF TOKEN";
$("input[type=checkbox]:checked").each(function(){
car_checkbox.push($(this).val());
}); //STore the checkbox result in an array
const data = {"user_id": user_id, "car-checkbox": car_checkbox}
console.log(data);
$.ajax({
type: 'POST',
url: '/submit-car/',
data: data,
beforeSend: function (request) {
request.setRequestHeader("X-CSRFToken", csrftoken);
},
success: function (data) {
$('#submit-form-field').prop('disabled', true);
location.reload();
alert("Submit OK!");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-row">
<input type="checkbox" name="car-checkbox" value="Audi" id="chck1">
<input type="checkbox" name="car-checkbox" value="BMW" id="chck2">
<input type="checkbox" name="car-checkbox" value="Lambo" id="chck2">
<input id="submit-car" type="button" value="Submit">
</div>
So where you are sending the checkbox array value to backend /submit-car/ ?
what is user_id in your click evennt?
As you are using jquery so
$('#submit-car').click(function () {
const car_checkbox = [];
$("input[type=checkbox]:checked").each(function(){
car_checkbox.push($(this).val());
}); //STore the checkbox result in an array
const data = {"user_id": user_id, "car-checkbox": car_checkbox}
$.ajax({
type: 'POST',
url: '/submit-car/',
data: data,
beforeSend: function (request) {
request.setRequestHeader("X-CSRFToken", csrftoken);
},
success: function (data) {
$('#submit-form-field').prop('disabled', true);
location.reload();
alert("Submit OK!");
}
});
});
Currently, my checkbox values is being stored as ["A","B","C"] into the database when I have only selected one option (eg C). Also, I have another question - is there any way possible to store it as ABC instead?
$(document).ready(function() {
"use strict";
var role;
});
function savenewuser() {
var url = serverURL() + "/newadmin.php";
checklist = new Array();
$('input:checkbox[name="roles[]"]').each(function() {
checklist.push($(this).val());
});
role = JSON.stringify(checklist);
$.ajax({
url: url,
type: 'GET',
data: {
"role": role,
},
success: function(arr) {
_getNewUserResult(arr);
},
error: function() {
alert("error");
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div><label for="rights">Rights</label></div>
<input type="checkbox" name="roles[]" value="A">Bookings
<input type="checkbox" name="roles[]" value="B">Incident Booking
<input type="checkbox" name="roles[]" value="C">Edit User
You're saving all the checkboxes:
$('input:checkbox[name="roles[]"]').each(function() {
checklist.push($(this).val());
});
Try saving :checked ones only:
$('input:checkbox[name="roles[]"]:checked').each(function() {
checklist.push($(this).val());
});
I have been having a little problem. I am trying to create a filter for my database. So far I have come up with this:
Blade File:
<input type="text" class="form-control" id="search" name="search" placeholder="Name, NORAD or ID"></input>
<select name="filtername" id="filtername">
<option value="none"></option>
<option value="Falcon">Falcon</option>
<option value="rb">R/B</option>
</select>
Javascript AJAX Call:
$(document).ready(function() {
$('#search').on('keyup', function() {
$value = $(this).val();
delay(function() {
if ('#search'.length > 3) {
$.ajax({
type: 'get',
url: '{{$launchsitename->site_code}}',
data: {
'search': $value
},
success: function(data) {
$('#launchsatdisplay').html(data);
}
});
}
}, 300);
});
$("#filtername").change(function() {
var filtername = $(this).val();
var dataString = "filtername=" + filtername;
$.ajax({
type: "get",
url: "{{$launchsitename->site_code}}",
data: {
'search': dataString
},
success: function(data) {
$('#launchsatdisplay').html(data);
}
});
});
});
Controller:
if ($request->ajax())
{
$output="";
$launchsitesatellite = DB::table('satellites')
->where(function($q) use ($request) {
$q->orWhere('satname','LIKE','%'.$request->search.'%')
->orWhere('norad_cat_id','LIKE','%'.$request->search.'%')
->orWhere('object_id','LIKE','%'.$request->search.'%');
})
->where('site', $site_code)->get();
if ($launchsitesatellite)
{
$output .='<tr>'.
'<th>'.'Satellite Name'.'</th>'.
'<th>'.'NORAD ID'.'</th>'.
'<th>'.'Object Type'.'</th>'.
'<th>'.'Launch Date'.'</th>'.
'<th>'.'Country'.'</th>'.
'<th>'.'Object ID'.'</th>'.
'<tr>';
foreach ($launchsitesatellite as $key => $launchsitesatellites) {
$output .='<tr>'.
'<td>'.$launchsitesatellites->satname.'</td>'.
'<td>'.$launchsitesatellites->norad_cat_id.'</td>'.
'<td>'.$launchsitesatellites->object_type.'</td>'.
'<td>'.$launchsitesatellites->launch.'</td>'.
'<td>'.$launchsitesatellites->country.'</td>'.
'<td>'.$launchsitesatellites->object_id.'</td>'.
'</tr>';
}
}
return $output;
}
else {
$launchsitesatellite = DB::table('satellites')->where('site', $site_code)->Paginate(40);
return view('pages/launchsite-filter', compact('launchsites', 'launchsitesatellite'));
}
This code is for making an AJAX call to my controller and getting the results from the database. The code posted above works perfectly for the input. I am able to search the database with ease. The only problem is with the select. Whenever I select an option, it returns no results. I am guessing there is something wrong with the way I programmed the select in my controller, as I don't think the Javascript would be causing the problem.
The select should be reading the satname column in my database called satellites and returning the filtered results.
Would somebody be able to shed some light on why the select is not working or where the error in my code is?
modify your ajax call code for select box as below
$("#filtername").change(function() {
var dataString = $(this).val();
$.ajax({
type: "get",
url: "{{$launchsitename->site_code}}",
data: {
'search': dataString
},
success: function(data) {
$('#launchsatdisplay').html(data);
}
});
});
I am trying to get the value of a textbox without pass through form actions (because i cannot neither redirect to another page or refresh the current one).
index.php
into head
<script type="text/javascript">
function send() {
$.ajax({
type:"POST",
url: "script.php",
data: {
fname: document.getElementById("fname").value,
lname: document.getElementById("lname").value
},
success: function callScriptAndReturnAlert() {
var sdata = new XMLHttpRequest();
sdata.onload = function() {
alert(this.responseText);
};
sdata.open("get", "script.php", true);
sdata.send();
}
});
}
</script>
into body
<button class="myclass" onclick="send();">MyButton</button>
<input type="text" id="fname" placeholder="First name here" />
<input type="text" id="lname" placeholder="Last name here" />
Button is before input just for UI stuffs
script.php
$prev = $_SESSION['prev'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
[....do something....]
echo 'You used '.$fname.' and '.$lname;
Well.. the script.php doesnt receive the value of the inputs fname and lname.
You are trying to make two ajax calls when you only need one.
<script type="text/javascript">
function send() {
$.ajax({
type:"POST",
url: "script.php",
data: {
fname: $("#fname").val(),
lname: $("#lname").val()
},
beforeSend: function(){
alert('Sending');
},
success: function(data) {
//Received data from PHP script
alert(data);
},
error: function(){
alert('Error !');
},
complete: function(){
alert('Done');
}
});
}
</script>
$.post(
'script.php', // Your PHP file
{ // The data to pass
'fname' : $('#fname').val(),
'lname' : $('#lname').val()
}
).done(function(data) { // Here your AJAX already finished correctly.
alert(data); // Show what the PHP script returned
});
The $.ajax(), $.get() and $.post() jQuery methods are for making AJAX calls and, due to that, they already manage their own XMLHttpRequest object.
I am working on a small tool which just consists of a single JSP which is used for view as well as for processing the AJAX response.
If the call is of type 'GET', I am showing a form the user.
<form id="submitForm" method="post">
<div class="ui-widget">
<label for="tags">Please Select the Merchant : </label>
<input id="tags" name="mechant" style="width:300px;height:40px;border: 0.5px solid;border-radius: 5px;">
<input type="submit" value="Get Data" style="border: 0.5px solid;border-radius: 5px;">
</div>
</form>
And following is the code which will make the call.
$("#submitForm").submit(function() {
$.ajax({
url: 'serve_tx_2.jsp',
type: 'POST',
data: {q: $('#tags').val()},
success: function(data) {
$('#data').html(data);
alert('Load was performed.');
},
beforeSend: function() {
// $('.loadgif').show();
},
complete: function() {
// $('.loadgif').hide();
}
});
//return false;
});
Once the user submits the form which goes as 'POST' the logic in the same JSP is returning the response.
Right now I am trying with a very simple logic.
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("Hello World");
Now when this response is return the whole of initial page is washed off and I just see "Hello World" on the page. Even though as per my understanding only the div with id "data" should be updated with value.
Kindly anyone have a look and let me know what might be going wrong here.
Thanks in advance.
You could try preventing the default handler as well as prevent bubbling up the DOM.
$("#submitForm").submit(function(event) {
// Prevent the default action
event.preventDefault();
// Pevent propagation of this event up the DOM
event.stopPropagation();
$.ajax({
url: 'serve_tx_2.jsp',
type: 'POST',
data: {q: $('#tags').val()},
success: function(data) {
$('#data').html(data);
alert('Load was performed.');
},
beforeSend: function() {
// $('.loadgif').show();
},
complete: function() {
// $('.loadgif').hide();
}
});
//return false;
});