Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all 141337 articles
Browse latest View live

Javascript to Python [closed]

$
0
0
<!DOCTYPE html>
<html>
<head>
    <title> Story Time </title>
</head>

<body>
    <h2> Story Time </h2>
    <p> <b>
    Enter your favorite character:
        <input type="text" id="characterBox" size=40 value =""> <br> <br>
    Enter your favorite place:
        <input type="text" id="placeBox" size=40 value=""> <br> <br>
    Enter favorite food:
        <input type="text" id="foodBox" size=40 value=""> <br> <br>
    </b>
    </p>

    <input type="button" value="click for story"
        onclick="document.getElementById('outputDiv').innerHTML=
        'Once upon a time, ' 
        +document.getElementById('characterBox').value +
        ' was flying through the sky when he hit a tree and fell to ground. To his surprise, he had landed in ' 
        + document.getElementById('placeBox').value +
        '. He looked around and saw a Red Robin and realized he was hungry, so he went in and ordered a ' 
        + document.getElementById('foodBox').value +
        '. After eating, he was satisfied and found a park bench and went to bed because it was too dark to fly back home.';">

    <hr>
    <div id="outputDiv"> </div>

</body>

</html>

I need to convert this code from Javascript to Python fo a school project. Here are the instructions: (1 is already complete)

  1. Create a web page that asks the user three different inputs. Use those inputs to create a story and display the story.

  2. Create a python program that asks the user for three different inputs. Use those inputs to create a story and display the story.


Finding object by parents value [closed]

$
0
0

I have this template:

{
    Main: {
        Client1: {
            Active: true,
            Offers: {
              RandomName1: {
                Name: 'Maria',
                Active: true,
                Value: 123
              },
              RandomName2: {
                Name: 'Louise',
                Active: true,
                Value: 123
              }
            }
        },
        Client2: {
            Active: true,
            Offers: {
              RandomName1: {
                Name: 'Hannah',
                Active: true,
                Value: 456
              }
            }
        },
        Client3: {
            Active: false,
            Offers: {
                RandomName1: {
                  Name: 'Denise',
                  Active: true,
                  Value: 789
                }
            }
        }
    }
}

I want to filter out all Offers where Active equals true, and also where the Offers parent is Active.

So in this case the result should be:

[
    {
        Name: 'Maria',
        Active: true,
        Value: 123
    },
    {
        Name: 'Louise',
        Active: true,
        Value: 123
    },
    {
         Name: 'Hannah',
         Active: true,
         Value: 456
    }
]

I've done a fair share of searching around and testing different solutions, but none has been a solution to this quite complicated filter.

Would be nice to get some help with this :)

How can I see formatted 'received' results with Jest?

$
0
0

Using Jest, failed tests often look something like this:

● someThing › Try doing a thingr

    expect(received).toHaveLength(expected)

    Expected length: 6
    Received length: 7
    Received array: [massive chunk of unformatted JSON, as a wall of text]

I currently paste the output into an editor and format it, how how can I make jest show me the output in a human readable format (like a JSON.stringify(result, null, 2)) or util.inspect() would show)?

How can I see formatted 'received' results with Jest?

Subtract days, months, years from a date in JavaScript

$
0
0

Does anybody know of a simple way of taking a date (e.g. Today) and going back X days, X months and X years?

I have tried that:

var date = new Date();
$("#searchDateFrom").val((date.getMonth() -1 ) + '/' + (date.getDate() - 6) + '/' + (date.getFullYear() - 1));

But I got a negative date, for example today the output was:

3/-3/2015

Any advise?

Thanks.

how to put items in an array sequentially?(javascript)

$
0
0

I wonder the title is right or not,

anyway what I wonder is how can do thing like this

const items = [a1,a2,a3,a4,a5,a6,a7,a8,a9 .. and so on ]

const flexbox1 = [];
const flexbox2 = [];
const flexbox3 = [];
const flexbox4 = [];



for (const item in items) {

// what I wonder is this part. 

      }


==> result:

const flexbox1 = [a1,a5,a9,a13 .. and so on];
const flexbox2 = [a2,a6,a10,a14 .. and so on];
const flexbox3 = [a3,a7,a11,a15 .. and so on];
const flexbox4 = [a4,a8,a12,a16 ... and so on];



How can I get the results above??

I've been trying for two days to find the answer in the book and on the internet, but I couldn't find it.

please help ....

Thanks in advance.

i want to push object into array of objects in Vue.js

