I cannot get the uploaded file returned using codeignter3 fileupload() - file-upload

I have the following code for file upload in the corresponding model file of codeigniter3.
$config['upload_path'] = './assets/img/report/';
$config['allowed_types'] = 'txt|odt|jpg|png|jpeg|pdf|docx';
$config['file_name'] = $this->id;
$config['overwrite'] = true;
$config['max_size'] = '150000';
$this->load->library('upload', $config);
if ($this->upload->do_upload('file')) {
return $this->upload->data('file_name');
}
return default.jpg;
The corresponding view file has the following code
<div class="form-group">
<label for="file">Attachment</label>
<input class="form-control-file"
type="file" name="file" />
<div class="invalid-feedback">
<?php echo form_error('file') ?>
</div>
</div>
But the code always returns default.jpg. How can I fix to return the uploaded file correctly. I use CI3 in Debian 11 running xampp8.1

**Configure your upload path**
After upload this will send you upload data or the upload error
$config = array(
'upload_path' => "./assets/img/report/",
'allowed_types' => "gif|jpg|png|jpeg|pdf",
'overwrite' => TRUE,
'max_size' => "2048000",
'max_height' => "768",
'max_width' => "1024"
);
$this->load->library('upload', $config);
if($this->upload->do_upload())
{
$data = array('upload_data' => $this->upload->data());
return $data;
}
else
{
$error = array('error' => $this->upload->display_errors());
}
}

Related

405 Method Not Allowed response: { "message": "The GET method is not supported for this route. Supported methods: POST."}

