[SOLVED]Problem regarding saving data in live collection

So basically, I’m fetching JSON array containing details of the player from an API (the whole documentation of the API: Smite / Paladins / Realm API Developer Guide - Google Docs) by giving player name (user type his/her player name into #input1 field) to the API. Now, I want to store the data that I fetched (using wixdata.insert()), into the database. It works fine in sandbox however no data is getting inserted into the live db. I checked the permission for the the db and also set every permission to “anyone”. Further more, I added suppressing authentication bit =>

  1. let options = {
  2. “suppressAuth”: true ,
  3. “suppressHooks”: true
  4.    }; 
    
  5. wixData.insert(“SUMMARY”, toInsert,options)
  6.                    .then(results => { 
    
  7.                         let  item = results;  
    
  8.                        console.log(item) //see item below 
    
  9.                      }) 
    
  10.                   . catch (err => { 
    
  11.                         let  errorMsg = err; 
    
  12.                        console.log(errorMsg); 
    
  13.                    }); 
    

None of them works, nothing get inserted into the live db. The console.log(item) at line 8, does print the data that im fetching from the JSON file.
PLEASE HELP !! :frowning:

Anyone there? HALLPP

Pronil:
What is the web page link?
Can you share all of the page code and the site code too?
I can’t see what your toInsert object looks like, make sure that you are using the correct key values from your data collection in the toInsert.
Steve

@stcroppe
Site: https://pronilchakraborty0.wixsite.com/mysite-1
Here is the code,

export function retireve_click(event, $w) {

function SaveDataToDatabase() {

    getplayer($w('#input1').value).then(res => { 
        console.log(res); 

let toInsert = {

“title”: res[0].Name,
“playerId”: res[0].Id,
“playerLevel”:res[0].Level,
“accountCreated”: res[0].Created_Datetime,
“lastLogin”: res[0].Last_Login_Datetime,
“winsLoss”: res[0].Wins + " " + “/” + " " + res[0].Losses,
“matchAfk”: res[0].Leaves,
“masteryLevel”: res[0].MasteryLevel,
“region”: res[0].Region,
“achievementCompleted”: res[0].Total_Achievements,

“rankSeason”: "Season: " + res[0].RankedConquest.Season,
“rankName”: res[0].RankedConquest.Name,
“rankWinsLoss”: res[0].RankedConquest.Wins + " " + “/” + " " + res[0].RankedConquest.Losses,
“rankTp”: res[0].RankedConquest.Points,
“rankTier”: res[0].RankedConquest.Tier,
“rankAfk”:res[0].RankedConquest.Leaves,
“previousRank”:res[0].RankedConquest.PrevRank

                }; 

//BELOW IS THE SUPPRESS PERMISSION for INSERTing INTO DATABASE
let options = {
“suppressAuth”: true ,
“suppressHooks”: true
};
wixData.insert(“SUMMARY”, toInsert,options)

                    .then(results => { 

let item = results;
console.log(item) //see item below
})
. catch (err => {
let errorMsg = err;
console.log(errorMsg);
});

    }); 

    wixLocation.to("https://pronilchakraborty0.wixsite.com/mysite-1/summary/"); 

} 

function ErrorTextCalls(condition) { //ErrorTextCalls function gets called when an error msg need to be shown at #text13 according to 3 different conditions
let fadeOptions = {
“duration”: 1700,
“delay”: 2000
};

    $w('#text13').text = " "; 
    $w('#text13').show(); 

if (condition === “playerName”) {

        $w('#text13').text = "Error: Please Type Username"; 

    }  **else if**  (condition === "noPlatform") { 

        $w('#text13').text = "Error: Please Select Platform"; 

    }  **else if**  (condition === "notFound") { 

        $w('#text13').text = "Error: Player Not Found !!!"; 
    } 
    $w('#text13').hide("fade", fadeOptions); 
} 

if ($w(‘#input1’).value === ‘’) {
//If the User didnt typed anyName at the input1 location

    ErrorTextCalls("playerName"); 

return ;
}
if ($w(‘#input1’).value !== ‘’) { //if the user typed something in input1

if ($w(‘#dropdown1’).value === ‘’) { //if the user didnt selected anything in the dropdown menu

        ErrorTextCalls("noPlatform"); 

return ;

    } 
} 

if ($w(‘#dropdown1’).value === ‘pc’) { //if the user selected pc from dropdown menu

    getplayerstatus($w('#input1').value).then(res => { 

        console.log(res); 

if (res[0].status_string === ‘Unknown’) { //if username not found according to the Paladins API

            ErrorTextCalls("notFound"); 

        }  **else**  { 
            SaveDataToDatabase(); 

// wixLocation.to(“https://pronilchakraborty0.wixsite.com/mysite-1/SUMMARY/”+ $w(‘#input1’).value + “/”);
}

    }); 
} 

if ($w(‘#dropdown1’).value === ‘xbox’) { //if the user selected xbox from dropdown menu

    getplayerstatusxbox($w('#input1').value).then(res => { 

        console.log(res); 

if (res[0].status_string === ‘Unknown’) { //if username not found according to the Paladins API

            ErrorTextCalls("notFound"); 

        }  **else**  { 
            SaveDataToDatabase(); 
           // wixLocation.to("https://pronilchakraborty0.wixsite.com/mysite-1/SUMMARY/" + $w('#input1').value + "/"); 
        } 
    }); 
} 

if ($w(‘#dropdown1’).value === ‘ps4’) { //if the user selected ps4 from dropdown menu

    getplayerstatusps4($w('#input1').value).then(res => { 

        console.log(res); 

if (res[0].status_string === ‘Unknown’) { //if username not found according to the Paladins API

            ErrorTextCalls("notFound"); 

        }  **else**  { 
            SaveDataToDatabase(); 
          //  wixLocation.to("https://pronilchakraborty0.wixsite.com/mysite-1/SUMMARY/" + $w('#input1').value + "/"); 
        } 
    }); 
} 

}

PS: Sorry for the delayed response

Hello Pronil,

Instead of declaring functions within functions, have them as top level functions so that you can call them and declutter your code and make it more managable.

Like so:

export function retireve_click(event, $w) {
    SaveDataToDatabase();
}

Remove all the other functions and just test the SaveDataToDatabase function first, make sure it is working correctly.

Then I see you want to do some sort of error checking so to do that, have it as a seperate function and put it in the SaveDataToDatabase function before you insert. (check for errors before inserting)

Like so:

if(errMessage == null){
	wixData.insert("SUMMARY", toInsert, options)
} else {
	$w('exampleText').text = errMessage
}

So in short, clean up your code, create a separate function for each functionality, test each function one at a time, and it should work.

Also use this button as it is really helpful :)!

Best,
Majd

Hi Pronil:

Majd’s suggestions on style are good ones, although javascript does allow this and it depends on your style. Getting indentation correct also helps with code assessment.

Now here’s what I have experienced with your save to database function…

function SaveDataToDatabase() {
    // Since this is returning a promise if you return the getplayer call you will be able to chain SaveDataToDatabase in a promise sequence where it is called. This might help with exception handling    
// Replace ->    getplayer($w('#input1').value).then(res => { with ...
    return getplayer($w('#input1').value)
    .then(res => {
	console.log(res);
	let toInsert = {
		"title": res[0].Name,
		"playerId": res[0].Id,
		"playerLevel":res[0].Level,
		"accountCreated": res[0].Created_Datetime,
		"lastLogin": res[0].Last_Login_Datetime,
		"winsLoss": res[0].Wins + " " + "/" + " " + res[0].Losses,
		"matchAfk": res[0].Leaves,
		"masteryLevel": res[0].MasteryLevel,
		"region": res[0].Region,
		"achievementCompleted": res[0].Total_Achievements,
						
		"rankSeason": "Season: " + res[0].RankedConquest.Season,
		"rankName": res[0].RankedConquest.Name,
		"rankWinsLoss": res[0].RankedConquest.Wins + " " + "/" + " " + res[0].RankedConquest.Losses,
		"rankTp": res[0].RankedConquest.Points,
		"rankTier": res[0].RankedConquest.Tier,
		"rankAfk":res[0].RankedConquest.Leaves,
		"previousRank":res[0].RankedConquest.PrevRank
	};
	//BELOW IS THE SUPPRESS PERMISSION for INSERTing INTO DATABASE
// **** THESE OPTIONS DO NOT WORK IN FRONT END. THEY ARE BACKEND ONLY
	let options = {
		"suppressAuth": true,
		"suppressHooks": true
	};
// ****************************
	// wixData.insert() returns a promise. If you return this inside
	// a promise then you can chain the .then call backs and make 
	// your code easier to manage
// Replace this	wixData.insert("SUMMARY", toInsert,options) with...
	return wixData.insert("SUMMARY", toInsert,options);
    })
    // This then is now chained to the getPlayer call
    .then(results => {
	let item = results;
	console.log(item) //see item below
    })
    // This will now catch all promise based errors including ones 
    // from the getplayer call
    .catch(err => {
	let errorMsg = err;
	console.log(errorMsg);
    });
    
// ***************** WHAT IS THIS SUPPOSED TO DO? ****************
// If you want to redirect to this page after a successful data 
// collection insert then you need to move this inside of the .then()
// that contains the results.
// As coded this executes immediately, redirects to a new page and aborts 
//your data collection save (so you will never save anything :-)			
    wixLocation.to("https://pronilchakraborty0.wixsite.com/mysite-1/summary/");
//**********************************************************************
}

So Majd’s suspicions were correct :slight_smile: - your save function is broken. If you make the suggestions I propose and move the wixLocation.to() call to one of the .then() functions, or delete it, you might get your expected results. At a minimum the catch() will show you any errors along the way :wink:

Steve

Thank you @stcroppe & @mqumseya . The solution you guys provided worked, It took a bit time, but worked. Really really appreciated your time and response. Again, thanks. :wink: