Home > front end >  Code not executing after second request to server
Code not executing after second request to server

Time:12-11

I make two requests to the server using $.post. After executing the first request, i call the second request, passing the information received from the first. The problem is that after the second request is done, the code is not working, request returns the data, i checked.

Requests to the server.

$("#start_search").click(function () {
        $.post("/getLinks", {
                searchText: $('#searchText').val(),
                picSize: $('input[name="pic"]:checked').val(),
                typeFile: $('input[name="file"]:checked').val(),
                clicks: $('#numberOfPics').val()
        },
        function (data) {
            //Work fine
            console.log('Done!')
            let json = JSON.parse(JSON.stringify(data));
            for (let arr of json[0].arrs){
                for (let path of arr[0]){
                    $.post("/setImg", {
                        path: path
                    }),
                    function (res){
                        //Dont work
                        console.log(JSON.parse(JSON.stringify(res)));
                    }
                }
            }
        });
    });

Second request on the server-side.

app.post("/setImg",  (req, res) => {
    let filepath = req.body.path;
    BD.start(filepath, function (err, result) {
        if (err) console.log(err)
        res.json([{
            result: result
        }])
    })
})

BD.start.

function SetToImgDB (filepath, callback){
    connection.query(`INSERT INTO imgs (filepath) VALUES ('${filepath}')`, (err, results) => {
        if (err) return callback(err);
        createObject(results.insertId, function (err, result) {
            if (err) return callback(err)
            return callback(null, result);
        });
    })
}

function createObject (id, callback) {
    connection.query(`insert into objects (date, img_src, origin, preview, rating) values ('${(new Date()).toISOString().slice(0,19).replace('T', ' ')}', '${id}', '0', '${id}', '0')`, (err, results) => {
        if (err) return callback(err);
        return callback(null, results.insertId);
    });
}

function start (filepath, callback){
    SetToImgDB(filepath, function (err, result) {
        if (err) return callback(err)
        return callback(null, result)
    });
}

module.exports = {
    start,
}

I tried using $.ajax, but that method dont want to work at all.

CodePudding user response:

There is a misplaced closing parenthesis:

$.post("/setImg", {
  path: path
}),
function (res){
  //Dont work
  console.log(JSON.parse(JSON.stringify(res)));
}

should read

$.post("/setImg", {
  path: path
},
function (res){
  //Dont work
  console.log(JSON.parse(JSON.stringify(res)));
})
  • Related