Chris
Chris

Reputation: 117

Why is AJAX GET request only working once?

I am trying to run a script to switch some electrical plugs on a WebApp and it works perfect but here comes the problem it only works once and I can't figure out why. I've also recognized that there is an XHR request going on forever without receiving a response as soon as I call the function.

Here is the function on my node JS server and on my Web App:

 function ajaxChangePlug(num,state) {
                $.ajax({
                    url: `/api/${num}/${state}`,
                    type: "GET",
                    data: { 
                        state: state,
                        num: num
                    },
                    dataType: "json",
                })
            };
        function handle1(num,state){
                ajaxChangePlug(num,state);
                if (state === "on") {
                    document.getElementById("1").setAttribute( "onClick", `handle1(${num},'off')`);
                    document.getElementById("1").src=`/resources/${num}_on.png`
                } else {
                    document.getElementById("1").setAttribute( "onClick", `handle1(${num},'on')`);
                    document.getElementById("1").src=`/resources/${num}.png`
                }    
            };
server.get('/api/:num/:state', (req, res) => {
    var state = req.params.state;
    var num = req.params.num;
    if(state === 'on'){
        shell.exec(`/home/pi/mynode/${num}${state}_on.sh`);

    }else{
        shell.exec(`/home/pi/mynode/${num}${state}_off.sh`);        
    }
});

Upvotes: 0

Views: 264

Answers (1)

Itamar Garcia
Itamar Garcia

Reputation: 906

You should wait for the response in you front-end like this:

$.ajax({
url: `/api/${num}/${state}`,
type: "GET",
data: {
	state: state,
	num: num
},
dataType: "json",
success: function (data) {
	if (data.state === "on") {
		document.getElementById("1").setAttribute("onClick", `handle1(${num},'off')`);
		document.getElementById("1").src = `/resources/${num}_on.png`
	} else {
		document.getElementById("1").setAttribute("onClick", `handle1(${num},'on')`);
		document.getElementById("1").src = `/resources/${num}.png`
	}
}
})

In your backend you should send the response like this:

server.get('/api/:num/:state', (req, res) => {
	var state = req.params.state;
	var num = req.params.num;
	if (state === 'on') {
		shell.exec(`/home/pi/mynode/${num}${state}_on.sh`);
		res.send('on');
	} else {
		shell.exec(`/home/pi/mynode/${num}${state}_off.sh`);
		res.send('off')
	}
});

Upvotes: 2

Related Questions