Ajax to php retrieving formdata - javascript

I'm sending my files through vue.js to my laravel backend but I'm not able to retrieve the data correctly.
Vue.js :
<b-form-file
v-model="files"
:state="Boolean(files)"
placeholder="Choisissez un fichier..."
drop-placeholder="Glisser ici..."
multiple
accept=".jpg, .png"
class="textOverflow"
name="file[]"
></b-form-file>
Ajax :
onSubmit(){
let formData = new FormData();
for( var i = 0; i < this.files.length; i++ ){
let file = this.files[i];
formData.append("filePos: "+ i, file, this.id);
}
axios.post('/pictures', formData,
{headers: {'Content-Type': 'multipart/form-data'} })
.then((res) => {
console.log(res);
})
.catch((err) => {
console.log(err);
});
}
Laravel php :
public function store(Request $request)
{
$images = $request->all();
info($images);
}
So this gives me :
[2020-04-26 15:40:48] local.INFO: array (
'filePos:_0' =>
Illuminate\Http\UploadedFile::__set_state(array(
'test' => false,
'originalName' => '25',
'mimeType' => 'image/png',
'error' => 0,
'hashName' => NULL,
)),
)
[2020-04-26 15:40:50] local.INFO: array (
'filePos:_0' =>
Illuminate\Http\UploadedFile::__set_state(array(
'test' => false,
'originalName' => '25',
'mimeType' => 'image/png',
'error' => 0,
'hashName' => NULL,
)),
)
Which is perfect, but I can't retrieve specific data like if I just want the originalName and do ->request('name'), I can the weird chain of characters as if I wasn't the correct encoding.
Does someone know how to retrieve specific information for separating the images, manipulate them and so.
Thanks for reading
Edit :
If I use dd instead of info :
array:1 [
"filePos:_0" => Illuminate\Http\UploadedFile {#343
-test: false
-originalName: "25"
-mimeType: "image/png"
-error: 0
#hashName: null
path: "C:\Users\Gian\AppData\Local\Temp"
filename: "phpEC28.tmp"
basename: "phpEC28.tmp"
pathname: "C:\Users\Gian\AppData\Local\Temp\phpEC28.tmp"
extension: "tmp"
realPath: "C:\Users\Gian\AppData\Local\Temp\phpEC28.tmp"
aTime: 2020-04-26 16:28:39
mTime: 2020-04-26 16:28:39
cTime: 2020-04-26 16:28:39
inode: 35184372088948345
size: 109758
perms: 0100666
owner: 0
group: 0
type: "file"
writable: true
readable: true
executable: false
file: true
dir: false
link: false
linkTarget: "C:\Users\Gian\AppData\Local\Temp\phpEC28.tmp"
}
]

Related

Javascript fetch method failing

So I am trying to call an api using the javascript fetch method. But it keeps failing.
I am trying to call this api this way:
const addressReq = await fetch(`https://vapi.verifyme.ng/v1/verifications/addresses`, {
headers:{
'Authorization':`Bearer ${AllKeys.verifyNINKey}`,
'Content-Type': 'application/json'
},
method:'POST',
body:{
'reference':`${id}`,
'city':`${city}`,
'state':`${state}`,
'landmark':`${city} ${estate && estate + ' estate'}`,
'lga': `${lga}`,
'street':`${street_number} ${street_name} ${estate} ${city}`,
"applicant.firstname" : `${displayName}`,
"applicant.lastname" : `${lastName}`,
"applicant.dob" : `${rows.birth_info}`,
"applicant.phone" : `${number}`,
"applicant.idType" : 'KYC',
"applicant.idNumber" : `${number}`,
// "applicant.firstname" : `${displayName}`,
// "applicant": {
// 'firstname':`${displayName}`,
// 'lastname':`${lastName}`,
// 'dob':`${rows.birth_info}`,
// 'phone':`${number}`,
// 'idType':'KYC',
// 'idNumber':`${number}`,
// }
}
}).then(async(res) => {
console.log(await res.json())
dispatch({ type:'UPDATE_STATUS',payload: {status:'guarantor'} })
}).catch(err => console.log(err))
But it doesn't work. I keep getting a 400 error
Object {
"error": "Bad Request",
"message": Array [
"applicant should not be null or undefined",
"state should not be empty",
"state must be a string",
"street should not be empty",
"street must be a string",
"lga should not be empty",
"lga must be a string",
],
"statusCode": 400,
}
But when I use postman it works.
I have also added a webhook on pipedream and I do not receive that either to prove it doesn't work.
I have tried everything possible but no positive feedback. Is there any thing I'm doing wrong?
Thanks to #Barmar all I needed to do was add JSON.stringify()
Outcome:
const addressReq = fetch(`https://vapi.verifyme.ng/v1/verifications/addresses`, {
headers:{
'Authorization':`Bearer ${AllKeys.verifyNINKey}`,
'Content-Type': 'application/json'
},
method:'POST',
body:JSON.stringify({
'reference':`${id}`,
'city':`${city}`,
'state':`${state}`,
'landmark':`${city} ${estate && estate + ' estate'}`,
'lga': `${lga}`,
'street':`${street_number} ${street_name} ${estate} ${city}`,
"applicant.firstname" : `${displayName}`,
"applicant.lastname" : `${lastName}`,
"applicant.dob" : `${rows.birth_info}`,
"applicant.phone" : `${number}`,
"applicant.idType" : 'KYC',
"applicant.idNumber" : `${number}`,
// "applicant.firstname" : `${displayName}`,
// "applicant": {
// 'firstname':`${displayName}`,
// 'lastname':`${lastName}`,
// 'dob':`${rows.birth_info}`,
// 'phone':`${number}`,
// 'idType':'KYC',
// 'idNumber':`${number}`,
// }
})
}).then((res) => {
console.log(res.json())
dispatch({ type:'UPDATE_STATUS',payload: {status:'guarantor'} })
}).catch(err => console.log(err))
You don't have to use asynch and await here, removed them, try again, should work
const addressReq = fetch(`https://vapi.verifyme.ng/v1/verifications/addresses`, {
headers:{
'Authorization':`Bearer ${AllKeys.verifyNINKey}`,
'Content-Type': 'application/json'
},
method:'POST',
body:{
'reference':`${id}`,
'city':`${city}`,
'state':`${state}`,
'landmark':`${city} ${estate && estate + ' estate'}`,
'lga': `${lga}`,
'street':`${street_number} ${street_name} ${estate} ${city}`,
"applicant.firstname" : `${displayName}`,
"applicant.lastname" : `${lastName}`,
"applicant.dob" : `${rows.birth_info}`,
"applicant.phone" : `${number}`,
"applicant.idType" : 'KYC',
"applicant.idNumber" : `${number}`,
// "applicant.firstname" : `${displayName}`,
// "applicant": {
// 'firstname':`${displayName}`,
// 'lastname':`${lastName}`,
// 'dob':`${rows.birth_info}`,
// 'phone':`${number}`,
// 'idType':'KYC',
// 'idNumber':`${number}`,
// }
}
}).then((res) => {
console.log(res.json())
dispatch({ type:'UPDATE_STATUS',payload: {status:'guarantor'} })
}).catch(err => console.log(err))

trying to store image from vue form and send to backend laravel

