Can I print fetch API data with only use of one then?
Like this
fetch(signup_url, {
method: 'POST',
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: user_name.value,
email: usr_email.value,
password: usr_password.value,
username: user_name.value,
lastname: usr_last_name.value,
type: usr_type.value,
phone: ph_number.value
})
})
.then((res) => {
var data = res.json() //Promise
console.log(data)
})
1 answer
-
answered 2020-11-28 12:55
Elanochecer
You just have to await the async function:
fetch(signup_url, { method: 'POST', headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: user_name.value, email: usr_email.value, password: usr_password.value, username: user_name.value, lastname: usr_last_name.value, type: usr_type.value, phone: ph_number.value }) }) .then(async (res) => { var data = await res.json() console.log(data) })
Though i don't get why you want to use just 1 then.
See also questions close to this topic
-
how to fetch a nested resource for every component in React router dom route
So I have some nested routes that look like this:
<Switch> <Route exact path={"/"}> <HomepageContainer /> </Route> <Route path={"/users"}> <UsersContainer /> </Route> <Route path={"/users/new"}> <NewUserContainer /> </Route> <Route path={"/users/:userId/edit"}> <EditUserContainer /> </Route> <Route path={"/users/:userId/comments"}> <UserCommentsContainer /> </Route> <Route path={"/users/:userId/comments/:commentId"}> <UserCommentContainer /> </Route> <Route render={() => <Redirect to={"/"} />} /> </Switch>
Three of which have a userId in the URL params and inside those components I fetch a user inside of a
useEffect
hook.Is there a way for react-router-dom to allow me to do this fetch in a single place and make the result available to EditUserContainer, UserCommentsContainer and UserCommentContainer?
-
I am basing a variable on a spreadsheet column to create PDFs in Google Apps Script. I can't get the variable to assign the correct value
I have a Google Form, and the results go to a Google Sheet. I wrote a Google Apps Script to create bulk PDFs from the spreadsheet.
There is a checkbox on the form, and the result that goes into the spreadsheet column is
Checked = "Check here if Information is same as above"
Unchecked = "" or NULL (I am not sure which)
This is the javascript to bulk create these PDFs. My problem is that it always comes through on the PDF as ☒, even if there is nothing in that column. I have tried a multitude of way of putting it in different places, using brackets, etc. to no avail. I am a SQL gal, and this is literally the first javascript I have written, so any help is appreciated.
function CreateBulkPDFs() { ///////////begin function{ const docFile = DriveApp.getFileById("1YAj3MubVRnYUpptEmc92esU0e3vP4KknrgvCO4l9BkI"); const tempFolder = DriveApp.getFolderById("1gmCPUmXsl4iwaVWv-7l43-y82cz2ENfF"); const pdfFolder = DriveApp.getFolderById("1UNHFAlvT5ZMTrIevdsIyf27SgyfO6PQQ"); const currentSheet = SpreadsheetApp.openById("1oMmL0Wfl9FSFX7_xb4RH-qc2o4qJvhlkNMTKMkwHXB8").getSheetByName("Form Responses 1"); const data = currentSheet.getRange(2, 1, currentSheet.getLastRow() - 1, 49).getDisplayValues(); //getRange(row start, column start, # of rows, # of columns) var chk; let errors = []; data.forEach(row => { ///////////begin forEach2( ///////////begin row2{ try { ///////////begin try{ if (row[1] !="Success") if (row[28] = "Check here if Information is same as above") chk = "☒"; if (row[28] != "Check here if Information is same as above") chk = "☐"; CreatePDF( row[2], row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10], row[11], row[12], row[13], row[14], row[15], row[16], row[17], row[18], row[19], row[20], row[21], row[22], row[23], row[24], row[25], row[26], row[27], //This is Check here if Information is same as above - row[28] chk, row[29], row[30], row[31], row[32], row[33], row[34], row[35], row[36], row[37], row[38], row[39], row[40], row[41], row[42], row[43], row[44], row[45], row[46], row[47], row[48], row[2] + " DOB: " + row[3], /*Name of Document*/ docFile, tempFolder, pdfFolder ); errors.push(["Success"]); } ///////////end try{ catch (err) { errors.push(["Failed"]); } } ///////////end row { ); ///////////end forEach( currentSheet.getRange(2, 2, currentSheet.getLastRow() - 1, 1).setValues(errors); } ///////////end function{
-
User input function not working properly?
In my node.js program, I have 2 user input functions. Before I added the 2nd one, it was working perfectly fine. After adding the 2nd one, the program directly goes to the 2nd one and executes that and completely skips the area of the code with the 1st user input function. I'm not sure why this could be? Is there a way I could have the entire program execute from top to bottom?
-
Add products to the cart jQuery/Ajax/Symfony/Twig
I am using session array as a cart in my store. So everytime I add new product to the cart I also update my total value of the cart that looks like:
<a class="navbar-brand px-3" href="{{path('checkout')}}" id="cart">Cart{{total}}€</a>
The problem is that the pages is reloaded every time i add a new product, because of
return $this->redirectToRoute('eshop');
in my add_product function.I want to add products and update the total value, without reloading the whole page. How can I implement jQuery and AJAX in this situation? And what changes should be done in add_product function?
I tried this but the product is not declared variable.
<script> $(document).ready(function() { $('#btnAddProduct').click(function() { var pos = $('{{product.id}}').val(); $.ajax({ url: "{{path('add_product', {'id' : 'id'}) }}", type: "POST", data: }, success: function() { } }); }); });
My products looks like this.
{% for product in products %} <div class="col-lg-2"> <div class="card mb-3"> <img src="{{asset(product.image)}}" class="img-fluid" alt="{{product.name}}"> <h5 class="text-center" >{{product.name}}</h5> <p class="text-center" >€{{product.price}}</p> <form action="{{path('add_product', {'id' : product.id}) }}" method="post"> <button id="btnAddProduct" class="btn btn-primary btn-block" type="submit" >Add product</button> </form> </div> </div> {% endfor %}
And also my add_product method in Symfony:
/** * @Route("/eshop/add_product/{id}", name="add_product") */ public function add_product($id,Request $request){ $product = $this->eshop_model->get_product($id); $total= $this->session->get('total'); $basket = $this->session->get('basket'); $check = 0; foreach($basket as $k => $v){ if($v['id'] == $product['id']){ $basket[$k]['quantity']++; $basket[$k]['subtotal'] += $product['price']; $check = 1; break; } } if($check == 0){ $a = array('id' => $product['id'], 'quantity' => 1, 'subtotal' => $product['price'], 'price' => $product['price'], 'name' => $product['name']); array_push($basket,$a); } $total= $total+ $product['price']; $this->session->set('total',$total); $this->session->set('basket',$basket); return $this->redirectToRoute('eshop'); }
-
How to check if jQuery, $ is called with a specific selector in Jasmine?
My Code:
$('#test1').val('string1');
I'm able to test if val has been called with 'string1'.
spyOn($.fn, 'val'); expect($.fn.val).toHaveBeenCalledWith('string1');
But I want to test if $ has been called with a specific selector. I want to be able to do this.
expect($.fn).toHaveBeenCalledWith('#test1');
-
refresh dataTable passing new values to the url
I have a reporting page where I have a dataTable that is fetching data from the database. It has a button to refresh the data so that if some data have been added or edited it will refresh the view (and everything works fine).
The code so far is:
$('#estrai').click(function(e){ e.preventDefault(); var dataDa = $('#data_da').val(); var dataA = $('#data_a').val(); var banca = $('#banca').val(); $('#report').DataTable({ destroy: true, "ajax": { "url": "endpoints/reporting.php?dataDa="+dataDa+"&dataA="+dataA+"&conto="+banca+"&anagrafica=banca", "dataSrc": "" }, "language":{ "sEmptyTable": "Nessun dato presente nella tabella", "sInfo": "Vista da _START_ a _END_ di _TOTAL_ elementi", "sInfoEmpty": "Vista da 0 a 0 di 0 elementi", "sInfoFiltered": "(filtrati da _MAX_ elementi totali)", "sInfoPostFix": "", "sInfoThousands": ".", "sLengthMenu": "Visualizza _MENU_ elementi", "sLoadingRecords": "Caricamento...", "sProcessing": "Elaborazione...", "sSearch": "Cerca:", "sZeroRecords": "La ricerca non ha portato alcun risultato.", "oPaginate": { "sFirst": "Inizio", "sPrevious": "Precedente", "sNext": "Successivo", "sLast": "Fine" }, "oAria": { "sSortAscending": ": attiva per ordinare la colonna in ordine crescente", "sSortDescending": ": attiva per ordinare la colonna in ordine decrescente" } }, dom: 'Bfrtip', buttons: [ {extend: 'copy', text: '<i class=" fa fa-clipboard"></i> Copia', className: 'standard-button btn btn-small'}, {extend: 'excelHtml5', text: '<i class=" fa fa-file-excel-o"></i> Excel', className: 'standard-button btn btn-small'}, {extend: 'pdfHtml5', text: '<i class=" fa fa-file-pdf-o"></i> Pdf', className: 'standard-button btn btn-small'}, {text: '<i class=" fa fa-refresh"></i> Aggiorna', action: function ( e, dt, node, config ) {dt.ajax.reload();}, className: 'standard-button btn btn-small'}, {text: '<i class=" fa fa-bug"></i> Segnala un bug', action: function( e, dt, node, config ){location.href = "#";}, className: 'standard-button btn btn-small bug'}, {text: '<i class=" fa fa-chevron-left"></i> Indietro', action: function( e, dt, node, config ){location.href = "/smartform/index.php";}, className: 'standard-button btn btn-small'} ], "columns": [ { "data": "id"}, { "data": "data"}, { "data": "descrizione"}, { "data": "banca"}, { "data": "movimento"}, { "data": "importo"}, { "data": "periodico"}, ], //"deferRend" : true, //"processing": true, //fixedHeader: true, //responsive: true }); });
This should redraw each time the dataTable and I'd like to know if there is a way to refresh the table by passing new
dataDa
,dataA
andbanca
parameters (from the form) without having to redraw the table.I had a look at
ajax.reload
but it is not accepting new parameters, only performing again the same request