Field 'mobile' expected a number but got ['2222222', '2222222'] - javascript

This is Error showing
TypeError at /page
Field 'mobile' expected a number but got ['22222', '3333'].
Request Method: POST
Request URL: http://127.0.0.1:8000/page
Django Version: 4.1
Exception Type: TypeError
Exception Value:
Field 'mobile' expected a number but got ['22222', '3333'].
While Submitting Form This error occurs.
I am trying to submit form of same name twice simultaneously to same model
Views.py
def page(request):
if request.method == 'POST':
description = request.POST['description']
price = request.POST['price']
name = request.POST.getlist('name')
mobile = request.POST.getlist('mobile')
pay = bill(description=description,price=price)
pay.save()
mypayee = payee(billId=pay,name=name,mobile=mobile)
mypayee.save()
return render(request, 'split_app/page.html')
this model
from django.db import models
# Create your models here.
class bill(models.Model):
price = models.IntegerField()
description = models.CharField(max_length=200)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.description
class payee(models.Model):
billId = models.ForeignKey(bill,on_delete=models.CASCADE,related_name='persons')
name = models.CharField(max_length=50)
mobile = models.IntegerField()
this is image of HTML FORM generated using javascript
enter image description here
** This is how I am submitting data with form having same form twice of same name(name & mobile) **
HTML generate
<div class="container my-3">
<button type="button" class="btn btn-secondary">ADD NEW BILL</button>
<form action="/page" method="POST">
{% csrf_token %}
<div class="input-group mb-3">
<label for="discription" class="col-sm-2 col-form-label">DESCRIPTION:</label>
<div class="col-sm-2">
<input type="text" name="description" id="discription" placeholder="Bill For.." />
</div>
</div>
<div class="input-group mb-3">
<label for="price" class="col-sm-2 col-form-label">BILL PRICE:</label>
<div class="col-sm-2">
<input type="number" name="price" id="price" title="only numbers allowed"
placeholder="&#x20B9" />
</div>
</div>
<div class="mb-3 row">
<label for="person" class="col-sm-2 col-form-label">SPLIT IN:</label>
<div class="col-sm-10">
<button type="button" class="btn btn-info" onclick="increment()">+</button>
<button type="button" class="btn btn-info" id="payeesbtn">ADD PAYEE:</button>
<button type="button" class="btn btn-info" onclick="decrement()">-</button>
<div class="container my-3" id="addpayees"></div>
</div>
</div>
<button type="submit" class="btn btn-info">Save</button>
</form>
</div>
Javascript
let x = 1;
function increment() {
const div = document.createElement('div');
div.className = 'container my-3';
div.idName = 'x';
div.innerHTML = `<h5>payee ${x}</h5>
<table>
<tr>
<th>Name:</th>
<td><input type="text" name="name"></td>
</tr>
<tr>
<th>Mobile:</th>
<td><input type="number" name="mobile"></td>
</tr>
</table>
<input type="button" value="-" onclick="decrement(this)" />
<button type="button" class="btn btn-info" onclick="decrement(this)">-</button>`;
document.getElementById("addpayees").appendChild(div);
x++;
};

The payee.mobile field is defined as an IntegerField, but in your view function you are calling:
mobile = request.POST.getlist('mobile')
which produces a list of values. Then you do this:
mypayee = payee(billId=pay,name=name,mobile=mobile)
That is what the error tells you. You are trying to create a payee instance and assign a list to the integer field.
PS:
If you want to create two separate instances of payee with both those values ['22222', '3333'], you need to do something like:
mypayee1 = payee(billId=pay,name=int(name[0]),mobile=int(mobile[0]))
mypayee2 = payee(billId=pay,name=int(name[1]),mobile=int(mobile[1]))
But I am just guessing here.
PPS:
If the size of the name and mobile lists is dynamic, you could loop over them. You did not provide a lot of context, but I assume that those query parameters in the POST request will have the same number of items, i.e. the lists will be of the same size. Then you could do something like this:
def page(request):
...
names = request.POST.getlist('name')
mobiles = request.POST.getlist('mobile')
pay = bill(description=description,price=price)
pay.save()
for name, mobile in zip(names, mobiles):
mypayee = payee(billId=pay,name=name,mobile=int(mobile))
mypayee.save()
If you don't care about the pre_save and post_save signals, you could create them in bulk like this: (check the docs for caveats!)
def page(request):
...
names = request.POST.getlist('name')
mobiles = request.POST.getlist('mobile')
pay = bill(description=description,price=price)
pay.save()
payee.objects.bulk_create([
payee(billId=pay,name=name,mobile=int(mobile))
for name, mobile in zip(names, mobiles)
])
Either way, at this point I would strongly suggest wrapping the entire affair in a transaction to ensure data integrity.

Related

Objects.filter(id__in=[ids]) "Field 'id' expected a number but got 1,2" JavaScript and Django

Im tring to set categories for my post without a form, with javascript
template:
<form enctype="multipart/form-data" method="POST" action="" accept=".mp4" style="text-align: center;">
{% csrf_token %}
<p style="color: gray; padding-top: 20px;">or</p>
<select name="" id="ms" multiple="multiple">
{% for category in categories%}
<!-- <option type="checkbox" value="{{category}}">{{category}}</option> -->
<input id="category" class="category" catid="{{category.id}}" type="checkbox" value="{{category.id}}">{{category}}</input>
{% endfor %}
</select>
<input type="text" name="title" id="title" placeholder="Title">
<input type="text" name="tags" id="tags" placeholder="Tags: Please separate by comma ','">
<textarea name="description" id="description" cols="30" rows="10" placeholder="Please describe your video..."></textarea>
<div class="form-group">
<label>Select file to upload.</label>
<input type="file" name="file" accept=".mp4" class="form-control" id="fileupload" placeholder="Select file">
</div>
<input type="submit" value="Upload" id="submit" class="btn btn-success">
</form>
js:
var id_categories = [];
var category = document.querySelectorAll("input[type=checkbox]:checked")
for (var i = 0; i < category.length; i++) {
id_categories.push(category[i].value)
}
var formData = new FormData();
formData.append('categories', id_categories)
in my views:
categories_1 = Category.objects.all()
if request.method == 'POST':
categories = request.POST['categories']
FileFolder.save()
tag_list = taggit.utils._parse_tags(tags)
FileFolder.tags.add(*tag_list)
categories_post = Category.objects.filter(id__in=[categories])
if categories_post:
for category in categories_post:
FileFolder.categories.add(category)
return render(request, 'main/create_post.html', {'categories': categories_1})
It returns :
ValueError: Field 'id' expected a number but got '3,4'.
but when i type manually [3,4], it works, any ideas?
Is categories = request.POST['categories'] casting to list?
Probably u have list of string ['3,4']
categories = parse_ids(request.POST['categories'])
def parse_ids(ids: str):
result = []
for id in ids.split(','):
try:
result.append(int(id))
except ValueError:
pass
return result
it looks like it is getting a string '3,4'
instead of numbers or an array of numbers
Edit:see those " (double quotes) marks in "3" means its a string.
in the Js: at line 4 instead of using id_categories.push(category[i].value)
you can use
id_categories.push(parseInt(category[i].value) ) But make sure that input only takes numbers

Putting values from Textboxes into an array

Good Day,
I have created a simple form with three boxes to capture text data. I also have a button that duplicates the form to facilitate multiple entries. I want to be able to take that data and place into 3 arrays, one for each text box.
The code is below:
$(document).ready(function()
{
$("#add").click(function()
{
addThis = "<div class='row mb-3'><div class='col-12'><input type='text' name='fname[]' id='fname' class='form-control' placeholder='First Name'></div></div><div class='row mb-3'><div class='col-12'><input type='text' name='mname[]' id='mname' class='form-control' placeholder='Middle Name'></div></div><div class='row mb-3'><div class='col-12'><input type='text' name='lname[]' id='lname' class='form-control' placeholder='Last Name'></div></div>";
$("#form1").append(addThis);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card" id="form2">
<div class="card-body">
<form action="" id="form1" class="card-body">
<div class="row mb-3">
<div class="col-12">
<input type="text" name="fname[]" id="fname" class="form-control" placeholder="First Name">
</div>
</div>
<div class="row mb-3">
<div class="col-12">
<input type="text" name="mname[]" id="mname" class="form-control" placeholder="Middle Name">
</div>
</div>
<div class="row mb-3">
<div class="col-12">
<input type="text" name="lname[]" id="lname" class="form-control" placeholder="Last Name">
</div>
</div>
</form>
<form action="">
<div class="d-grid gap-2">
<div class="btn-group" role="group">
<button type="button" class="btn btn-primary" id="add">Add Another</button>
<button type="button" name="test" class="btn btn-success">TEST</button>
</div>
</div>
</form>
</div>
I want to eventually submit the data into the table, looping through the arrays for each instance of the form.
Could some one point me in the right direction please?
Heres a possible solution using fieldsets to group your name inputs.
See comments in jQuery JS so you know whats happening...
// our form as const object
const form = $('#form');
// on form submit pass event
$(form).on('submit', function(e) {
// stop event default behaviour
e.preventDefault();
// set entry as serialized array
let entry_arr_obj = $(this).serializeArray();
// set empty object for formatted entry data
let formatted_entry_obj = {};
// for each entry array obj values as key => object
$.each(entry_arr_obj, function(k, obj) {
// split object field name by underscore to create name_fieldset array containing fieldset id and name key
let name_fieldset = obj.name.split('_');
// set the set id from name_fieldset array
let fieldset = parseInt(name_fieldset[1]);
// set name key from name_fieldset array
let name = name_fieldset[0];
// if formatted_entry_obj does not have own property matching current fieldset id
if(!formatted_entry_obj.hasOwnProperty(fieldset)) {
// add fieldset id and empty object to formatted_entry_obj
formatted_entry_obj[fieldset] = {};
}
// add field name and field value to formatted_entry_obj current fieldset object
formatted_entry_obj[fieldset][name] = obj.value;
});
// log our entry object
console.log(formatted_entry_obj);
});
// on form add field set
$(form).on('click', '.add', function(e) {
// get all our fieldsets
let fieldsets = $('fieldset',form);
// last fieldset obj and id
let last_fieldset = fieldsets[fieldsets.length-1];
let last_fieldset_id = parseInt($(last_fieldset).data('set'));
// create new fieldset id
let new_fieldset_id = last_fieldset_id + 1;
// clone last fieldset and filter attributes
$(last_fieldset).clone().filter(function() {
// update data set attribute with new fieldset id
$(this).attr(
'data-set',
new_fieldset_id
// now filter children elements (cols)
).children().filter(function() {
// now filter children elements (inputs)
$(this).children().filter(function() {
// get child element name attr
let name_attr = $(this).attr('name');
// if we have name attr
if(name_attr) {
// explode the name attr value via underscore
let name_fieldset = name_attr.split('_');
// return updated name attribute with new fieldset name and empty value
return $(this).attr(
'name',
name_fieldset[0] + '_' + new_fieldset_id
).val(null);
}
// else return child element
return $(this);
});
// return child element
return $(this);
});
// return all of cloned elem
return $(this);
// then insert after last field set
}).insertAfter(last_fieldset);
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.6.2/dist/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container py-3">
<form id="form">
<fieldset data-set="1" class="form-row mb-3">
<div class="col-sm-4">
<input type="text" name="fname_1" placeholder="First Name" class="form-control form-control-sm" />
</div>
<div class="col-sm-4">
<input type="text" name="mname_1" placeholder="Middle Name" class="form-control form-control-sm" />
</div>
<div class="col-sm-4">
<input type="text" name="lname_1" placeholder="Last Name" class="form-control form-control-sm" />
</div>
</fieldset>
<button type="button" class="add btn btn-sm btn-primary btn-block">Add Fieldset</button>
<button type="submit" class="btn btn-sm btn-success btn-block">Submit</button>
</form>
</div>

Function on form submit works only once [Angular]

I have made a search products app where I have form 3 fields from which I want to search the products. On submission the searchProducts() function is called which sends a get request to my api with request parameters it got from the form fields.
Problem - My form works only once. I can search only once and then I have to refresh the page to search again. Sometimes it works twice but not more than that. I do not know why.
I want to keep calling the searchProducts() function whenever the form is submitted. I want to work it again and again without refreshing the page as a user can search multiple times.
My searchProducts() function / Component -
export class SearchproductComponent implements OnInit {
isAuthenticated(){
return this.userService.isAuthenticated();
}
productSearchForm = this.fb.group({
productCode: [, []],
name: [, []],
brand: [, []],
priceLow: [,[]],
priceHigh: [, []]
})
get productCode(){
return this.productSearchForm.get('productCode');
}
get name(){
return this.productSearchForm.get('name');
}
get brand(){
return this.productSearchForm.get('brand');
}
constructor(private fb: FormBuilder, public productsService: ProductsService, public userService: UserserviceService) { }
ngOnInit(): void {
}
searchProducts(){
let name = this.productSearchForm.controls.name.value!
let brand = this.productSearchForm.controls.brand.value!
let productCode = this.productSearchForm.controls.productCode.value!
if (name && brand === null && productCode === null){
let response = this.productsService.getProductsByName(name)
console.log(response)
}
if (name && brand && productCode === null){
let response = this.productsService.getProductsByNameAndBrand(name, brand)
console.log(response)
console.log("Name and Brand Working");
}
if (name && brand && productCode){
let response = this.productsService.getProductsByNameAndBrandAndProductCode(name, brand, productCode)
console.log(response)
console.log("Name and Brand and Product Code Working")
}
It has more functions but you get the idea.
My searchProducts html file -
<div class="search-form">
<form (ngSubmit)="searchProducts()" [formGroup]="productSearchForm" name="productSearch" class="form-inline">
<div class="row">
<div class="col-4">
<div class="mb-3">
<label for="product-code" class="form-label">Product Code: </label>
<input type="text" class="form-control" id="product-code" name="product-code" formControlName="productCode">
</div>
</div>
<div class="col-4">
<div class="mb-3">
<label for="name" class="form-label">Name: </label>
<input type="text" class="form-control" id="name" name="name" formControlName="name">
</div>
</div>
<div class="col-4">
<div class="mb-3">
<label for="brand" class="form-label">Brand: </label>
<input type="text" class="form-control" id="brand" name="brand" formControlName="brand">
</div></div>
</div>
<div class="row">
<div class="col-2 mb-3">
<button type="submit" class="btn btn-primary mb-3">Search</button>
<button type="button" class="btn btn-warning" (click)="filterAnother()">Search Another</button>
</div>
<div class="col-10 mb-3" *ngIf="isAuthenticated();">
<div class="row">
<div class="col-2">
</div>
<div class="col-2">
<button type="button" class="btn btn-success mb-3" (click)="filterByPrice()">Filter by Price</button>
<button type="button" class="btn btn-primary" (click)="filterAnother()">Filter Another</button>
</div>
<div class="col-2 mu-2">
<label for="price-range" class="form-label price-range-label">Price Range: </label>
</div>
<div class="col-3">
<input type="text" class="form-control" id="price-range-low" name="price-low" formControlName="priceLow">
</div>
<div class="col-3">
<input type="text" class="form-control" id="price-range-high" name="price-high" formControlName="priceHigh">
</div>
</div>
</div>
</div>
</form>
</div>
I want searchProducts() to work again and again. It only works once.
My UI looks like this -
I tried adding another button search another to run function onclick but still does not work.
In your first if function, you are checking if all your inputs are null:
if (name && brand === null && productCode === null)
UPDATE:
You can do the following instead since you only search when there is a name typed in:
if (name !== null && brand === null && productCode === null)
So if you only search nulls, you won't get a response from your service I imagine. You're also doing the same check in the second if, just with a different logic:
if (name && brand && productCode === null)
UPDATE:
You can do the following instead since you are searching whenever there is a name & brand typed in:
if (name !== null && brand !== null && productCode === null)
Your third if function works since you are making sure that all of them exist, with this logic you should be able to search, but only if all 3 inputs have values, you can try in the link below:
if (name && brand && productCode)
I reproduced your code in StackBlitz and it looks like you need to improve your first 2 if statements logic so you can properly search when only one value (or 2) is being passed to angular service. Here is the StackBlitz link if you want to review it: https://stackblitz.com/edit/angular-ivy-ywlaqz?file=src/app/app.component.ts.

Laravel 7 dynamic "add fields" form. foreach() argument must be of type array|object, null given

This my first post here, but by no mean my first time visiting. I'm an amateur coder and I'm working on something that has stumped me for passed day or two...
I'm building a site using Laravel 7. One of the pages includes a dynamic form that allows the user to add addition for fields as needed.
I'm am generating the dynamic form fields and a tinymce editor as well as submitting the form using javascript.
The issue I'm running into is this:
Upon clicking the 'Submit' button the page does not transition or show any signs of having been submitted. The first portion of the form data is successfully submitted and added to the appropriate database table but the dynamic fields are not added to their table and an error is thrown in the browser console.
The believe the relevant issue is message "foreach() argument must be of type array|object, string given" as this seems to be where the code stops running and things go wrong.
This function applies to the dynamic image_id[] portion of the form.
The full error info is:
XHR POST https://www.mydomainname.com/create
[HTTP/1.1 500 Internal Server Error 479ms]
Request:
format "galleries"
title "This+is+the+title+of+the+content"
short "This+is+the+short+description+for+the+content."
thumb "https://www.mydomainname.com/storage/giraffe1.jpg"
category "funny"
image_id […]
0 "Image+1"
1 "Image+2"
2 "Image+3"
Response:
message "foreach() argument must be of type array|object, string given"
exception "ErrorException"
file "/home/user/site/app/Http/Controllers/ContentController.php"
line 149
trace [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
Line 149:
foreach($request->input('image_id[]') as $key => $image) {
This is my Blade View, including the Javascript:
#extends('layouts.app')
#section('title', 'Post New Content')
#section('content')
<script src="https://cdn.tiny.cloud/1/arx09ivbx1ikchqgcvc6558h9sx2crokpd2c1152g667mh0c/tinymce/6/tinymce.min.js"></script>
<script src="/vendor/laravel-filemanager/js/stand-alone-button.js"></script>
<div class="container">
<div class="row">
<div class="col-md-8">
#if (session('status'))
<div class="alert alert-success" role="alert">
{{ session('status') }}
</div>
#endif
<div class="alert alert-danger print-error-msg" style="display:none">
<ul></ul>
</div>
<div class="alert alert-success print-success-msg" style="display:none">
<ul></ul>
</div>
<div class="card shadow">
<h2 class="card-header">
Post a New Gallery
<a class="btn btn-danger" style="float: right" href="{{ url()->previous() }}" onclick="return confirm('Are you sure? All progress will be lost!')">Go Back</a>
</h2>
<div class="card-body">
<form name="add_name" id="add_name">
<input type="hidden" name="format" value="galleries" class="form-control" required>
<div class="form-group row mb-0">
<div class="col-md-12">
<strong>Title:</strong>
<input type="text" name="title" class="form-control" required>
</div>
</div>
<div class="form-group row mb-0">
<div class="col-md-12">
<strong>Description:</strong>
<input type="text" name="short" class="form-control" required>
</div>
</div>
<div class="col-md-12">
<div class="row">
<div class="col-md-6">
<strong>Thumbnail:</strong>
<div class="input-group">
<div class="col-md-10">
<input type="text" id="thumb" class="form-control" name="thumb" aria-label="thumb" aria-describedby="button-image" required>
</div>
<div class="col-md-2">
<div class="input-group-append">
<button class="btn btn-primary" type="button" id="button-image">Browse</button>
</div>
</div>
</div>
</div>
<div class="col-md-6">
<strong>Category: </strong>
<select name="category" class="form-control" required>
<option value="" disabled selected>Select content category...</option>
#foreach($allCategories as $category)
<option value="{{ $category->name }}">{{ ucfirst(trans($category->name)) }}</option>
#endforeach
</select>
</div>
</div>
</div>
<br>
<!-- Dynamic Fields -->
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="image_id[]" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
<!-- End Dynamic Fields -->
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
var postURL = "<?php echo url('create'); ?>";
var i=1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'" class="dynamic-added">' +
'<td><input type="text" name="image_id[]" class="form-control name_list" /></td>' +
'<td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td>' +
'</tr>');
});
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
});
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#submit').click(function(){
$.ajax({
url:postURL,
method:"POST",
data:$('#add_name').serialize(),
type:'json',
success:function(data)
{
if(data.error){
printErrorMsg(data.error);
}else{
i=1;
$('.dynamic-added').remove();
$('#add_name')[0].reset();
$(".print-success-msg").find("ul").html('');
$(".print-success-msg").css('display','block');
$(".print-error-msg").css('display','none');
$(".print-success-msg").find("ul").append('<li>Record Inserted Successfully.</li>');
}
}
});
});
function printErrorMsg (msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display','block');
$(".print-success-msg").css('display','none');
$.each( msg, function( key, value ) {
$(".print-error-msg").find("ul").append('<li>'+value+'</li>');
});
}
});
</script>
<script>
document.addEventListener("DOMContentLoaded", function() {
document.getElementById('button-image').addEventListener('click', (event) => {
event.preventDefault();
window.open('/file-manager/fm-button', 'fm', 'width=1400,height=800');
});
});
// set file link
function fmSetLink($url) {
document.getElementById('thumb').value = $url;
}
</script>
#endsection
And here is my Controller:
public function createPost(Request $request)
{
$post = new Content();
$post->title = $request->get('title');
$post->short = $request->get('short');
$post->long = $request->get('long');
$post->thumb = $request->get('thumb');
$post->format = $request->get('format');
$post->category = $request->get('category');
$post->author = Auth::user()->id;
$post->save();
$order = 0;
foreach($request->input('image_id[]') as $key => $content) {
$contentImg = new ContentImages();
$contentImg->content_id = $post->id;
$contentImg->image_id = $content->image_id;
$contentImg->image_order = $order+1;
$contentImg->save();
}
return response()->json(['success'=>'done']);
}
And, finally, my Routes:
Route::get("create","ContentController#create");
Route::post("create","ContentController#createPost");
Things I Have Tried
I've tried several variations of the image_id syntax and nothing seems to be working...
As posted above:
foreach() argument must be of type array|object, null given
Using $request->input('image_id'):
"Attempt to read property \"image_id\" on string"
I tried $request('image_id') and got:
Object of type Illuminate\Http\Request is not callable
Then I tried $request->input(['image_id']) which just gave
foreach() argument must be of type array|object, null given
The output from dd($request->input('image_id') is:
array:2 [
0 => "Name 1"
1 => "Name 2"
]
and dd($request->input('image_id[]')) gave null.
Output of dd($request->all()):
array:6 [
"format" => "galleries"
"title" => "Thoughtless Driver Ruins Everyone's Day at the Wildlife Park"
"short" => "This lady made a mess at the West Midland Safari Park. The Giraffe was not injured."
"thumb" => "https://www.mydomainname.com/storage/photos/1/6317a2b460c98.jpg"
"category" => "oops"
"image_id" => array:3 [
0 => "Name 1"
1 => "Name 2"
2 => "Name 3"
]
]
I'm really lost on this one.
Any guidance here would be GREATLY appreciated, as well as any recommendations on better ways to handle this scenario.
I'm a marginally talented amateur with this stuff but nowhere near expert and I'm always looking to learn.
Much thanks in advance!!
SMR
Okay, so I figured out what I was doing wrong.
$request->input('image_id') was the correct solution.
My issue was further down. Once I corrected to $request->input('image_id'), this lead to another error, "Attempt to read property \"image_id\" on string", but this was actually due to a syntax error further down the page.
Fixed that, and all is now well!
Thank you to those who helped!

How I can send a form POST from a jQuery datepicker

I have this form:
<div role="tabpanel" class="tab-pane" id="xcell">
<div class = "row">
<div class = "col-md-7">
<form method = "POST" action = "<?php echo base_url('Usercontroller/getXcell') ?>">
<div class="form-group">
Start: <input id ="startdate" type ="text" size = "8"/>
</div>
<div class="form-group">
Sfarsit: <input id ="enddate" type ="text" size = "8"/>
</div>
<button type="submit" class="btn btn-default btn-success">Genereaza xcell</button>
</form>
</div>
</div>
</div>
And this is the javascript calendar:
$(document).ready(function(){
$('#startdate').datepicker({
startdate : $(this).val()
});
$('#enddate').datepicker({});
});
I was trying with this startdate : $(this).val(), but it will give a empty result. This is the function where I send data:
public function getXcell() {
$data= $this->input->post();
var_dump($data);
}
I'm using codeigniter, I want to send the inputs that are selected in Start and Sfarsit to my php function to work with. Thanks
You forgot to add name attribute in your form fields
<div class="form-group">
Start: <input id ="startdate" type ="text" size = "8" name="startdate"/>
</div>
<div class="form-group">
Sfarsit: <input id ="enddate" type ="text" size = "8" name="enddate" />
</div>

Categories

Resources