I'm a newbie and i'm trying to create a rest project with Vue and Laravel and I have a form that allows to send an image, but when I try to store it in the db, I got an error:
"Request failed with status code 422"
and
"The image must be an image"
I can't figure how to solve it, any suggestion?
<script>
export default {
data() {
return {
title: undefined,
year: undefined,
director: undefined,
plot: undefined,
rating: undefined,
image: null,
};
},
methods: {
insertedFile(e) {
this.image = e.target.files[0];
},
addFilm() {
const formData = new FormData;
formData.set('image', this.image)
console.log(formData.get('image'));
//
axios
.post("/api/films", {
title: this.title,
year: this.year,
director: this.director,
plot: this.plot,
rating: this.rating,
image:formData
})
.then((response) => {
console.warn(response)
});
},
},
};
</script>
<template>
<form #submit.prevent="addFilm()" enctype="multipart/form-data" method="post">
<input type="text" name="title" placeholder="title" v-model="title" />
<input type="number" name="year" placeholder="year" v-model="year" />
<input
type="text"
name="director"
placeholder="director"
v-model="director"
/>
<input type="text" name="plot" placeholder="plot" v-model="plot" />
<input
type="number"
name="rating"
placeholder="rating"
v-model="rating"
/>
<input
type="file"
name="image"
id="image"
#change="insertedFile($event)"
/>
<button type="submit">Submit</button>
</form>
</template>
Controller:
public function store(Request $request)
{
$request->validate([
'title' => 'required',
'year' => 'required',
'plot' => 'required',
'director' => 'required',
'rating' => 'required',
'image' => 'image|mimes:jpg,png,jpeg,svg|max:2048'
]);
$film = new Film([
'title' => $request->title,
'year' => $request->year,
'plot' => $request->plot,
'director' => $request->director,
'rating' => $request->rating,
"image" => $request->file('image')->store('images', 'public')
]);
$film->save();
return redirect()->route('home')
->with('success', 'film created successfully!');
}
Try combining your payload (data) with your formData and setting the content-type header of your axios request to multipart/form-data:
const config = {
headers: {
'content-type': 'multipart/form-data'
}
}
let data = new FormData();
data.append('title', this.title);
data.append('year', this.year);
data.append('director', this.director);
data.append('plot', this.plot);
data.append('rating', this.rating);
data.append('image', this.image);
axios.post('api/films', data, config)
.then((response) => {
console.warn(response)
})
.catch((error) => {
console.log(error);
});
you're passing the FormData object as image.
in order to make it work, you should give axios the FormData object containing all the data you want to send.
addFilm method should look like this:
const formData = new FormData;
formData.append('image', this.image)
formData.append('title', this.title)
formData.append('year', this.year)
formData.append('director', this.director)
formData.append('plot', this.plot)
formData.append('rating', this.rating)
formData.append('image', this.image)
axios
.post("/api/films", formData)
.then((response) => {
console.warn(response)
});

Trying to update the body of a blog post using Sequelize and Handlebars.js

Im creating an online blog posting webpage that uses Sequelize and Handlebars to display the pages. The problem I am having is that I'm trying to give the user an option to update the contents of a post they have made, and I am able to change the title of the post and save it, but no matter what I do, changing the body of the post does not save as well.
Heres the code for the Post Model (/models/Post.js)
const { Model, DataTypes } = require('sequelize');
const sequelize = require('../config/connection');
// Post Model
class Post extends Model {
static upvote(body, models) {
return models.Vote.create({
user_id: body.user_id,
post_id: body.post_id,
}).then(() => {
return Post.findOne({
where: {
id: body.post_id,
},
attributes: [
'id',
'title',
'created_at',
// use raw MySQL aggregate function query to get a count of how many votes the post has and return it under the name `vote_count`
[
sequelize.literal(
'(SELECT COUNT(*) FROM vote WHERE post.id = vote.post_id)'
),
'vote_count',
],
]
})
})
}
}
Post.init(
{
id: {
type: DataTypes.INTEGER,
allowNull: false,
primaryKey: true,
autoIncrement: true
},
title: {
type: DataTypes.STRING,
allowNull: false
},
post_text: {
type: DataTypes.TEXT,
allowNull: false,
validate: {
len: [4]
}
},
user_id: {
type: DataTypes.INTEGER,
references: {
model: 'user',
key: 'id'
}
}
},
{
sequelize,
freezeTableName: true,
underscored: true,
modelName: 'post'
}
);
module.exports = Post;
This is the handlebars template (views/edit-post.handlebars)
<article>
← Back to dashboard
<h2>
Edit Post
</h2>
<form class="edit-post-form">
<div>
<input name="post-title" type="text" value="{{post.title}}" />
</div>
<div>
<textarea name="post-text">{{post.post_text}}</textarea>
</div>
<div>
{{post.vote_count}} {{format_plural "point" post.vote_count}} by you on {{format_date post.created_at}}
|
{{post.comments.length}} {{format_plural "comment" post.comments.length}}
</div>
<button type="submit">Save post</button>
<button type="button" class="delete-post-btn">Delete post</button>
</form>
</article>
<form class="comment-form">
<div>
<textarea name="comment-body"></textarea>
</div>
<div>
<button type="submit">add comment</button>
</div>
</form>
{{> comments post.comments}}
<script src="/javascript/edit-post.js"></script>
<script src="/javascript/delete-post.js"></script>
<script src="/javascript/comment.js"></script>
Here's the Javascript file (/public/javascript/edit-post.js)
async function editFormHandler(event) {
event.preventDefault();
const id = window.location.toString().split('/')[
window.location.toString().split('/').length - 1
];
const title = document.querySelector('input[name="post-title"]').value;
const post_text = document.querySelector('textarea[name="post-text"]').value;
const response = await fetch(`/api/posts/${id}`, {
method: 'PUT',
body: JSON.stringify({
title,
post_text
}),
headers: {
'Content-Type': 'application/json',
},
});
if (response.ok) {
document.location.replace('/dashboard/');
} else {
alert(response.statusText);
}
}
document
.querySelector('.edit-post-form')
.addEventListener('submit', editFormHandler);
And the route function where the routes are located (controllers/dashboard-routes.js)
const router = require('express').Router();
const sequelize = require('../config/connection');
const { Post, User, Comment } = require('../models');
const withAuth = require('../utils/auth');
router.get('/', withAuth, (req, res) => {
Post.findAll({
where: {
// use the ID from the session
user_id: req.session.user_id,
},
attributes: [
'id',
'title',
'post_text',
'created_at',
[
sequelize.literal(
'(SELECT COUNT(*) FROM vote WHERE post.id = vote.post_id)'
),
'vote_count',
],
],
include: [
{
model: Comment,
attributes: ['id', 'comment_text', 'post_id', 'user_id', 'created_at'],
include: {
model: User,
attributes: ['username'],
},
},
{
model: User,
attributes: ['username'],
},
],
})
.then((dbPostData) => {
// serialize data before passing to template
const posts = dbPostData.map((post) => post.get({ plain: true }));
res.render('dashboard', { posts, loggedIn: true });
})
.catch((err) => {
console.log(err);
res.status(500).json(err);
});
});
//GET api/posts/edit/i
router.get('/edit/:id', withAuth, (req, res) => {
Post.findOne({
where: {
id: req.params.id,
},
attributes: [
'id',
'title',
'post_text',
'user_id',
'created_at',
[
`(SELECT COUNT(*) FROM vote WHERE post.id = vote.post_id)`,
'vote_count',
],
],
include: [
{
model: Comment,
attributes: ['id', 'comment_text', 'post_id', 'user_id', 'created_at'],
include: {
model: User,
attributes: ['username'],
},
},
{
model: User,
attributes: ['username'],
},
],
})
.then((dbPostData) => {
if (dbPostData) {
const post = dbPostData.get({ plain: true });
res.render('edit-post', {
post,
loggedIn: true,
});
} else {
res.status(404).end();
}
})
.catch((err) => {
console.log(err);
res.status(500).json(err);
});
});
module.exports = router;
Im pretty sure this is all of the related code but the rest is on: https://github.com/Zacharycampanelli/hi_tech_blog
I've tried changing the object the body is stored in from to and neither seem to be giving me any luck

How to save an excel file using react-query with react-native-fs?

I am using react-query wrapped around axios for APIs and trying to save/download the response to an excel file and store it. Below is the code and the api response. I am unable to figure out if I'm missing out on any headers, if the response type is incorrect or the RNFS.writeFile call is wrong.
import axios from 'axios';
import RNFS from 'react-native-fs';
import {useQuery} from 'react-query';
export function useExportGains(
accountId: number,
fileFormat: string,
fromDate: string,
toDate: string,
) {
const getReport = async () => {
const baseApiUrl = 'https://devenv.product.com/API'; // api url
const Api = axios.create({baseURL: baseApiUrl});
const params = {
fromDate: fromDate,
toDate: toDate,
contextFilter: {
appUserIds: [1],
},
};
const mimeType =
fileFormat === 'pdf'
? 'application/pdf'
: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
Api.get(`Reporting/AccountAnalytics/${accountId}/exportGains/${fileFormat}`, {
params,
headers: {
'Content-Type': mimeType,
},
responseType: 'blob',
}).then(res => {
let dir = RNFS.DocumentDirectoryPath;
let filePath = dir + '/test.' + fileFormat;
RNFS.writeFile(filePath, res.data, 'blob');
});
};
const {data, ...rest} = useQuery(
['Reporting/AccountAnalytics/exportGains', accountId],
() => getReport,
{enabled: false},
);
return {data, ...rest};
}
API response from the swagger doc:
PK
�;YT��ssL�[Content_Types].xml��Mn�0��=E�-J]TUE`џe�Tz7�Ƕ<��wb(�*J�`+�y�{v4O7����xW�Q1��k�������"CRN+��b(����|3;,EC�Ī�Va�8��>���5.dP�R-#��w���QN������V+K��wA"X�㮱c�B�`M���r��J�'�L=ؘ�n�(�������f�ѐ�T�W�r��X������eq��HJ_צ��U˒C����i-Zeܠ���Q�et� ����v��#$� ��^�ړi�Q�;E����}*�g�� �p~����y`#�dN��#d�O
��i�G�2�O&�PK
�;YT_rels/PK
�;YT�I��K_rels/.rels���N�0#�|E���nH��� ��&4>�$n���ă�#�i�q��g���<��R�,��·����iq*�#2p���f�L#J�ɽ�YH�z���u�=M�+��O�iB)���v������t�ɀ愩��#ں%��1�5ln[o��a� gZ��(dL��y�W�*P��]V׻�=��HС���hS�N��Z�u�] �όKB������#wY c�2�'7�|PK
�;YTxl/PK
�;YT xl/_rels/PK
�;YT�$�V��xl/_rels/workbook.xml.rels���j�0D��
��ZvZJ)�s)�\[����LlIh7m��UH��Ĭؙ�H���8�OL���*J�M���|4��g��[=�
&$��w�74�r}$�M<)p��EJ2GME���MҨ9��ɨ�^w(We�$���O��
��V �)��C��_�9���J�$���/�:dG]d���WK�s��s��<�[�V�tB��)?�����0_!��!��4�E�ǩy���PK
�;YTxl/worksheets/PK
�;YT��xl/worksheets/sheet1.xml�U�r�0}�Wh����1ΤqӤI�4��Y�h���_ߋ0.�x2ya��"ݣm~��R�aRq�����������\��c�4�#����x��X|�o�|W c�A�B�h]�,KфeD�D�r#b!3��)W�*$#�e�������q�0��q�)[
��X�+�R�a�*ᅪ�2�����uqFEV��O��S�2:�]�B����9���i��3N�P"�#�;L�_s`8-��
�ԑdq�/�٫����p��%�XL֩~��W��%�1k��ݳ
K
�����3�E�%S�
��CP�*�E/�%�C�[�$�c#�VZd�� �Ӄ`�(�/�rNJ��`HzzT�>hwH<>-���'F�j�����Z�����I-���n��|�f��f.�&��[$Ͳ���ݙ�~��e�\�5-ɗ#�.��[����}mbN�jbn[6�q��ļ6v���6�����vdLڌ���6�6��8o3~T�q��w�L:�ݷ�Nb�ѝNp?��;��~U�I���8��I������������#ѝD_���lj�6vyAV���JYl�3\o��sͿ���c�&4�����
�dقI�B�aU��L�$$�sb�BjI�1���˂���L�n��*kN��Mk���~�\5�O�9�Ǘz�PK
�;YT�~�eqxl/sharedStrings.xml�SMO�0��+��!ېBm�iSa���Ǩ��H�Sb��O:��J�v��{�ˋ��?\o�zJ��b�����}������C�i<a�>��<;K���8U�H{�5�5:��E���g$�^s�T\#�k�l2���XRP��$U�����k��c!K�f�dkb �Cx4-Y�{�.֏�ڂ�ٹo�lX��>�%C�5
�� C�3Ya(|S��7���m�Tᇑ�:,=ː��o<0��dH�t��
��#���#m���w_G$���C��G`���Ҵ��m�l���D*�[�%4T��n�!�)B$����A�?��AN4xH6��iX0<\N�{��m�{��C� Vw&�PK
�;YT xl/theme/PK
�;YTv�0�!xl/theme/theme1.xml�YMo�6��W���R'�S�nm� q;�HK��N����
��m�a[�إ�5�:lп�Wև)�j�&�P 98"�<���%i_�q2tH��<�X��5������u8�Ҷ�T8�0��XS"��]�* !A#���X�R�mK����c��1!V0�� |bCf7j�5;�4�P�C�zo<�.A�D���r�}�����}w�S�h�>�/���:Ĭc�.�
ɱ��R���U��Y6��9��*�F��rjN�)U���[�֯mϵ42-h�����s�)�.�]_���z�����g��^ͩ�(���2e���:�eJS���)��Zk�Q��4�c��뭕)�FY[�����(),`4:X&$�=_�9h��-3�
�v�!��R0��ʌ�#.�H�+!5������p$(�i�k��9W.�%
�t�U��$�P>s̛�?�y��y����ǿ�<yr����|����/���3����_?��� u�?��o_U ��|�ͳ?_<{����Ԅ�x��4$�%Gh����I�3R��%
jB�UPBޝbfvI9��#���Q���#L5!oa ��9�ra��v�N�i���D�a|hT�[X��$�ܦF����L�e���'Q(y�1�RZ��u�|��C����3�#efݢ!,��h#�z)B;P�3��mrX�B�`fJX)�7�D��l5���U`4t*�RूE� ��)��{bZ2�6�6e΀6
�P��zs�C��A/�al��F��X#�b�˕�^��d���#�:c�ߧ~`N���Dk��r�N��(�ʽ<��[;;���/;�Bg߂��XQ�����v�m<�v T�e�l�M�m�>Z�֬m�ȞJ
��c�ؾ�2rG��^���f�ьW��s�e�/�l�W�R�8]�T�/s��D1�pe���Wc
��&��2x�v���7K��BR:�eI]3����󫬧ؕu֝
��i:m=�P['_k����E�/Y�LH�X�{��5}��Ӽ�k�����і��{�w�P{,Z�����4�8�Xc8��c�L�4(���c�*�u��]�~�"��5�����XH��e�g�/z"͑��J�rQ��Ъ�4����{i��xL\U5���|����#4b����V�z��m4��oeYY.��N�+�8�YA���H 頰#�F�U>��O��ɹ�)��]87�ٳ�Q���ph]q#݁��E��CP:�i�%_�'6�C�ݥR���j��HPh�*��������]7�����2�F䐰aR�kI0,��'�J�\ZH�X�#��Z/�յζ����C�T��o�j����Q�~�y�N����p�A��T�L;'�d*�r�J;+�br��u?a����]� ~z��߬���J��~���ۆ����R:\�q����p ��lJ�0̞vE���{���ɴ�d�)6�1��q��Q�~���2=I(
nsn��6���X�_p6�i���<�2��?ed0o��ر��Q\ɓ�(��|�(����Eu|j�����$�J�^�����%��PK
�;YT��v��,
xl/styles.xml�U]o�0}߯���Q
4��jI�T��&5���I��S%���g�~���(���{ν���DW{��Q�"�޹�̩����:u�T�3)H��Wɇ��F�w�h`DÝ���*���sYav
�8�f���*�yeI�!�uC�1�U���5"��u�d��X�
eT-x6��
����H��g`��?zh�GN8͔�d�ύ(�EA3�8��!�
JF�mJ^�\�M<�D�S�+��Z�Nz��Mn�N h�`)s�������5COr��8��-|���� ƙ�E]rITH1���H�L2��6gG,l(��f1�-М,iNMm�Gx
G��3�Q���zhe���-�D��4Q"5��ׇ�#L��2��_��
<?����H���5N�����B��۝�,����tN�o���J���f��{{�'��bT��E�SP7meڅ����#��M�`_��'쮗_��,����Ҧ˺N�C5x��]T/��*�*5j��f�Q`oH�,���75e��'�h����]m_�S/F#'��^��1�INk��V_�ԝ�0��7���׷�nFP+ß׋���:�����:�8�`�r��r�Z�3�w��F��?<�݋lD�3V�K��~�b8Z��7�g��>�C�S�Nz�z�$�Sg^Nx�*�,��4���s�"���r¨ ��Ǩ)�Y��:V
���7PK
�;YT docProps/PK
�;YT�r<�xdocProps/app.xml�RAn�0���1�
�b8mshQv��ZYD(��n��/%������`4���;t��1�
��E)
�&���+��r�I��kp�c%�H�NP�"&�HEv�T��9��$�b��k�7MHp�^����y�г�.�[�F_c}'Cqr\����u0C>z�c���>Fg
p�I�ݚ(4\|>tJΗ*mѼ&�G]*9�ր�u6�
8B%���0t��H��W=� �;�v-�_#8ĩDɂgq����H��ϐ^�EdRr"G8�α���� �K���d|qg�!�h6������c1��������ס��srB߬����xn�T���S��s��������y�n�|z�zy�(o�r<��S��)�?PK
�;YT=[$�+^docProps/core.xml���n�0E�����ĉ��J��V��T� ��,{��!�m������Ҿg�gF.�[�$?�4�BE��47B�U��I����1*����M�-����3\���(Ҟr[�u�b���Y$t��)�ѭ�e|�V�I��c� ��|P�o���14�#����'6�S�jA���J�����1譗ضm֎z4�_����G?j*u�*�.����s�Ѧ�%>����0�q�K �yw��F�a�}9�$�C������u6A5� Is���Y�#��~u/_ԟ���ȿ�GA��}�%�_PK
�;YT]��Vmxl/workbook.xml���n�0#��
�wpڈ��".��wcO��7���wH����������hr���%��%`����J���>z�$&n%��BI��zX]�o��<ocI��|�X
�΃ŕ���aǢ�el��l�esf���B(�=W�J����.��'����q�q��o�H8��UZ�s�Ĉb��.�ƪO��#��
�(\tu#�*ySo��<��\-k���r�{��M�ES�yLoR%�%Ŝ���Dh�K�4��lJY���#$Լ���:��|��9%�2A�u������.^{ҷk٭�}�m�?#�(6���-a-g�
��#����<�,��`�PK
�;YT��ssL�[Content_Types].xmlPK
�;YT}_rels/PK
�;YT�I��K�_rels/.relsPK
�;YT�xl/PK
�;YT �xl/_rels/PK
�;YT�$�V���xl/_rels/workbook.xml.relsPK
�;YTxl/worksheets/PK
�;YT��Hxl/worksheets/sheet1.xmlPK
�;YT�~�eq(xl/sharedStrings.xmlPK
�;YT �xl/theme/PK
�;YTv�0�!�xl/theme/theme1.xmlPK
�;YT��v��,
8xl/styles.xmlPK
�;YT ,docProps/PK
�;YT�r<�xSdocProps/app.xmlPK
�;YT=[$�+^�docProps/core.xmlPK
�;YT]��VmSxl/workbook.xmlPK��

use ajax response data in another javascript

I want to use ajax response data in another javascript.
AJAX In view (sell_report.php)
<script src="<?php echo base_url(); ?>public/js/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$('.select_year_product').on('change',function () {
var select_year_product = $('.select_year_product').val();
$.ajax({
method : "POST",
url : '<?php echo site_url('sell_report/select_data_yearwise'); ?>',
data: { select_year_product:select_year_product },
success : function (data){
alert(data);
}
});
});
</script>
Above is the ajax call here in i have to select product yearwise from database it's working fine. i got response in alert(data) in ajax response. Below is the my controller Code from here i got result.
Sell_report.php (Controller)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Sell_report extends CI_Controller {
public function select_data_yearwise()
{
$select_year_product = $this->input->post('select_year_product');
$res_yearwise = $this->db->query("select * from product where year='$select_year_product'");
$row_yearwise = $res_yearwise->result();
print_r($row_yearwise);
exit();
}
}
Now,
I want to use this reponse in another javascript which is in the same view
where i write the ajax script.
The script in which i want the ajax response is explained below.
This script is for dynamic graph i have to pass the values which i got in array of ajax response through for each loop.
<script type="text/javascript">
var Script = function () {
//morris chart
$(function () {
// data stolen from http://howmanyleft.co.uk/vehicle/jaguar_'e'_type
Morris.Bar({
element: 'hero-bar',
data: [
{device: 'iPhone', geekbench: 136},
{device: 'iPhone 3G', geekbench: 137},
{device: 'iPhone 3GS', geekbench: 275},
{device: 'iPhone 4', geekbench: 380},
{device: 'iPhone 4S', geekbench: 655},
{device: 'iPhone 5', geekbench: 1571}
],
xkey: 'device',
ykeys: ['geekbench'],
labels: ['Geekbench'],
barRatio: 0.4,
xLabelAngle: 35,
hideHover: 'auto',
barColors: ['#6883a3']
});
$('.code-example').each(function (index, el) {
eval($(el).text());
});
});
}();
</script>
EDIT with AJAX Response:
Array
(
[0] => stdClass Object
(
[id] => 25
[name] => Product 1
[handle] => Handle1
[description] => <p>This is for Testing..!</p>
[total_order_income] => 1420
[type_id] => 19
[brand_id] => 5
[supplier_id] => 5
[final_price] => 147
[user_id] => 2
[supplier_code] => 123456
[sales_account_code] => 123456
[purchase_account_code] => 123456
[supply_price] => 100
[markup] => 5
[retail_price] => 105
[tax_amount] => 42
[quantity] => 50
[status] => 1
[dt_added] => 1472551929
[dt_updated] => 1472551929
)
[1] => stdClass Object
(
[id] => 29
[name] => Samsung 4G
[handle] => Samsung 4G
[description] => <p>It is very good phone</p>
[total_order_income] => 1420
[type_id] => 18
[brand_id] => 6
[supplier_id] => 1
[final_price] => 121
[user_id] => 2
[supplier_code] => 100
[sales_account_code] => 200
[purchase_account_code] => 300
[supply_price] => 100
[markup] => 10
[retail_price] => 110
[tax_amount] => 11
[quantity] => 0
[status] => 1
[dt_added] => 1472627773
[dt_updated] => 1472627773
)
[2] => stdClass Object
(
[id] => 30
[name] => Product 12
[handle] => Handle
[description] => Description
[total_order_income] => 1420
[type_id] => 0
[brand_id] => 0
[supplier_id] => 0
[final_price] => 150
[user_id] => 2
[supplier_code] => Description
[sales_account_code] => 123
[purchase_account_code] => Description
[supply_price] =>
[markup] =>
[retail_price] =>
[tax_amount] =>
[quantity] => 20
[status] => 1
[dt_added] => 1472628990
[dt_updated] => 1472628990
)
)
Here is x-axis i want product names and in y-axis i want
total_order_income.
Create the bar chart. Morris.Bar(options) returns the bar chart object for future use so make sure to save a reference to it. (to update the data)
Hook up the year change event so that you do your AJAX request. If you do this after you create the bar chart and within the same scope, you can use the chart without creating a global variable for it. (yay for closures)
In the AJAX success callback, process the data to convert it into the correct format.
Still in the AJAX callback, call chart.setData(data) to update the chart.
/* Step 1 */
var bar_chart = Morris.Bar({
element: 'hero-bar',
data: [],
xkey: 'device',
ykeys: ['geekbench'],
labels: ['Geekbench'],
barRatio: 0.4,
xLabelAngle: 35,
hideHover: 'auto',
barColors: ['#6883a3']
});
/* Step 2 */
$('.select_year_product').on('change',function () {
var select_year_product = $('.select_year_product').val();
$.ajax({
method : "POST",
url : '<?php echo site_url('sell_report/select_data_yearwise'); ?>',
data: { select_year_product:select_year_product },
success : function (data){
/* Step 3: format data here */
/* Step 4 */
bar_chart.setData(data);
}
});
});
If you needed help with step 3 then I'll happily give some pointers but it would be helpful to provide some sample responses from the AJAX request.
Edit: JSON encoding the data before sending it makes more sense than parsing the print_r output:
public function select_data_yearwise()
{
$select_year_product = $this->input->post('select_year_product');
$res_yearwise = $this->db->query("select * from product where year='$select_year_product'");
$row_yearwise = $res_yearwise->result();
echo json_encode($row_yearwise);
exit();
}
Client side:
success : function (data){
JSON.parse(data).map(d => /* extract the details you want here */ )
/* Step 4 */
bar_chart.setData(data);
}

Categories

Resources