I have code in html inputs and checkbox the javascript code collects the data of the inputs and in ajax must send the information does not reach the php where it receives it and puts it in session.
ajax send the array for the php file, but the array is empty and i dont know what happen, im sorry my english is very ugly :(
function addcarto() {
var quantity1 = document.getElementById("quiantitynice1").value;
var quantity2 = document.getElementById("quiantitynice2").value;
var quantity3 = document.getElementById("quiantitynice3").value;
var quantity4 = document.getElementById("quiantitynice4").value;
var quantity5 = document.getElementById("quiantitynice5").value;
var quantity6 = document.getElementById("quiantitynice6").value;
var quantity7 = document.getElementById("quiantitynice7").value;
var quantity8 = document.getElementById("quiantitynice8").value;
var quantity9 = document.getElementById("quiantitynice9").value;
var quantity10 = document.getElementById("quiantitynice10").value;
var quantity11 = document.getElementById("quiantitynice11").value;
var quantity12 = document.getElementById("quiantitynice12").value;
var quantity13 = document.getElementById("quiantitynice13").value;
var quantity14 = document.getElementById("quiantitynice14").value;
var quantity15 = document.getElementById("quiantitynice15").value;
var quantity16 = document.getElementById("quiantitynice16").value;
var quantity17 = document.getElementById("quiantitynice17").value;
var quantity18 = document.getElementById("quiantitynice18").value;
var quantity19 = document.getElementById("quiantitynice19").value;
var quantity20 = document.getElementById("quiantitynice20").value;
var quantity21 = document.getElementById("quiantitynice21").value;
var quantities = [quantity1, quantity2, quantity3, quantity4, quantity5, quantity6, quantity7, quantity8, quantity9, quantity10, quantity11, quantity12, quantity13, quantity14, quantity15, quantity16, quantity17, quantity18, quantity19, quantity20, quantity21];
$.ajax({
type: 'post',
url: 'php/addCart2.php',
data: 'cantidades=' + quantities,
//data: { 'cantidades': JSON.stringify(quantities)},
success: function (response) {
alert(response.status);
},
error: function () {
alert("error");
}
});
}
<div class="form-check">
<input class="form-check-input" name="ingrediente" type="checkbox" id="ing19" value="19">
<label class="form-check-label" for="ing19">CAMARON</label>
</div>
<div class="quiantitynice" id="quiantitynice19" style='position:relative;display:none'>
<input class="formgroup" type="number" name="quantity" id="quiantitynice19" min="1" value="" Style="width:45Px" placeholder="1">
</div>
<div class="row text-center">
<div class="col">
<button class="btn btn-lg btn-wy" name ="btnsubmin" type = "submit" onclick="addcarto('');">AGREGAR</button>
</div>
</div>
this is the code of the php file:
<?php
session_start();
if(!empty($_POST)) {
//si llega id y cantidad
$canti = $_POST['cantidades'];
$_SESSION["canti"] = $canti;
}
?>
use these code in your ajax:
contentType: 'application/json; charset=utf-8',
dataType: "JSON",
Related
I have a form with text fields which the user can "Add New" by clicking a button. These fields share the same name. I'm trying pass the values into Google Spreadsheets, but the values all come through as 'undefined' with the following code, even though console.log prints the answers as strings which look okay to me.
So if the user for example submits 3 separate entries for SUNDAY_NOTES[], all 3 strings should end up in one cell broken up by new lines, but instead I'm just getting "undefined".
<form action="" method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]"> // the user can create multiples of these ^ for each day of the week
<input type="submit" id="submit" />
</form>
<script>
$(document).ready(function() {
var $form = $('form#timesheet'),
url = 'https://script.google.com/macros/s/AKf45XRaA/exec'
$('#submit').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeArray().map((e) => {
return e.value
}).join('\n')
});
})
});
</script>
Your code works. In the snippet below I am storing the data split by \n in a variable and logging it. You can check the output.
Although your JS is correct, I suspect that you actually want to be using a different HTTP method. Perhaps POST or PUT? I can't be specific as you have not said which API endpoint you are using.
$(document).ready(function() {
var $form = $('form#timesheet'),
url = 'https://script.google.com/macros/s/AKf45XRaA/exec'
$('#submit').on('click', function(e) {
e.preventDefault();
var data = $form.serializeArray().map((e) => {
return e.value
}).join('\n');
console.log(data);
var jqxhr = $.ajax({
url: url,
method: "POST",
dataType: "json",
data: data
}).done(response => {
console.log(response);
}).fail((jqXHR, textStatus) => {
console.log("Request failed: " + textStatus);
});
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]">
<input type="submit" id="submit" />
</form>
remove the [] from your input's name as this is needed if you want to receive an array in the server side, then create a function that groups the values according to the inouts' keys :
function group(arr) {
var tempArr = [];
arr.forEach(function(e) {
var tempObj = tempArr.find(function(a) { return a.name == e.name });
if (!tempObj)
tempArr.push(e)
else
tempArr[tempArr.indexOf(tempObj)].value += ', ' + e.value;
});
return tempArr;
}
and use it like :
$('#submit').on('click', function(e) {
e.preventDefault();
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: group($form.serializeArray()),
//... rest of your code
this will keep the original structure that works,
here's a snippet :
var $form = $('form#timesheet');
function group(arr) {
var tempArr = [];
arr.forEach(function(e) {
var tempObj = tempArr.find(function(a) { return a.name == e.name });
if (!tempObj)
tempArr.push(e)
else
tempArr[tempArr.indexOf(tempObj)].value += ', ' + e.value;
});
return tempArr;
}
$form.submit(function(e) {
e.preventDefault();
var grouped = group($form.serializeArray());
console.log(JSON.stringify(grouped))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES"><br />
<input type="text" name="SUNDAY_NOTES"> // user can click a button to keep adding more SUNDAY_NOTES fields
<input type="text" name="MONDAY_NOTES"> // and so forth
<input type="submit" id="submit" />
</form>
i have form that need the previous value inserted....i'm using ajax,but the success: function(data) wont let me moved to the next page...
here is my code
HTML
<form>
<input type="text" name="id_1" id="id_1>
<input type="text" name="id_2" id="id_2>
<input type="text" name="id_3" id="id_3>
<button type="button" onclick="next();">
</form>
<div id="tabelna"></div>
JQuery
var id_1 = $('#id_1').val();
var id_2= $('#id_2').val();
var id_3= $('#id_3').val();
var datana = 'id_1='+id_1+'&id_2='+id_2+'&id_3='+id_3;
var urlna="<?=base_url()?>something/something/something";
$.ajax({
type: 'POST',
url: urlna,
data: datana,
beforeSend:function(data){
},
message:"<center>><h3>Loading Data. . .</h3></center>"
});
},
error: function(data) {
jAlert('Failed');
},
success: function(data) {
load();
}
})
return false;
}
function load()
{
$('#tabelna').load('<?=base_url()?>something/something/something') (This is my mistake)
}
CONTROLLER
function set_value()
{
extract($_POST);
$d['id1'] = $this-db->query('SELECT * FROM TBL1 where id='.$id_1);
$d['id2'] = $this-db->query('SELECT * FROM TBL2 where id='.$id_2);
$d['id3'] = $this-db->query('SELECT * FROM TBL3 where id='.$id_3);
$this->load->view('something/v_add',$d); (this is my mistake)
}
How can i pass the submitted value to the controller and shows new form ?
we can call controller function using window.location
function load()
{
window.location.href = "<?php echo site_url('controller_d/login/admin_link_delete_user');?>";
}
I have a form which gets files along with other inputs , I want to pass those data to my ajax function. But when i check for those files in server , the server doesn't receive the file. I am new to ajax and Jquery. Here is what i have done.
<form id = "comp_inter_form">
<input type="radio" name="inter_fit" id="inter_good_fit" value = "good" >
<input type="radio" name="inter_fit" id="inter_bad_fit"
<input id="report_upload" type="file"/>
<input id="skype_upload" type="file"/>
<input id="audio_upload" type="file"/>
<input type = "submit" class = "update_interview_btn btn btn-primary" value = "Update"/>
</form>
Ajax function
function completeInterview(id,profile_id){
console.log("Candidate ID is : "+id+"\n Profile id is :"+profile_id );
$('#completeIntModal').modal('show');
var candidate_id = id;
var profile_id = profile_id;
var inter_fit,report_file,skype_file,audio_file;
$("#comp_inter_form").on('submit',function(){
var inter_fit = $("input[name=inter_fit]:checked").val();
var report_file = $("#report_upload").prop('files');
var skype_file = $("#skype_upload").prop('files');
var audio_file = $("#audio_upload").prop('files');
var dataString = 'inter_fit=' +inter_fit+ '&report_file=' +report_file+ '&skype_file=' +skype_file+ '&audio_file=' +audio_file+ '&candidate_id=' +candidate_id+ '&profile_id=' +profile_id;
$.ajax({
type: "POST",
url: "/complete_interview",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: dataString,
cache: false,
success: function(data) {
alert(data.msg);
},
error : function(xhr ,status ,error)
{
console.log(xhr);
alert(xhr);
}
});
});
Please try to make it like following and check if it works, As you are trying to post content VIA ajax with file input, it has to be treated separately.
You have to use FormData for this.
$("#comp_inter_form").on('submit',function(){
var inter_fit = $("input[name=inter_fit]:checked").val();
var report_file = $("#report_upload").prop('files');
var skype_file = $("#skype_upload").prop('files');
var audio_file = $("#audio_upload").prop('files');
var dataString = 'inter_fit=' +inter_fit+ '&report_file=' +report_file+ '&skype_file=' +skype_file+ '&audio_file=' +audio_file+ '&candidate_id=' +candidate_id+ '&profile_id=' +profile_id;
var formData = new FormData();
formData.append("inter_fit",inter_fit);
formData.append("candidate_id",candidate_id);
formData.append("profile_id",profile_id);
var fileInput = $("#report_upload").get(0);
formData.append("report_file",fileInput.files[0]);
fileInput = $("#skype_upload").get(0);
formData.append("skype_file",fileInput.files[0]);
fileInput = $("#audio_upload").get(0);
formData.append("audio_file",fileInput.files[0]);
$.ajax({
type: "POST",
url: "/complete_interview",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: formData,
contentType: false, // Not to set any content header
processData: false, // Not to process data
cache: false,
success: function(data) {
alert(data.msg);
},
error : function(xhr ,status ,error)
{
console.log(xhr);
alert(xhr);
}
});
On the server side you need to check for posted file array and process those accordingly.
So I've been scouring the interwebs and I cant find anything that works for me. I have a simple html form that I need to send via JSON to the app engine datastore.
HTML form:
<form method="get" name="vehicle-form" id="vehicle-form">
<input type="text" name="type" placeholder="Vehicle Type" requried>
<input type="text" name="make" placeholder="Make" requried>
<input type="text" name="model" placeholder="Model" requried>
<input type="text" name="year" placeholder="Year" requried>
<button id="submit-btn">Add</button>
</form>
Javascript: EDIT: Changed this- now all the values are going in as null
var formData = {};
$("#part-form").serializeArray().map(function (x) { formData[x.name] = x.value; });
//var par = document.getElementById("test2");
//par.innerHTML += "<p>";
//for (var i in formData) {
// par.innerHTML += formData[i] + "<br>";
//}
//par.innerHTML += "</p>";
var uriString = myUrl;
$.ajax({
url: uriString,
type: "POST",
//data: JSON.stringify(formData)
data: { "type" : formData[0], "quantity" : formData[1], "cost" : formData[2], "vehicle_id" : formData[3] }
});
I am doing this on a windows 8 phone, and the success function doesn't execute, and no data is added to the datastore.
Here is the backend code for the POST request
class AddVehicle(webapp2.RequestHandler):
def post(self):
"""Creates a vehicle entity
POST Vehicle Variables:
vehicle_type = vehicle type - required
make = Make - requried
model = Model - required
year = Year - required
"""
new_vehicle = Vehicle()
vehicle_type = self.request.get('type', default_value=None)
make = self.request.get('make', default_value=None)
model = self.request.get('model', default_value=None)
year = self.request.get('year', default_value=None)
# all required info
new_vehicle.vehicle_type = vehicle_type
new_vehicle.make = make
new_vehicle.model = model
new_vehicle.year = year
self.response.write(new_vehicle)
# post data into datastore
key = new_vehicle.put()
out = new_vehicle.to_dict()
self.response.write(json.dumps(out))
return
This is the ndb model
class Vehicle(ndb.Model):
vehicle_type = ndb.StringProperty(required=True)
make = ndb.StringProperty(required=True)
model = ndb.StringProperty(required=True)
year = ndb.StringProperty(required=True)
Got it to work:
$.ajax({
url: uriString,
type: "POST",
contentType: "application/x-www-form-urlencoded", //<-- THIS
data: { type: vehicle_type, make: vehicle_make, model: vehicle_model, year: vehicle_year },
success: function (result) {
WinJS.Navigation.navigate("/pages/vehicleAdd/vehicleAdd.html");
}
});
Turns out I needed to send url encoded form data instead of json...
I m sending some checkbox which are selected,their value to next php page with ajax call.but in the above code i m not able to send it to ajax call
code is as below
<html>
<head>
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="services"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
$(document).ready(function(){
$('#btnSubmit').on('click', function () {
alert("hi");
//var os = $('#originState').val();
\ //var c = $('#commodity').val();
//var ds = $('#destState').val();
var ser = get_check_value();
//var queryString = "os=" + os;
var queryString = "&ser=" + ser;
alert("hi");
$.ajax({
//alert("ajax");
type: "POST",
url: "sortingajax.php",
data: "query=" + queryString,
success: function (b) {
// alert(a+' ok. '+b)
$('#results').html(b);
console.log(b);
}
});
});
});
</script>
<form name="searchForm">
<input type="checkbox" name="services" value="twic" />TWIC
<br/>
<input type="checkbox" name="services" value="enclosedTrucking" />Enclosed Trucking
<br/>
<input type="checkbox" name="services" value="flatBedTrucking" />Flat Bed Trucking
<br/>
<input type="submit" id="btnSubmit" value="Submit" />
</form>
<div id="results">
</div>
</body>
</html>
In above code.When i select checkboxes from page,and on click of submit.i want to pass them to next php page with ajax call.but its not going to next page and no response is coming back....
Please help guysss
ajaxphp page
<?php
include('connection.php');
$query=$_GET['query'];
echo $query;
$countsql='SELECT * FROM XML';
$countsql1=mysql_query($countsql);
$numrows = mysql_num_rows($countsql1);
$countArray2=array();
print($countsql);
while($row = mysql_fetch_array($countsql1)) {
// Append to the array
$countArray2[] = $row;
//echo $row['PID']."<BR />";
}
?>
<?php
foreach($countArray2 as $array)
{
?>
<div class="search">
hi
</div>
<?php $i++; } ?>
data: "query=" + queryString, is wrong because the "query=" + is a syntax error. It should be:
var queryString = "os="+os+"&ser="+ser;
and then
data : queryString,
Or you can format it like:
data : {
'ser' : ser,
'os' : os
}
Then there is the fact that your Ajax is using POST but you're trying to read the request with $_GET rather than $_POST or $_REQUEST in your PHP.
You can try with these two amends:
var data : "?ser=" + ser; // put '?' instead of '&'
Or more jQuery way:
data : { ser : ser },
And you are missing the dataType in your ajax:
dataType : 'html',
On the php side, as this is a post request, so you have to put this:
$query=$_POST['ser'];
Maybe you're forgetting to prevent the Submit button default behavior:
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="services"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
$(document).ready(function(){
$('#btnSubmit').on('click', function (evt) {
evt.preventDefault();
alert("hi");
//var os = $('#originState').val();
\ //var c = $('#commodity').val();
//var ds = $('#destState').val();
var ser = get_check_value();
//var queryString = "os=" + os;
var queryString = "&ser=" + ser;
alert("hi");
$.ajax({
//alert("ajax");
type: "POST",
url: "sortingajax.php",
data: "query=" + queryString,
success: function (b) {
// alert(a+' ok. '+b)
$('#results').html(b);
console.log(b);
}
});
});
});
</script>