Prisma Nextjs Getting undefined session before getting to submitData on form

I am making an edit function for objects in my postgres database. I am using nextauth as well for my session. When I try to submit form data (like updating the fields defined in my schema), I get an error, client_fetch_error undefined Posting to the database works just fine. (By the way I am new to web development as a whole)

I am using next version 12.1.2 and next-auth 4.24.6

Apologies if I didn’t include some information that would be useful, ask away if I left out anything.

Here is the route that has all of the code for the edit page,

import React, { useState } from "react";
import { GetServerSideProps } from "next";
import ReactMarkdown from "react-markdown";
import Layout from "../../../components/Layout";
import Router from "next/router";
import { PostProps } from "../../../components/Post";
import prisma from '../../../lib/prisma'
import { useSession } from "next-auth/react";

export const getServerSideProps: GetServerSideProps = async ({ params }) => {
  const course = await prisma.course.findUnique({
    where: {
      id: String(params?.id) ,
    },
    include: {
      author: {
        select: { name: true, email: true,},
      },
    },
  });
  return {
    props: course,
  };
};

const Post: React.FC<PostProps> = (props) => {
  const { data: session, status } = useSession();
  if (status === 'loading') {
    return <div>Authenticating ...</div>;
  }
  const userHasValidSession = Boolean(session);
  const postBelongsToUser = session?.user?.email === props.author?.email;
  let title = props.title;
  
  title = `${title}`;
  
  const [desc, setDesc] = useState("");
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");
  const [number, setPhone] = useState("");
  const [courseid, setCourseid] = useState("");

  const submitData = async (e: React.SyntheticEvent) => {
    console.log("got to submit")
    e.preventDefault();
    try {
      const body = { title, courseid, name, email, number, desc };
      await fetch(`/api/post/${props.id}`, {
        method: "PUT",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      await Router.push("/");
    } catch (error) {
      console.error(error);
    }
  };

  return (
    <Layout>
      <div>
        <h2>{title}</h2>
        <p>By {props?.author?.name || "Unknown author"}</p>
        <ReactMarkdown children={props.desc} />
        <form onSubmit={submitData}>
          
          <h3>Course ID</h3>
          <input
            autoFocus
            onChange={(e) => setCourseid(e.target.value)}
            placeholder="e.g. Math 301"
            type="text"
            value={courseid}
          />
          
          <h3>Teacher's Name</h3>
          <input
            autoFocus
            onChange={(e) => setName(e.target.value)}
            placeholder="Teacher Name"
            type="text"
            value={name}
          />
          <h3>Email</h3>
          <input
            autoFocus
            onChange={(e) => setEmail(e.target.value)}
            placeholder="Email"
            type="text"
            value={email}
          />
          <h3>Phone</h3>
          <input
            autoFocus
            onChange={(e) => setPhone(e.target.value)}
            placeholder="Number"
            type="text"
            value={number}
          />
       
          <textarea
            cols={50}
            onChange={(e) => setDesc(e.target.value)}
            placeholder="Important Notes"
            rows={8}
            value={desc}
          />
           {userHasValidSession && postBelongsToUser && (
          <button type="submit">Edit</button>
        )}
          <a className="back" href="#" onClick={() => Router.push("/")}>
            or Cancel
          </a>
          
        </form>

      </div>
      
    </Layout>
  );
};

export default Post;

Is there a way to see exactly what objects the GC is recycling during “Major GC” events in the profiler?

I’m currently writing an Electron/Typescript based game with a render loop. I’ve been developing it for about a year but have only just discovered that the game has horrible memory issues if the render loop goes on too long (while profiling performance, I eventually see “Major GC” events that cause lag and interrupt/skip frames. I believe there must be an object that’s not being correctly managed somewhere (I’ve tried to adhere to high performance best practices, memory pooling, no new allocations during render, etc.)

Is there any way that I can see exactly what the GC is recycling during these frames so I can isolate the leak?

I’ve tried profiling memory, but this only seems to show new allocations rather than what’s being deallocated (I create large pools of objects at the start of rendering, and I guess some of them are not being recycled properly). There doesn’t seem to be any way through the performance tab to dig any deeper into what’s actually happening in the major GC frames. I’ve tried console logging out every allocation I think I’m making and counting when they’re returned to the pool, but nothing obvious is emerging.

React-Redux could not find react-redux context value when using useSelector

i created a store and authreducer and every thik work as expected
but when i add the use sellector in app .js i got this err

ERROR  Error: could not find react-redux context value; please ensure the component is wrapped in a <Provider>  

(I have tried using useSelector in other files without any errors. )

enter image description here

import { ApolloClient, ApolloProvider } from "@apollo/client";
import { Provider, useSelector } from "react-redux";
import Navigation from "./navigation";
import Navigation2 from "./navigation2";
import { store } from "./src/Redux/store";
import InMemoryCacheFct from "./src/apolloClient/InMemoryCache";

export default function App() {

  const user = useSelector(state => state.auth.isAuthenticated);// the err is when i add this line even he works in other files

  const client = new ApolloClient({
    uri: ".......serverUrl",
    cache: InMemoryCacheFct(),
    queryDeduplication: true,
  });

  return (
    <ApolloProvider client={client}>
      <Provider store={store}>
        {user ? <Navigation /> : <Navigation2 />}
      </Provider>
    </ApolloProvider>
  );
}

TypeError: ollama.chat is not a function in Node.js with the ollama module

I’m working on a Node.js project where I’m trying to use the ollama (ollama-js) module. However, when I call the async function chatWithLlama() (which has ollama.chat() inside), I encounter the following error:

TypeError: ollama.chat is not a function

Here’s the relevant code snippet:

const ollama = require('ollama');

async function chatWithLlama() {
  try {
    const response = await ollama.chat({
      model: 'llama3',
      messages: [{ role: 'user', content: 'Why is the sky blue?' }],
    });
    console.log(response.message.content);
  } catch (error) {
    console.error('Error:', error);
  }
}

chatWithLlama();

I have made sure that the ollama module is properly installed using npm and included in the package.json file and node_modules directory. I also have Ollama running on my Mac, with llama3 already installed. How can I resolve this issue?

How can I make my popup appear fully visible on Google map with React?

What I’m doing:

  1. I’m using @react-google-maps/api with React, rendering some markers + popup div.
  2. I’m using OverlayView for the markers on the map.
  3. When I click a pin – I show an info div for that pin.
  4. The info popup div is currently a Box element from ChakraUI, that can change if need be. But it shouldn’t make any difference.

What I would like:

  • I want to ensure that the popup div is fully visible, not cut off, depending on the position of the map relative to its bounds.

I would be happy to have either of the following:

  • Move the map so the info window is fully visible.
  • Position the info window differently so that it’s fully visible.

I’ve not had any success yet, just can’t find a way to do it. Any help would be appreciated.

Here’s the React markup, showing how I’m rending the marker with the price, and the info popup

  return (
    <>
      <OverlayView position={props.position} mapPaneName={OverlayView.OVERLAY_MOUSE_TARGET}>
        <Box>
          <Card                      
            id={`marker-${props.markerIndex}`}
            border={'1px solid rgb(221, 222, 224)'}
            borderRadius={'24px'} 
            width={'max-content'}  
            onClick={props.onClick}  
            color={ (props.isSelected || props.isHoveringResult) ? 'white': 'black' }     
            backgroundColor={ (props.isSelected  || props.isHoveringResult) ? 'black': 'white' }>
            <CardBody padding={'8px'} textAlign={'center'}> 
              <Text fontSize={'14px'} fontWeight={'bold'}>
                {priceStr}
              </Text>
            </CardBody>
          </Card>


          {/* Desktop display item sticks to map and moves. */}
          { props.isSelected && 
            <Box 
              id={`markerPopup-${props.markerIndex}`}
              onClick={() => {
                event.stopImmediatePropagation();
              }}
              width={{ base: '100%', sm: '400px'}}
              position={'relative'} marginTop={'16px'}
              zIndex={'tooltip'}>
              <HotelSearchResultDisplayMapItem />
              <Box pos={'absolute'} right="8px" top="8px" cursor={'pointer'}>
                <FontAwesomeIcon             
                icon={solidCircleXMark} 
                size='3x'
                color='white'
                />
              </Box>         
            </Box>
          }        
        </Box>
      </OverlayView>
    </>
  );

Here’s what it looks like so far:

You can see that because my marker is lower down, the popup is cut-off.

enter image description here

How many series does echart support for line graph

I have an array of user objects. Each user has an array of dates. For each date there is an “activity counter”. I would like to output this information as a line graph using echart.js, where the x axis is the date, y is the activity bar, the line on the graph is the individual user.
I see big performance problems with more than 200 users on the graph. I don’t understand if echart really can’t render 200 lines well or if the problem is in my data?
I transfer data for each user as a separate series:

const options = {
  //
  //...some basic settings,
  series: [
    {
      "type": "line",
      "data": "0", "0", "7", ...other ~30 activity-points..., "3"
    },
    {
      "type": "line",
      "data": "15", "43", "17", ...other ~30 activity-points..., "6"
    },
    ...other ~200 data-objects
  ]
}
myChart.setOption(option);

I have now reproduced the example locally to encapsulate the environment, on a blank page, just a script with a graph, with minimal settings. And I get performance problems when trying to interact with a graph: mouseMove causes huge rendering lags. The more settings you make (for example, add a stack option to display a line graph), the worse it gets.

Expo error: Uncaught Error: java.lang.Exception: Failed to load all assets

When I start expo server using npx expo start -c server starts. My mobile and laptop are also connected on the same network. Now when I scan expo qr code through expo go in mobile, it displays error saying Uncaught error: java.lang.Exception: Failed to load all assets sometimes displays timeout error. What’s the issue? It’s fresh project just installed everything.

In package.json file as per the documentation i’ve set

{
   .....
   "main": "expo-router/entry",
   .....
}

and project folder structure like

......
app
  _layout.jsx
assets
node_modules
.....
......

Getting nth child count from a div class using javascript

I am trying to find count or nth child from here. As per below I should get 3 and dynamically it will change based on number results.

<div class="result-container list-layout-container">
   <div class="list-layout">Result1</div>
   <div class="list-layout">Result2</div>
   <div class="list-layout">Result3</div>
</div>

so, I used the below function to get the length 3 but I am not getting it instead I am getting undefined or 0.
Please suggest.

var len = document.getElementsByClassName('result-container').length;
console.log("Length count is", len);

How to strip the digit from a string

I am trying to extract a number from a string using regex for javascript.

Test cases

value[0]        ---> 0
value[1]        ---> 1
object2value[0] ---> 0
object90        ---> no match

i tried using ([w]+)*?[d] but it give

value[0]        ---> value[0]
value[1]        ---> value[1]
object2value[0] ---> object2value[0]
object90        ---> no match

how i can achieve this.

How to check if a user’s answer is valid and re ask the question if it is not in javascript?

I am making a choose your own adventure story game and I am trying to take a user’s input and see whether they typed “n” or “y” and if they didn’t re-ask the question. Currently, when typing in something other than “y” or “n” the code works and re-asks the question.

However, when the user inputs “n” I want the code to update the variable choice to false and run code that tells the user they have failed and asks them if they would like to try again. This code does not run and instead continues the for loop.

I assume that this code also does not work when I try to update the variable restartGame.

I am super new to coding and this is the first proper code that I have made myself outside of my highschool class instruction so any help would be amazing. 🙂

Here is the code that I made:

let food = null;

let storyParts = ["You wake up in a dark hole and an alien approaches you. His name is Tony.",
"You board Tony's ship and you see a goblin in the corner. Tony tells you it doesn't bite.",
"The goblin is visibly shaken and bites off one of your fingers.", 
"Tony feels bad and offers you food.", 
"You eat the " + food]

let storyChoices = ["Do you board his ship? (Yes / No) ", 
"Do you pet the goblin? (Yes / No) ", 
"Spin for food? (Yes / No) ",
"Try again? (Yes / No) "]

let failStatements = ["Tony is disappointed in you. He was your father the whole time. Game over.", 
"Tony is upset. He asks you to leave. Game over."]

let foodOptions = ["pizza", "cupcake", "goblin soup", "finger", "pasta"]

function userInput(line) {
    while (1) {
        let answer = readLine(line);
        if (answer == "y") {
            break;
            return true;
        } else if (answer == "n") {
            break;
            return false;
        } else {
            println("Please type 'y' for yes and 'n' for no.");
        }
    }
}

for (let i = 0, len = storyParts.length; i < len; i++) {
    println(storyParts[i]);
    let choice = null;
    if (i == 0) {
        choice = userInput(storyChoices[0]);
    } else if (i == 1) {
        choice = userInput(storyChoices[1]);
    } else if (i == 4) {
        choice = userInput(storyChoices[2]);
    } else {
        
    }
    if (choice == false) {
        let restartGame = userInput(storyChoices[3]);
        if (restartGame == true) {
            i = -1;
            continue;
        } else if (restartGame == false) {
            i = len;
            break;
        } else {

        }
    }
}

The output is below. As you can see when I first type n it continues to the next part of the story when I want it to show the fail statement and ask if I would like to restart the story.

You wake up in a dark hole and an alien approaches you. His name is Tony.
Do you board his ship? (Yes / No) n
You board Tony's ship and you see a goblin in the corner. Tony tells you it doesn't bite.
Do you pet the goblin? (Yes / No) y
The goblin is visibly shaken and bites off one of your fingers.
Tony feels bad and offers you food.
You eat the null
Spin for food? (Yes / No) e
Please type 'y' for yes and 'n' for no.
Spin for food? (Yes / No) e
Please type 'y' for yes and 'n' for no.
Spin for food? (Yes / No) n

“How to Troubleshoot File Saving Issues When Uploading to Server?”

“Hello Community,

I’m currently working on a client-server application, and I’ve encountered an issue when uploading files to the server. It seems that when I upload a file, it’s not being saved with its original name, extension, or content. For instance, if I upload a file named ‘file.txt’ containing specific information, it’s saved on the server simply as ‘upload’, without retaining its original name, extension, or content.

Could anyone advise me on how to ensure that files uploaded to the server are saved with their original name, extension, and content intact? Any help on resolving this matter would be greatly appreciated.

Thank you!”

client

import socket
import os

HOST = 'localhost'
PORT = 5173

def subir_archivo(socket_cliente, nombre_archivo):
    socket_cliente.sendall(b"subir")
    socket_cliente.sendall(nombre_archivo.encode('utf-8'))

    with open(nombre_archivo, 'rb') as archivo:
        contenido = archivo.read()
    socket_cliente.sendall(contenido)

    print("Archivo enviado al servidor:", nombre_archivo)

def descargar_archivo(socket_cliente, nombre_archivo):
    socket_cliente.sendall(b"descargar")
    socket_cliente.sendall(nombre_archivo.encode('utf-8'))

    respuesta = socket_cliente.recv(1024)
    if respuesta == b"EXISTE":
        contenido = socket_cliente.recv(1024)
        with open(nombre_archivo, 'wb') as archivo:
            archivo.write(contenido)
        print("Archivo descargado:", nombre_archivo)
    else:
        print("El archivo no existe en el servidor.")

opcion = input("¿Qué acción deseas realizar? (subir/descargar): ").lower()

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as cliente:
    cliente.connect((HOST, PORT))

    if opcion == 'subir':
        nombre_archivo = input("Ingrese el nombre del archivo que desea subir: ")
        subir_archivo(cliente, nombre_archivo)
    if opcion == 'descargar':
        nombre_archivo = input("Ingrese el nombre del archivo que desea descargar: ")
        descargar_archivo(cliente, nombre_archivo)

server

import socket
import hashlib
import threading

HOST = "localhost"
PORT = 5173

def receive_file(client_socket):
    # Receive the file name from the client
    file_name = client_socket.recv(1024).decode()
    
    # Receive the file content from the client
    file_content = client_socket.recv(1024)
    
    # Receive the hash of the file from the client
    received_hash = client_socket.recv(1024).decode()

    # Calculate the hash of the received file content
    calculated_hash = hashlib.sha256(file_content).hexdigest()

    # Write the received file content to a file
    with open(file_name, 'wb') as file:

        # Check if the calculated hash matches the received hash
        if calculated_hash == received_hash:
    
            # Write the file content to the file
            with open(file_name, 'wb') as file:
                file.write(file_content)
            print(f"File '{file_name}' received and saved successfully.")
            # Send acknowledgment to the client
            client_socket.send("ACK".encode())

def handle_client(client_socket):
    # Call the receive_file function to handle file receiving
    receive_file(client_socket)
    # Close the client socket
    client_socket.close()

def main():
    # Create a server socket
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Bind the server socket to the specified host and port
    server.bind((HOST, PORT))
    # Listen for incoming connections
    server.listen()
    print("Server waiting for connections...")

    while True:
        # Accept a client connection
        client_socket, client_address = server.accept() 
        print(f"Connection accepted from {client_address}")
        
        # Create a new thread to handle the client
        client_thread = threading.Thread(target=handle_client, args=(client_socket,))
        client_thread.start()

main()

````

Send Livewire data from component to JS library

I have a livewire component that incorporates a js library, gridstack.js.

I’ve never tried to incorporate an external js library without a livewire wrapper before. Caleb made it so easy to implement livewire/sortable since I didn’t have to write any js. I’m trying to use Gridstack.js as if I were using Shopify/draggable directly with livewire without using livewire/sortable.

This is what I have so far and my interactive grid loads correctly. I’m able to adjust gridstack items on the page and save them to the database via $wire.taskMoved(newItems) in the @script, all as expected. I need to be able to display a new or edited $task that’s created with livewire. Right now I need refresh the page to see any edited or added $task that was created in the backend.

I started to experiment with this below with the following code. It works, everytime I edit or add a task I receive a console log but I’m not sure what to put here from the gridstack api to have those items updated.

document.addEventListener('taskAdjusted', () => {
   console.log('HERE after taskAdjusted')
})

I also tried to add wire:key="project-{{$project->id}}" in the $projects foreach and wire:key="task-{{$task->id}}" in the $tasks foreach but it didnt work so I found that wire:ignore on the div works best.

<div>
    @foreach($projects as $project)
        <div class="grid-stack gs-id-{{$project->id}}" id="{{$project->id}}" wire:ignore>
            @foreach($days as $day_index => $day)
                @foreach($day->tasks as $task)
                    <div class="grid-stack-item" gs-x="{{$day_index}}" gs-w="{{$task->duration}}" gs-y="1" gs-id="{{$task->id}}">
                        <div
                            wire:click="$dispatchTo('tasks.task-create', 'editTask', { task_id: {{$task->id}} })"
                            class="grid-stack-item-content"
                            >
                            <span>{{$task->title}}</span>
                        </div>
                    </div>
                @endforeach
            @endforeach
        </div>
    @endforeach

    <livewire:tasks.task-create :projects="$projects" :days="$days"/>
</div>

@assets
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gridstack.js/10.1.2/gridstack-all.js" defer></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/gridstack.js/10.1.2/gridstack.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/gridstack.js/10.1.2/gridstack-extra.min.css">
@endassets

@script
    <script>
        let grids = GridStack.initAll({
            column: 6,
            cellHeight: '60px',
            cellWidth: '100px',
            float: false,
            resizable: {
                handles: 'e'
            },
            margin: 2
        })

        grids.forEach(grid => {
            grid.on('change', function(event, items) {
                let newItems = []

                items.forEach ((el) => {
                    newItems.push({_id: el._id, x: el.x, y: el.y, w: el.w, task_id: el.id})
                });

                $wire.taskMoved(newItems)
            })
        })

        document.addEventListener('taskAdjusted', () => {
            console.log('HERE after taskAdjusted')
        })
    </script>
@endscript

This is a follow up question to a previous one that you guys were able to help me with, Thank you!

What am I doing wrong on this dark mode button?

I started coding today and I’m trying to make a simple static dark mode button, but the background of the button doesn’t change his color, i already fixed one thing on the line 36 on CSS it was “–bg: var(–gren);” but the screen would be black when i clicked (https://i.stack.imgur.com/CYUB4.png):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>site</title>
    <link rel="stylesheet" href="main.css">
</head>
<body class="light-theme">
    <h1>Task List</h1>
    <p id="msg">Current tasks:</p>
    <ul>
        <li class="list">Add visual styles</li>
        <li class="list">Add light and dark themes</li>
        <li> Enable switching the theme</li>
    </ul>
    <div>
        <button class="btn">Dark</button>
    </div>
    <script src="app.js" defer></script>
    <noscript>You need to enable JavaScript to view the full site.</noscript>
</body>
</html>

body {
    font-family: monospace;
}
ul {
    font-family: Arial, Helvetica, sans-serif;
}

li {
    list-style: circle;
}

.list {
    list-style: square;
}

.light-theme {
    color: black;
    background: #00FF00;
    
}

:root {
    --green: #00FF00;
    --white: #ffffff;
    --black: #000000;
}

.light-theme {
    --bg: var(--green);
    --fontColor: var(--black);
    --btng: var(--black)
    --btnFontColor: var(--white)
}

.dark-theme {
    background: var(--black);
    --fontColor: var(--green);
    --btnBg: var(--white)
    --btnFontColor: var(--black)
}

* {
    color: var(--fontColor);
    font-family: Arial, Helvetica, sans-serif;
}

body  {
    background: var(--bg);
}

.btn {
    color: var(--btnFontColor);
    background-color: var(--btnBg);
}

.btn {
    position: absolute;
    top: 20px;
    left: 250px;
    height: 50px;
    width: 50px;
    border-radius: 50%;
    border: none;
    color: var(--btnFontColor);
    background-color: var(--btnBg);
}


.btn:focus { outline: none; }




 'use scrict'

const switcher = document.querySelector('.btn');

switcher.addEventListener('click', function() {
    document.body.classList.toggle('dark-theme')

    var className = document.body.className;
    if(className == "light-theme") {
        this.textContent = "Dark";
    }   
    else {
        this.textContent = "Light"
    }

    console.log('current class name: ' + className);
});
enter image description here

how it was supposed to be: (https://i.stack.imgur.com/SGUMf.png)

Open a new HTML page in a JS function and then write some HTML on it when the previous html is a login page

hi im trying to make a login page that after you push the button it goes to the index. I did that but now i want to change part of the html to say welcome back ( and the name of the username)

i’ve wrote this so far but i dont know how to save the username so i can use it again in the next page.

this is the html:

<form id="login-form">
<!--Error Message-->
        <div id="login-error-msg-holder">
      <p id="login-error-msg">Invalid username <span id="error-msg-second-line">and/or password</span></p>
    </div>

<!--Form-->
    <div class="form-floating">
      <input type="name" class="form-control name " name="name" id="floatingInput" id="name-field" placeholder="user123">
      <label for="floatingInput">Username</label>
    </div>
    <div class="form-floating">
      <input type="password" id="password-field" class="form-control" id="floatingPassword" name="password" placeholder="Password">
      <label for="floatingPassword">Password</label>
    </div>

    <div class="form-check text-start my-3">
      <input class="form-check-input" type="checkbox" value="remember-me" id="flexCheckDefault">
      <label class="form-check-label" for="flexCheckDefault">
        Remember me
      </label>
    </div>
    <button class="btn w-100 py-2" id="login-form-submit" value="Login" type="submit">Sign in</button>
    <p class="mt-5 mb-3 text-body-secondary">&copy; 2017–2024</p>
  </form>
</main>

And this is the js:

window.onload=loginButton.addEventListener("click",(e) => {
    e.preventDefault();
    const name = loginForm.name.value;
    const password = loginForm.password.value;

    if (name === "user123" && password === "1") {
        window.location.href = 'index.html';

    } else {
        loginErrorMsg.style.opacity = 1;
    }
})

function message(){

        if (window.history='Login.html' ) {
        document.getElementById('navlogin').innerHTML='Welcome back'+ name + '!';
        }
        
        else{
            document.getElementById('navlogin').innerHTML='';
        }
}

i tried using the console.log but i cant save it for a little time so i can use it later.

any ideas?

How to show a data-toggle class with ajax and php

I have difficulties with the legagy code. I need to implement the function that opens de data-toggle, I have include parsedResponse in the verify data, since is the responsible to show the response of info. But it’s not working.. sobody help?

function checkInfo(input_data) {
var requestData = {
data: input_data
};
var info = input_data;
$.ajax({
url: “/endpoint/search”,
type: ‘POST’,
data: requestData,
success: function(response) {
$(‘.search_result’).html(response);
process_contacts();
process_opportunities();
verify_data(info, function(parsedResponse){
if ($(‘#collapseOne’).hasClass(‘collapse’) && !($(‘#collapseOne’).hasClass(‘show’)) && parsedResponse.success === true){
$(‘.open_contact’).click();
console.log(parsedResponse.success);
}
});
}
});
}

function verify_data(data) {
$.ajax({
url: ‘/endpoint/verify’,
type: ‘POST’,
dataType: ‘json’,
data: {
data: data
}
})
.done(function(response) {
var parsedResponse = $.parseJSON(response);
if (parsedResponse) {
$(‘.save_info’).removeAttr(‘disabled’);
} else {
$(‘.save_info’).attr(‘disabled’, ‘disabled’);
}
return parsedResponse;
})
}

I expect to be able to reach the parsedResponse as true and do the click event.