I created an API with tymon/jwt-auth, I test it on POSTMAN and it works very well, but when I want to consume it with Guzzle I encountered this error :
GuzzleHttp\Exception\ClientException Client error: POST http://localhost/project/public/api/stands/1/images2/ resulted in a
405 Method Not Allowed response: { "message": "The GET method is not
supported for this route. Supported methods: POST.", "exception":
"Symfony\ (truncated...)
Route for API :
Route::post('stands/{id}/images2', 'ImageController#store');
Controller ImageController.php for API :
public function store(Request $request, $id) {
$validator = Validator::make($request->all(),
[
'nom' => 'required|mimes:jpeg,png'
]);
if ($validator->fails()) {
return response()->json(['error'=>$validator->errors()], 401);
}
if ($files = $request->file('nom'))
{
$path = public_path() . '/images/';
$files->move($path, $files->getClientOriginalName() );
$image = new Image();
$image->nom = $files->getClientOriginalName();
// $image->stand_id= $request->stand_id;
$stand = $this->user->stands()->find($id);
if ($stand->images()->save($image)){
return response()->json([
'success' => true,
"message" => "File successfully uploaded"
]);
$image->save();
}
else{
return response()->json([
'success' => false,
'message' => 'Sorry, image could not be added'
], 500);
}
}
}
Form :
<form method="POST" enctype="multipart/form-data" action="{{ route('postImage',request()->route('id')) }}">
{{ csrf_field() }}
{{ method_field("post")}}
<!--begin::Card-->
<div class="card card-custom gutter-b example example-compact">
<div class="card-header">
<div class="card-title">
<h3 class="card-label">
Upload
</h3>
</div>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-6 mx-auto">
<div class="box-browse" >
<div class="custom-file">
<input type="file" name="nom" class="custom-file-input" id="inputGroupFile01">
</div>
<div class="content-upload">
<i class="fa fa-download" aria-hidden="true"></i>
</div>
<span class="form-text text-muted">Allowed file types: png, jpg,
jpeg.</span>
<!-- <div class="custom-file">
<label class="custom-file-label" for="customFile">Choose
file</label>
</div> -->
</div>
</div>
</div>
</div>
</div>
<!--end::Card-->
<input type="submit" name="submit" value="ok" />
</form>
Controller Admin\ImageController.php that consumes API for upload file :
public function store(Request $request, $id){
$file = $request->file('nom');
$file_path = $file->getPathname();
$file_mime = $file->getMimeType('image');
$file_uploaded_name = $file->getClientOriginalName();
$url = "http://localhost/project/public/api/stands/".$id."/images2/";
$client = new \GuzzleHttp\Client();
try {
$response = $client->post($url,
[
'multipart' => [
[
'name' => 'nom',
'filename' => $file_uploaded_name,
'Content-Type' => 'multipart/form_data',
'contents' => fopen($file_path, 'r'),]
],
'headers' =>
[
'Authorization' => 'Bearer '.Session::get('token'),
'Accept' => 'application/json',
'Content-Type' => 'multipart/form_data',
]
]);
} catch (Exception $e) {
}
the route :
Route::post('/stands/{id}/images2/', 'Admin\ImageController#store')->name('postImage');

Prestashop after submit return page html

Hello I develop a module under Prestashop 1.6 and I am blocked on the submission of a form.
I add in my module a form with the hook "DisplayAdminOrderContentShip" which retrieves a tpl hook_button.tpl which displays my form (button)
relance
here is my tpl:
<div class="panel panel-default">
<div class="panel-heading">
<p>Export commande mecalux</p>
</div>
<div class="panel-body">
<p>Permet de relancer l'export vers Mecalux de la commande</p>
<form method="POST" action="#">
<button type="submit" value="1" id="exportordersubmit" name="exportordersubmit" class="btn btn-default pull-right">
<i class="process-icon-refresh"></i> {l s='Relancer l\'export' mod='exportorders'}
</button>
</form>
</div>
Here is my function:
public function hookDisplayAdminOrderContentShip($params)
{
$order = new Order(Tools::getValue('id_order'));
$status = (int)Configuration::get('EXPORTORDERS_STATUS_TRANSFERED_TO_WMS');
$statusError = (int)Configuration::get('EXPORTORDERS_STATUS_CMD_ERROR');
if (Tools::isSubmit('exportordersubmit')) {
if (isset($order) && (int)$order->valid == 1) {
if ($order->current_state != $status && $order->current_state != $statusError) {
return;
}
if (!$order->valid) {
return;
}
$customer = $order->getCustomer();
$deliveryAddress = new Address($order->id_address_delivery);
$id_country_delivery = $deliveryAddress->getCountryAndState($order->id_address_delivery);
$iso = new Country();
$userXml = [
'id_client' => $customer->id,
'email' => $customer->email,
'livraison' => $deliveryAddress,
'country_code_delivery' => $iso->getIsoById($id_country_delivery['id_country'])
];
$dateOrder = new DateTime($order->date_add);
$orderXml = [
'id' => $order->id,
'sorCode' => $order->reference,
'payment' => $order->payment,
'date' => $dateOrder->format('Y-m-d\TH:i:s') . 'Z',
];
$result = $this->fileXml($userXml, $orderXml, $order->getProducts());
if ((int)$result === 1) {
$order->setCurrentState($statusError, (int)$this->context->employee->id ? (int)$this->context->employee->id : 0);
$html = [
'message' => $this->displayError('Erreur de transmission au WMS'),
];
} else {
if ((int)$order->current_state !== (int)$status) {
$order->setCurrentState($status, (int)$this->context->employee->id ? (int)$this->context->employee->id : 0);
$order->wms_transfered = 1;
$order->save();
$html = [
'message' => $this->displayConfirmation('Transmise au WMS'),
];
}
}
}
}
$this->context->smarty->assign(
array(
'alert' => $html
)
);
return ($this->display(__FILE__, 'views/templates/hook/hook_button.tpl'));
}
and when I click here is the result of my page:
html
normally it should return an alert in the order detail page (admin) I do not see where my problem comes from have any idea?
Thank you for your help.
fetch

Laravel - dropbox driver - This driver does not support retrieving URLs

Using
Laravel 5.7
I'm trying to use dropbox driver to upload images , it works .. but when i want to get the url .. it gives me an error
This driver does not support retrieving URLs
filesystems.php
'disks' => [
'dropbox' => [
'driver' => 'dropbox',
'app_secret' => env('DROPBOX_APP_SECRET'),
'token' => env('DROPBOX_TOKEN'),
],
],
UploadController.php
public function postUpload(Request $request)
{
$user = Auth::user();
$file = $request->file('picture');
$filename=uniqid($user->id."_").".".$file->getClientOriginalExtension();
Storage::disk('dropbox')->put($filename, File::get($file), 'public');
$url = Storage::disk('dropbox')->url($filename);
$user->profile_pic = $url;
$user->save();
$user->profile_pic = $filename;
$user->save();
return view('upload-complete')->with('filename', $filename)->with('url',$url);
}
upload-complete.blade.php
#extends('template')
#section('content')
<div class="container">
<h1>File Uploaded</h1>
<hr />
<div class="text-center">
<img src="{{ $url }}" class="img-rounded" />
</div>
</div>
#endsection

Symfony 3 form + Aurelia

So i've playing around with building a web app in Symfony 3, using a form type and rendering the form on the page. I am starting to Aurelia, and am trying to render a Symfony form on the page via an Aurelia custom element, and then post the form back to symfony. I've gotten to the point of validating the form upon submit, but it never validates. Can someone please look over the below code and see if i'm missing something somewhere?
Form type:
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\OptionsResolver\OptionsResolver;
use AppBundle\Service\PayeeService;
class PayeeType extends AbstractType
{
/**
* #param FormBuilderInterface $builder
* #param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('name', TextType::class)
->add('category', ChoiceType::class, [
'choices' => [
'Uncategorized' => PayeeService::CATEGORY_UNCATEGORIZED,
'Installment Loan' => PayeeService::CATEGORY_INSTALLMENT_LOAN,
'Credit Card' => PayeeService::CATEGORY_CREDIT_CARD,
'Utility' => PayeeService::CATEGORY_UTILITY,
'Mortgage' => PayeeService::CATEGORY_MORTGAGE,
'Entertainment' => PayeeService::CATEGORY_ENTERTAINMENT
],
'choices_as_values' => true
])
->add('amount', MoneyType::class, ['currency' => 'USD', 'grouping' => true])
->add('frequency', ChoiceType::class, [
'choices' => [
'Recurring' => PayeeService::FREQUENCY_RECURRING,
'One-time' => PayeeService::FREQUENCY_ONETIME
],
'choices_as_values' => true
])
->add('method', ChoiceType::class, [
'choices' => [
'ACH' => PayeeService::PAY_METHOD_ACH,
'Check' => PayeeService::PAY_METHOD_CHECK
],
'choices_as_values' => true
])
->add('dateLastPaid', DateType::class)
->add('dueDate', DateType::class)
->add('gracePeriod', IntegerType::class)
->add('balance', MoneyType::class, ['currency' => 'USD', 'grouping' => true])
->add('active', CheckboxType::class, ['label' => 'Active', 'data' => true])
->add('save', SubmitType::class, ['label' => 'Save Payee'])
;
}
/**
* #param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Payee'
));
}
}
Controller:
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
class FormController extends Controller
{
/**
* #Route("/_form/entity/{entity}", name="new_entity_form")
* #Method("GET")
*/
public function getFormForNewEntity(Request $request)
{
$rawName = $request->get('entity');
$content = $request->getContent();
$data = json_decode($content, true);
$formName = strtolower($rawName) . "_form";
$submitFunction = $data['submitFunction'];
$entityName = "AppBundle\Entity\\" . $rawName;
$entity = new $entityName();
$form = $this->createForm("\AppBundle\Form\\{$rawName}Type", $entity);
return $this->render('form/form.html.twig', [
'name' => $formName,
'form' => $form->createView(),
'submitFunction' => $submitFunction]);
}
/**
* #Route("/_form/entity/{entity}", name="new_entity_create")
* #Method("POST")
*/
public function saveFormForNewEntity(Request $request)
{
$em = $this->getDoctrine()->getManager();
$rawName = $request->get('entity');
$entityName = "AppBundle\Entity\\" . $rawName;
$entity = new $entityName();
$form = $this->createForm("\AppBundle\Form\\{$rawName}Type", $entity);
$form->handleRequest($request);
if ($form->isValid()) {
$em->persist($entity);
$em->flush();
return new JsonResponse(['result' => true]);
} elseif ($form->isEmpty()) {
return new JsonResponse(['result' => false, 'errors' => 'form empty']);
} else {
return new JsonResponse(['result' => false, 'errors' => iterator_to_array($form->getErrors(true))]);
}
}
}
Form twig:
{{ form_start(form, {'attr': {'id':name, 'role':'form', 'submit.delegate':submitFunction}}) }}
{{ form_widget(form) }}
{{ form_end(form) }}
Aurelia component js:
import {InlineViewStrategy} from 'aurelia-framework';
import {customElement, bindable, inject} from 'aurelia-framework';
import $ from 'jquery';
import {HttpClient} from 'aurelia-http-client';
import 'fetch';
#customElement('symfony-form')
#inject(Element)
export class SymfonyForm {
#bindable entity;
constructor(element) {
this.content = '';
this.http = new HttpClient();
this.http.configure(config => {
config
.withBaseUrl('http://localhost:8000/');
});
this.element = element;
}
bind(binding, override) {
return this.http.get('_form/entity/' + this.entity, {'submitFunction': 'submit()'})
//.then(response => response.html())
.then(response => {
this.content = response.response;
});
}
submit() {
// application/x-www-form-urlencoded
this.http.createRequest('_form/entity/' + this.entity)
.withHeader('Content-Type', 'application/x-www-form-urlencoded')
.asPost()
.withContent($(this.element).find('form').serialize())
.send()
.then(response => {
alert(response.response);
});
//alert('submitted ' + this.entity);
// return this.http.post('_form/entity/' + this.entity, $(this.element).find('form').serialize())
// .then(response => {
// alert(response.response);
// });
}
}
aurelia component view:
<template>
<form role="form" submit.delegate="submit()">
<div innerHTML.bind="content"></div>
</form>
</template>
aurelia page:
<template>
<require from="form"></require>
<section class="au-animate">
<h2>${heading}</h2>
<form role="form" submit.delegate="submit()">
<div class="form-group">
<label for="fn">First Name</label>
<input type="text" value.bind="firstName" class="form-control" id="fn" placeholder="first name">
</div>
<div class="form-group">
<label for="ln">Last Name</label>
<input type="text" value.bind="lastName" class="form-control" id="ln" placeholder="last name">
</div>
<div class="form-group">
<label>Full Name</label>
<p class="help-block">${fullName | upper}</p>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
<symfony-form entity="Payee"></symfony-form>
</section>
</template>
I'm not an expert on SPAs, or JS frameworks, but from what I can see the problem is the lack of a CSFR field with the correct token and also that I don't believe your inputs are named correctly for symphony to read them correctly (I may have missed where this is handled so apologies if so). You need to have the input name formatted as below:
<input type="text" name="formname[formfield]" />
So for example I believe you need your name field to be:
<input type="text" name="payeetype[name]" />

Yii 2.0 hidden field value not modifiable using javascript

In my model I have a hidden field.I am modifying its value using javascript (jQuery).But when I submit the form to model, it still contains its initial value instead of values modified via javascript.I have checked whether javascript is modifying the values, and is confirmed that values are being modified.But when form is submitted it is sending initial values.
Code is given below
<?php
/*Model -- wrong_answers is my hidden field*/
namespace app\models;
use yii;
use yii\db;
use yii\base\Model;
use yii\web\UploadedFile;
class QuestionModel extends Model
{
public $quiz_id = null;
public $question = '';
public $choices = '';
public $explanation ="";
public $hints = array();
public $correct_answer = "";
public $wrong_answers = '{}';//when populating from already entered data use {"a":"as"} format instead of {'a':'as'}
public $wrong_answer = "";
public function rules()
{
return [
[['quiz_id'], 'safe'] ,
[['question'], 'required'] ,
[['correct_answer'], 'required'] ,
[['wrong_answers'], 'safe'] ,
[['wrong_answer'], 'safe'] ,
[['explanation'],'required']
];
}
public function get_quiz($quiz_id) {
$ret = array();
$command = Yii::$app->db->createCommand("CALL get_quiz(:qz_id)");
$command->bindParam(":qz_id", $this->quiz_id);
$result = $command->queryAll();
if(sizeof($result) > 0) {
$ret = $result[0] ;
}
return $ret;
}
public function save_question() {
$ret = false;
//echo "quiz- id is ".$this->quiz_id;
$quiz_details = $this->get_quiz($this->quiz_id);
if(sizeof($quiz_details)) {
$quiz_data = $quiz_details['quiz_data'];
$quiz_data = json_decode($quiz_data);
$choices = [];
echo $this->wrong_answers;
exit;
$wrong_answers_array = json_decode($this->wrong_answers);
if($this->wrong_answer)
array_push($wrong_answers_array, $this->wrong_answer);
print_r($wrong_answers_array);
exit;
foreach($wrong_answers_array as $wr_ans) {
array_push($choices,array('choice'=>$wr_ans));
}
$question_data = array('question'=>$this->question,'explanation'=>$this->explanation,'choices'=>$choices);
$ret = false;
}
return $ret;
}
public function getHint($key) {
return $this->hints[$key];
}
}
Controller - actionAdd_question is the action
<?php
namespace app\controllers;
use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\filters\VerbFilter;
use app\models\QuizModel;
use app\models\QuestionModel;
use yii\web\UploadedFile;
global $username;
class QuizController extends Controller
{
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['#'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'logout' => ['post'],
],
],
];
}
public function actions()
{
return [
'error' => [
'class' => 'yii\web\ErrorAction',
],
'captcha' => [
'class' => 'yii\captcha\CaptchaAction',
'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
],
];
}
public function actionEntry()
{
}
public function actionView_all() {
$request = Yii::$app->request;
$layout_params=array(
'username'=>'admin',
'sidebar_menu1_class' =>'active',
'sidebar_menu12_class' =>'active',
'dash_title' => 'Courses',
'dash_sub_title'=>'View all'
);
$message = '';
$data = array();
$layout_params['scripts'] = array("view-all-modules.js");
/*$model = new ViewAllCompaniesModel();
$pagination_data = $model->getTotalCompanies();
$layout_params['js_variables'] = array(
'totalCompanyPages'=>$pagination_data['total_page_count'],
'csrfToken' => "'".$request->csrfToken."'" ,
'csrfTokenName' => "'".$request->csrfParam."'"
);
*/
return $this->render('view-all-modules', [
'layout_params'=>$layout_params,
'message' =>$message,
'data' =>$data
]);
}
public function actionAdd() {
$layout_params=array(
'username'=>'admin',
'sidebar_menu1_class' =>'active',
'sidebar_menu12_class' =>'active',
'dash_title' => 'Quiz',
'dash_sub_title'=>'Add new quiz'
);
$message = array();
$request = Yii::$app->request;
$proceed = true;
$parent_course_id = null;
$req_params = $_POST;
$layout_params['scripts'] = array("add-quiz.js");
$model = new QuizModel();
if(!$model->quiz_id) {
if ($model->load($request->post()) && $model->validate()) {
$params = $request->post();
$model->save_quiz();
$message['title'] = 'Wow !';
$message['body'] = 'Successfully added quiz '.$model->quiz_title;
} else {
}
} else {
}
return $this->render('add-quiz', ['model' => $model,
'layout_params'=>$layout_params,
'message' =>$message
]);
//return $this->render('add-company',$data);
}
public function actionSave() {
//print_r($_POST);
}
public function actionAdd_question() {
print_r($_POST);
$layout_params=array(
'username'=>'admin',
'sidebar_menu1_class' =>'active',
'sidebar_menu12_class' =>'active',
'dash_title' => 'Quiz',
'dash_sub_title'=>'Add question'
);
$request = Yii::$app->request;
$message = array();
$layout_params['scripts'] = array("add-question.js");
$model = new QuestionModel();
if($request->get('q_id')) {
$model->quiz_id = $request->get('q_id');
if ($model->load($request->post()) && $model->validate()) {
$model->save_question();
} else {
echo "yo yo";
}
return $this->render('add-question', ['model' => $model,
'layout_params'=>$layout_params,
'message' =>$message
]);
} else {
}
}
public function actionIndex()
{
$data = array(
'layout_params'=>array(
'username'=>'admin',
'sidebar_menu11_class' =>'active'
)
);//
}
public function actionLogout()
{
Yii::$app->user->logout();
return $this->goHome();
}
}
View
/*Assigning the parameters to be accessible by layouts*/
foreach($layout_params as $layout_param => $value) {
$this->params[$layout_param] = $value;
}
?>
<div class="form-group">
</div>
<div class="col-md-12">
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title">Add Question</h3>
</div><!-- /.box-header -->
<!-- form start -->
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<input type = 'hidden' id = 'test' name = 'test' />
<div class="box-body">
<?php if(isset($message)&&sizeof($message)): ?>
<div class="form-group">
<div class="callout callout-info alert-dismissible">
<h4><?php if(isset($message['title']))echo $message['title'];?></h4>
<p>
<?php if(isset($message['body']))echo $message['body'];?>
</p>
</div>
</div>
<?php endif;?>
<div class="form-group">
<?= $form->field($model, 'question')->textInput(array('class'=>'form-control')); ?>
</div>
<div class="form-group">
<?= $form->field($model, 'correct_answer')->textInput(array("class"=>"form-control",'id'=>'correct_answer')); ?>
<?= Html::activeHiddenInput($model, 'wrong_answers',array('id'=>'wrong_answers')) ;?>
<?= Html::activeHiddenInput($model, 'quiz_id',array('id'=>'quiz_id')) ;?>
</div>
<div class="form-group">
<?= $form->field($model, 'wrong_answer')->textInput(array("class"=>"form-control ",'id'=>'wrong_answer')); ?>
<button id = 'add-answer' type = "button">Add Another</button>
<?= Html::activeHiddenInput($model, 'wrong_answers',array('id'=>'wrong_answers')) ;?>
<?= Html::activeHiddenInput($model, 'quiz_id',array('id'=>'quiz_id')) ;?>
</div>
<div class="form-group" id ='wrong-group'>
<h3>Wrong Answers</h3>
<!-- The following dummy html is used for generating html inside javascript -->
<ul class="edit-list-dummy" id ="edit-list-dummy">
<li> <button class="btn btn-danger" id = 'dummy-wrong-ans-delete' onClick = "deleteWrongAnswer(this.name)" type ="button">Delete</button> <span id ='dummy-wrong-answer'>Hello I am a wrong answer here</span>
</ul>
<ul class="edit-list" id = 'wrong-answers'>
</ul>
</div>
<div class="form-group">
<?= $form->field($model, 'explanation')->textArea(array("class"=>"form-control",'id'=>'explanation')); ?>
</div>
</div><!-- /.box-body --> <div class="box-footer">
<?= Html::submitButton('Save Question', ['class' => 'btn btn-primary','onclick'=>'this.preventDefault']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
</div>
Javascript -#wrong_answers is my hidden input id
var wrongAnswers = {};//{1:answer1,2:answer2...};
var randCount = 0;//radom count for setting as wrongAnswers attribute
//initialise wrong answers json from database
$(document).ready(function() {
console.log($('#wrong_answers').val());
wrongAnswers = jQuery.parseJSON($('#wrong_answers').val());
console.log(wrongAnswers);
$('#add-answer').click(function() {
var wrongAns = $('#wrong_answer').val().trim();
if(wrongAns) {
wrongAnswers[randCount] = wrongAns;
randCount++;
generateWrongAnswers();
$('#wrong_answer').val("");
// alert($('#wrong_answers').val());
}
});
generateWrongAnswers();
});
function generateWrongAnswers() {
$('#wrong-group').hide();
var html = '';
for(var wrongIdx in wrongAnswers) {
//console.log("w is ".wrongAnsIdx);
$('#dummy-wrong-answer').html(wrongAnswers[wrongIdx]);
$('#dummy-wrong-ans-delete').attr('name',wrongIdx);
html += $('#edit-list-dummy').html();
}
if(html) {
$('#wrong-group').show();
$('#wrong-answers').html(html);
}
var jsonData = JSON.stringify(wrongAnswers);
$('#wrong_answers').val(jsonData);
// $('#test').val(jsonData);
//$('#correct_answer').val("Mallu");
// alert($('#wrong_answers').val());
}
function deleteWrongAnswer(idx) {
delete wrongAnswers[idx];
generateWrongAnswers() ;
}
Finall solved it. The issue is that, I accidentally included two hidden input fields with same id.Removed one and solved