$
0
0

im new to vue and im trying to get the whole concept of vue and how to use it, now im trying to learn lists.

JS:


Vue.config.productionTip = false;

new Vue({
  el: '#app',
  data: {
    items: [
    {Name: "qwe"},
    {Name: "qwe"},
    {Name: "zxc"},
    {Name: "qwe"},
    {Name: "asd"}
  ] },
  methods: {
      items.push({Name: "tyu"})
}
})

HTML:

<div id="app">
    <ol>
      <li v-for="item in items">{{item.Name}}</li>
    </ol>
</div> 

How to delete grey border around canvas

$
0
0

I need to export to pdf file some fragment of html. I use for that html2canvas and pdfjs. But there is added some grey border around this fragment

Here is test html fragment:

<div class="col-md-12 white-bg box-shadow margb0" id="test">
     <div class="col-md-12 paddl0 paddr0 margt0 margb10">
          <h4 class="paddb10 margt20 margb10 border-bottom-sc">
              Some information out here
          </h4>
     </div>
</div>

And css for it (col-md-12 is from bootstrap.min.css):

.white-bg { background: #ffffff; }
.margb0 {margin-bottom: 0px !important;}
.margt0 {margin-top: 0px !important;}
.margb10 {margin-bottom: 10px;}
.margt20 { margin-top: 20px;}
.paddl0 {padding-left: 0px !important;}
.paddr0 {padding-right: 0px !important;}
.paddb10 { padding-bottom: 10px;}
.border-bottom-sc {border-bottom: 1px solid #424343;}

In Chrome it looks like this: enter image description here

Here is how I do this in js:

var pdf = new jsPDF('p', 'pt', 'a4', true);
var content = document.getElementById('test');
html2canvas(content, { background: "white" },
                         { scrollX: 0, scrollY: 0 }).then(function (canvas) {
    var srcImg  = canvas;
    var sX      = 0;
    var sY      = 0;
    var sWidth  = 1150;
    var sHeight = 1350;
    var dX      = 25;
    var dY      = 25;
    var dWidth  = 1150;
    var dHeight = 1350;
    window.onePageCanvas = document.createElement("canvas");
    onePageCanvas.setAttribute('width', 1150);
    onePageCanvas.setAttribute('height', 1350);
    var ctx = onePageCanvas.getContext('2d');
    ctx.drawImage(srcImg, sX, sY, sWidth, sHeight, dX, dY, dWidth, dHeight);
    var canvasDataURL = onePageCanvas.toDataURL("image/png", 1.0);

    var width         = onePageCanvas.width;
    var height        = onePageCanvas.height;
    pdf.addImage(canvasDataURL, 'jpg', 0, 0, (width*.51), (height*.51));
    pdf.save('test.pdf');
});

And here is how this fragment looks in document: enter image description here

Demo: https://jsfiddle.net/x6yg1kbm/2/

So my question: how to not show this border during pdf export?

JavaScript ReverseMatch

$
0
0

Is simple, i have this sentence:

str = "aeiou";

Need RegExp to scan string every X chars, but in reverse.

Example:

let every=2,
    match = new RegExp(/>>RegExp Here<</gi);  
//result "a ei ou"

Loading text file and then printing it

$
0
0
document.addEventListener('DOMContentLoaded', function() {
    let fileInput = document.getElementById("fileInput")
    let displayArea = document.getElementById("displayArea")

    fileInput.addEventListener("change", (e) => {
        let file = fileInput.files[0];

        let reader = new FileReader();

        reader.onload = (e) => {
            displayArea.innerText = e.target.result;
        };

        reader.onerror = (e) => {
            console.error("File could not be read! Code " + e.target.error.code);
        };

        reader.readAsText(file);

        console.log(displayArea.innerText);
    });
}, false);

<input type="file" id="fileInput">
<div id="displayArea"></div>

div contains the text, but console.log gets <empty string>.

I think it logs before reader.onload.

I tried to do something with async and await, but without any success.

Thanks a lot!

How to submit a value with a submit button AND by the enter button?

$
0
0

Can someone help me with some javascript code?

I would start a javascript function after click the submit button AND after pressing the 'Enter' key. I've made this code, seperately it works, but together the 'Enter' key doesn't works. What goes wrong?

Thanks!!

<form onsubmit="SubmitFormData(); return false;" id="myForm" method="post">

 Name:    <input name="name" id="name" type="text" /><br />


<input type="submit" id="submitFormData" onclick="SubmitFormData();" value="Submit" />
</form>

<script>
var input = document.getElementById("name");
input.addEventListener("keyup", function(event) {
  if (event.keyCode === 13) {
   event.preventDefault();
   SubmitFormData();
  }
});
</script>

function SubmitFormData() {
var name = $("#name").val();
$.post("submit.php", { name: name },
function(data) {
 $('#results').html(data);
 $('#myForm')[0].reset();
});
}

Integrating Symfony/PHP applcation with real time chat

$
0
0

I am developing a Symfony web application. I want to have a real time chat functionality in it.

What do you think is the best option in my situation? I have been searching for answer and i got to the following option: using nodejs + socket.io running aside with PHP - i am not experienced in the server field but i don't think running two servers (PHP - apache/nginix + nodejs) is a good idea. I mean is it reliable for a scalable web application?

So what do you think? Is there another option?

NodeJS routes not getting called using Express

$
0
0

I am trying to build a basic rest api using nodeJS. But when I'm trying to call any endpoint none of them are getting called. What changes should i make in order to make it work. Please help.

const express = require('express') ;
const app = express() ;
const morgan = require('morgan') ;
const bodyParser = require('body-parser') ;

const productRoutes = require('./api/routes/products') ;
const orderRoutes = require('./api/routes/orders') ;

console.log('abc1') ;

//middleware
app.use(morgan('dev')) ;
app.use(express.urlencoded({ extended: true }));
app.use(express.json);

console.log('abc2') ;

//routes
app.use('/products' , productRoutes ) ;
//console.log('abc5') ;
app.use('/orders' , orderRoutes) ;


//delete it later
app.get('/' , (req , res, next) => {
    res.status(200).json({
        message: 'done'
    }) ;
}) ;
//delete end

//for 404 / not found error
app.use((req,res,next) => {
    const error = new Error('not found');
    error.status = 404 ;
    next(error);
});

//handle any error
app.use((error , req, res,next) => {
    res.status(error.status || 500) ;
    res.json({
        message : error.message 
    }) ;
});

module.exports = app ;

my app.js file

const express = require('express') ;
const router = express.Router() ;

router.get('/' , (req,res,next) =>{
    console.log('abc') ;
    res.status(200).json({
        message : 'In get routes'
    }
    ) ;
}) ;

router.post('/' , (req,res,next) =>{
    res.status(201).json({
        message : 'In post routes'
    }
    ) ;
}) ;

router.get('/:productId' , (req,res,next) =>{
    res.status(200).json({
        message : 'In get routes' + req.params.productId 
    }
    ) ;
}) ;

module.exports = router ;

my products.js file

const http = require('http') ;
const app = require('./app') ;

const port = process.env.PORT || 3000 ;
console.log(port) ;

const server = http.createServer(app);

server.listen(port) ;

my server.js file

When I'm trying to run the server it runs normally. And the console.logs are also working fine. And also no error is getting thrown.

i am creating to isolate parts of my model with a FadeToggle effect with a degree of transparency. I can do? [closed]

$
0
0

I would like to connect the sech function with the fadetoggle effect. where am i wrong? how should I set it up?

function T00()
{
NOP_VIEWER.model.search('00', function onSuccess(dbids) {NOP_VIEWER.showAll(); NOP_VIEWER.isolate(dbids); }, function onError(err) { console.error(err); }, 'Timeline_Storico');}.fadeToggle(400)

How to handle the apple callback in Parse Server

$
0
0

I have the Sign in with apple working to the point that I'm signed in with apple and apple redirects with a Post request to my server.

I set up the following express post handler:

app.post('/apple-callback', async function (req, res) {
    let data = req.body.id_token
    let buff = Buffer.from(data.split('.')[1], 'base64')
    let text = buff.toString('utf8')
    let json = JSON.parse(text)
    try {
        let currentUser = await Parse.User.logInWith('apple', {
            'authData':{
                'id': json.sub,
                'token': data
            } 
        })

        console.info(currentUser)
    } catch (error) {
        console.error(error)
    }

    res.json({
        'fissa': req.body,
        'state': req.body.state,
        'code': req.body.code,
        'idToken': req.body.id_token,
        json,
        sub: json.sub
    })
})

but I get the following error:

Feb 25, 2020, 15:56:39 +01:00- ERROR
Uncaught internal server error. { JsonWebTokenError: invalid signature
    at /opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:133:19
    at getSecret (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:90:14)
    at Object.module.exports [as verify] (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:94:10)
    at verifyIdToken (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/index.js:43:25)
    at process._tickCallback (internal/process/next_tick.js:68:7) name: 'JsonWebTokenError', message: 'invalid signature' } JsonWebTokenError: invalid signature
    at /opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:133:19
    at getSecret (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:90:14)
    at Object.module.exports [as verify] (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:94:10)
    at verifyIdToken (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/index.js:43:25)
    at process._tickCallback (internal/process/next_tick.js:68:7)
Feb 25, 2020, 15:56:39 +01:00- ERROR
JsonWebTokenError: invalid signatureJsonWebTokenError: invalid signature
    at /opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:133:19
    at getSecret (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:90:14)
    at Object.module.exports [as verify] (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:94:10)
    at verifyIdToken (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/index.js:43:25)
    at process._tickCallback (internal/process/next_tick.js:68:7)
Feb 25, 2020, 15:56:39 +01:00- ERROR
Uncaught internal server error. { JsonWebTokenError: invalid signature
    at /opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:133:19
    at getSecret (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:90:14)
    at Object.module.exports [as verify] (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:94:10)
    at verifyIdToken (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/index.js:43:25)
    at process._tickCallback (internal/process/next_tick.js:68:7) name: 'JsonWebTokenError', message: 'invalid signature' } JsonWebTokenError: invalid signature
    at /opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:133:19
    at getSecret (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:90:14)
    at Object.module.exports [as verify] (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:94:10)
    at verifyIdToken (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/index.js:43:25)
    at process._tickCallback (internal/process/next_tick.js:68:7)
Feb 25, 2020, 15:56:39 +01:00- ERROR
JsonWebTokenError: invalid signatureJsonWebTokenError: invalid signature
    at /opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:133:19
    at getSecret (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:90:14)
    at Object.module.exports [as verify] (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:94:10)
    at verifyIdToken (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/index.js:43:25)
    at process._tickCallback (internal/process/next_tick.js:68:7)
Feb 25, 2020, 15:56:39 +01:00- ERROR
Uncaught internal server error. { JsonWebTokenError: invalid signature
    at /opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:133:19
    at getSecret (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:90:14)
    at Object.module.exports [as verify] (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:94:10)
    at verifyIdToken (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/index.js:43:25)
    at process._tickCallback (internal/process/next_tick.js:68:7) name: 'JsonWebTokenError', message: 'invalid signature' } JsonWebTokenError: invalid signature
    at /opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:133:19
    at getSecret (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:90:14)
    at Object.module.exports [as verify] (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:94:10)
    at verifyIdToken (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/index.js:43:25)
    at process._tickCallback (internal/process/next_tick.js:68:7)
Feb 25, 2020, 15:56:39 +01:00- ERROR
JsonWebTokenError: invalid signatureJsonWebTokenError: invalid signature
    at /opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:133:19
    at getSecret (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:90:14)
    at Object.module.exports [as verify] (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:94:10)
    at verifyIdToken (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/index.js:43:25)
    at process._tickCallback (internal/process/next_tick.js:68:7)
Feb 25, 2020, 15:56:39 +01:00- ERROR
Uncaught internal server error. { JsonWebTokenError: invalid signature
    at /opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:133:19
    at getSecret (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:90:14)
    at Object.module.exports [as verify] (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:94:10)
    at verifyIdToken (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/index.js:43:25)
    at process._tickCallback (internal/process/next_tick.js:68:7) name: 'JsonWebTokenError', message: 'invalid signature' } JsonWebTokenError: invalid signature
    at /opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:133:19
    at getSecret (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:90:14)
    at Object.module.exports [as verify] (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:94:10)
    at verifyIdToken (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/index.js:43:25)
    at process._tickCallback (internal/process/next_tick.js:68:7)
Feb 25, 2020, 15:56:39 +01:00- ERROR
JsonWebTokenError: invalid signatureJsonWebTokenError: invalid signature
    at /opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:133:19
    at getSecret (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:90:14)
    at Object.module.exports [as verify] (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/node_modules/jsonwebtoken/verify.js:94:10)
    at verifyIdToken (/opt/app-root/src/node_modules/sashido-parse-server-apple-auth-adapter/index.js:43:25)
    at process._tickCallback (internal/process/next_tick.js:68:7)

Any suggestions?

This is how far I got with parse docs and some trial and error.

But I don't know how to fix the errors and get a valid parse user.

Angular project version update [closed]

$
0
0

What is the best way to Update My Advanced Angular 4 Project to Angular 8.

enter image description here


How to create new img in new div in new header in js?

$
0
0

I want to create slider in js. Here is my code. The problem is how I've mentioned, with creating new img element in new div element in new header element "in the same time", sth. like header > div > img.

const myRequest = new Request('./database.json');
const myHeader = document.querySelector('main');

export const headerTwo = (fragment) => {
    fetch(myRequest)
    .then(function (response) {
        console.warn(response);
        return response.json();
    })
    .then(function () {

    let header = document.createElement('div');

    // above is the problem with creating header > div > img 

    header.setAttribute('class', 'slider');

    const slideList = [{
        img: "https://",
        text: 'sth 1'},{
        img: "https://",
        text: 'sth 2'},{
        img: "https://",
        text: 'sth 3'}
        ];

    const time = 3000;
    let active = 0;

    const changeSlide = () => {
        active++;
        if (active === slideList.length) {
            active = 0;
        }
        header.src = slideList[active].img;
        header.textContent = slideList[active].text;
        };
    let indexInterval = setInterval(changeSlide, time);

    myHeader.appendChild(header);
    })
    .then(function() {
        console.log('Co to ????');
    })
.catch(function (error) {
    console.log('--------- ', error);
});


}

How do I fix RichEmbed?

$
0
0

I am trying to print get embed message in discord, but this happens:

TypeError: Discord.RichEmbed is not a constructor

Here is my code:

const Discord = require('discord.js');
const bot = new Discord.Client();
const token = 'mytokenhere';
const prefix = '!';

bot.on('ready', () => {
    console.log('This bot is online!');
});

bot.on('message', message => {
    let args = message.content.substring(prefix.length).split("");

    switch(args[0]) {
        case 'pomoc':
            message.channel.send('.')
            break;
        case 'cc':
            if(!args[1]) return message.reply('Podaj 2 argument! (liczbe wiadomosci do skasowania)')
            message.channel.bulkDelete(args[1]); 
            break;
        case 'embed':
            var embed = new Discord.RichEmbed()
                .setAuthor(message.author.username)
                .setDescription("Usuario rikolino.")
                .setColor("#3535353")
                .addField("Usuario", '${message.author.username}#${message.author.discriminator}')
                .addField("ID", message.author.id)
                .addField("Creación", message.author.createdAt);

            message.channel.send({embed});
            break;
    }
});

bot.login(token);

I tried many other solutions, but the result is always the same, I really don't know where the problem is.

Jquery Serialize not working to post to laravel controller

$
0
0

i'm can't save my data in databse when i'm something to do with my input or select html tag. Whats wrong guys??

Ajax

$("input, select, textarea").on('change blur' ,function(e){
    e.preventDefault();

    $.ajax({
       type:'POST',
       url:'/karyawan-diterima/edit',
       data: $('#myForm').serialize(),
       success:function(sukses){
          //alert(data);
          console.log(sukses);
          $('#sukses').show();

          setInterval(function() {
            $('#sukses').fadeOut();
          }, 2500);
       }
    });
});

Update Controller

$id = $request->id;

    $k = karyawan::where('id', $id) -> first();
    $d = detail_karyawan::where('id_karyawan', $id) -> first();

    $k->nama = $request->nama;
    $k->telp = $request->telp;
    $k->bagian = $request->bagian;
    $k->nik_lama = $request->nik_lama;
    $k->nik_baru = $request->nik_baru;
    $k->jk = $request->jk;
    $k->alamat = $request->alamat;

    $k->update;

    $sukses = 'success';
    return response()->json($sukses, 200);

enter image description here

Twitter API won't authenticate me - {code: 32, ...}

$
0
0

I am trying to work with Twitter APIs to build a web application using ExpressJS. I am using PassportJS for Twitter authentication. After logging in, I tried making a call to the GET friends/ids endpoint and I was getting { errors: [ { code: 32, message: 'Could not authenticate you.' } ] }. I am using the request npm module to make calls to the endpoint. I have built everything necessary, especially the header string for Authorization, but that error is all that comes back. Here's what I have so far:

somefile.js

const request = require('request')
const crypto = require('crypto')
const Math = require('mathjs')

const oauthConsumerKey = process.env.CONSUMER_KEY
const oauthConsumerSecret = process.env.CONSUMER_SECRET
const oauthNonce = crypto.randomBytes(16).toString('hex')
const oauthSignatureMethod = 'HMAC-SHA1'
const oauthTimestamp = Math.floor(Date.now() / 1000)
const oauthVersion = '1.0'
const httpMethod = 'GET'

// Build parameter string
const buildSignatureParameterString = (token) => {
    const oauthToken = encodeURIComponent(token)
    const signatureParameterString = `include_entities=true&oauth_consumer_key=${oauthConsumerKey}&oauth_nonce=${oauthNonce}&oauth_signature_method=${oauthSignatureMethod}&oauth_timestamp=${oauthTimestamp}&oauth_token=${oauthToken}&oauth_version=${oauthVersion}`
    return signatureParameterString
}

// Build signing key
const buildSigningKey = (tokenSecret) => {
    const signingKey = `${encodeURIComponent(oauthConsumerSecret)}&${encodeURIComponent(tokenSecret)}`
    return signingKey
}

// GET friends/ids
const getFriends = (id, token, signParamString, signingKey) => {
    const oauthToken = encodeURIComponent(token)
    const url = `https://api.twitter.com/1.1/friends/ids.json?user_id=${id}`
    const signatureBaseString = `${httpMethod}&${encodeURIComponent(url)}&${encodeURIComponent(signParamString)}`
    const oauthSignature = encodeURIComponent(crypto.createHmac('sha1', signingKey).update(signatureBaseString).digest('base64'))
    const authHeaderString = `OAuth oauth_consumer_key="${oauthConsumerKey}",oauth_nonce="${oauthNonce}",oauth_signature="${oauthSignature}",oauth_signature_method="${oauthSignatureMethod}",oauth_timestamp="${oauthTimestamp}",oauth_token="${oauthToken}",oauth_version="${oauthVersion}"`
    console.log(authHeaderString)
    const options = {
        url,
        json: true,
        headers: {
            'Authorization': authHeaderString
        }
    }
    request(options, (error, response) => {
        if(error)  return console.log(error)
        console.log(`Status code: ${response.statusCode}\n`)
        console.log(response.body)
    })
}

module.exports = { buildSignatureParameterString, buildSigningKey, getFriends }

index.js (entry point)

const { buildSignatureParameterString, buildSigningKey, getFriends } = require('./utils/unfollowers')

passport.use(new TwitterStrategy({
    consumerKey: process.env.CONSUMER_KEY,
    consumerSecret: process.env.CONSUMER_SECRET,
    callbackURL: `http://${process.env.BASE_URL}:${process.env.PORT}/auth/twitter/callback`,
}, (token, tokenSecret, profile, callback) => {
    profile.token = token
    profile.tokenSecret = tokenSecret
    return callback(null, profile)
}))

...

app.get('/friendsIDs', require('connect-ensure-login').ensureLoggedIn('/'), (req, res) => {
    const signParamString = buildSignatureParameterString(req.user.token)
    const signingKey = buildSigningKey(req.user.tokenSecret)
    getFriendsIDs(req.user.id, req.user.token, signParamString, signingKey)
    console.log(`Authorization: ${req.headers.authorization}`)
    const { screen_name: screenName, followers_count: followers, friends_count: following } = req.user._json
    res.render('friendsIDs', { screenName, followers, following })
})

Here's what I found out: console.log(Authorization: ${req.headers.authorization}) returns undefined and I don't understand why. I think I just need a way to set the Authorization header and I'll get an actual response. I know the request module supports OAUTH1.0. In fact, I have used it and it works. I just wanna know what's behind my error. Thanks for the help!

Use Javascript to build an output with JSON Response [closed]

$
0
0

This is going to be a goofy one. I'm building a javascript app.

I start off by fetching I'm getting json with a random amount of "results"

const res = await fetch(url); 
var json = await res.json();

JSON Response

{"results":[2796080665,2808331491,2839332582],"hasMore":false,"offset":5975413715}

I need to take all of the results and build an output/return that would look like:

  {
    "fromObjectId": 2796080665,
     "toObjectId": 123,

  },
  {
    "fromObjectId": 2808331491,
    "toObjectId": 123
  },
{
    "fromObjectId": 2839332582,
     "toObjectId": 123,

  }

I'm using this in a Zapier "Run Javascript Event". So I need the result to be dumped into a webook Data box. And it needs to look exactly like the out put below. You can see that the fromObjectID is from the json GET.

I'm going to use this data in a PUT.

Any ideas on how to do this?

Viewing all 141337 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>