Cannot send form data with ajax call to PHP

I know this question has been asked before but frustratingly there still appears to be no working solution. I am trying to send form data including a profile image as well as other user details to a PHP file in order to upload them. I’m trying to use FormData in order to do this but haven’t been able to get it to work so I made a really simple version of it but still can’t get the ajax to post any data.

Here is all my code:

HTML:

<form id="testForm" class="" action="" method="post" enctype="multipart/form-data">
 <input type="text" name="name" value="">
 <input type="submit" name="submit" value="Submit">
</form>

Javascript:

$('#testForm').submit(function(e){
 e.preventDefault();

 form = $("#testForm");
 var data = new FormData(form[0]);
 console.log(...data);

 $.ajax({
  url: "testFormData.php",
  type: "POST",
  data:{data},
  cache: false,
  contentType : false,
  processData: false,
  success: function(dataResult){
    console.log(dataResult);
  }
 });
});

PHP:

$testText = htmlspecialchars($_POST['name']);
echo $testText;

I know that it is reading the form data because when I log it I can see the values, however, the ajax simply returns the error Undefined array key "name" from the PHP.

Does anyone know of a way to get this working?

Values for autocomplete dropdown – ReactJS

List of dynamic values from backend need to listed in autocomplete dropdown, as user types in. I am able to get values from backend(console). But that does not get listed in the dropdown.

In the below method(onChangeInputItemNo) , when I pass "1407E24R7"(which is not available in DB), I get the value of "this.state.ItemNumberData" as 
  ['1407E2417', '1407E2420', '1407E2422', '1407E2423', '1407E2425', '1407E2426', '1407E2427', '1407E2428', '1407E2429'] from the backend. 

User has typed ‘R’ wrongly here, but backend provided values that are similar to the input sent instead of returning null.

So I expect my search autocomplete to list these values for me to select from but it does not, as “1407E24R7” has ‘R’ in it( as its not a valid data). If I give any value available in DB, Like “1407E2417”, I get that value as dropdown like’1407E2417′ in frontend.

May I know if it has to anything to do with ‘material UI autocomplete dropdown’ default functionality. or will it(onChangeInputItemNo) only display values that fully match.

  onChangeInputItemNo = value => {    
    getItemNoAutocomplete(value).then(
        (response) => {
            if (response.ok) {
                response.json()
                    .then((responseData) => {
                        this.setState({
                            isLoading: false,
                            ItemNumberData: responseData
                        })
                        console.log("ItemNos", this.state.ItemNumberData)
                    });
            }
           
        })
        
    } 


<Autocomplete
     value={this.state.currentItem.itemNo}
     options={this.state.ItemNumberData}
     renderOption={(option) => (
            <Typography class="typography">{option}</Typography>
     )}
      getOptionLabel={option => option}
      autoHighlight={true}                                                                                          
      renderInput={params => (
      <TextField                                                       
                {...params} 
                 onChange={e => this.onChangeInputItemNo(e.target.value)} 
                label="Search" variant={"outlined"}
                size="small" fullWidth />
     )}                                                                                                                                      
 />
                                            

How to add a conditional in a query using firestore

I have some troubles trying to make a query.

Right now with this code I’m able to display an image stored in Firestore by using template literals and the .innerHTML but I want to inject an empty string if there is nothing in the field or if the field doesn’t exist because I don’t want to show the figure tag if it’s empty

Any help would be gladly appreciate it thanks in advance

db.collection("Ludolab").doc("offer").collection("list").doc(idRef).collection("index")
  .doc(idCon).collection("content")
    .where( 'image', '!=', false)
      .get()  
        .then(function (querySnapshot) {
          const image  = document.getElementById('image');

          db.collection("Ludolab").doc("offer").collection("list").doc(idRef).collection("index")
            .doc(idCon).collection("content").onSnapshot((querySnapshot) => {
              imagen.innerHTML = '';
              querySnapshot.forEach((doc) => {
               
                image.innerHTML +=`  
                  <figure class="image is-3by2">
                    <img src="${doc.data().image}">
                  </figure>
                `
            });
          }); 
        })


enter image description here

Need to display WITH different questions on each button click in React

-2

I need to display different questions on each button click in React Quiz app. Tried to pass state from one component to other in an array but never showed different question. New to react please help.

Code help: https://codesandbox.io/s/pop-up-react-forked-rsypkh?file=/src/styles.css

Tried to apply onclicks in react but shows same question on each butoon click and expected to have different question

encode object into cookie string for testing

I’m using cookies to pass the session about the logged in user, and on the server I can set and get them fine:

res.cookie("foo", { bar: "baz" })

// later on
console.log(req.cookies.foo) // { bar: "baz" }

now I want to test that, and I need to set the cookie header, but I don’t know how to convert an object, i.e. { bar: "baz" }, to the header string the cookie evaluates to
enter image description here

What’s the algo used here?

(I’m using supertest but it shouldn’t matter IMO)

How to handle the Amchart 5 cursor height?

How to make the Amchart 5 cursor height dynamic based on the series shape? To only show under the graph.

It can be achieved in amCahrts 3 using limitToGraph and in amCharts4 using chart.cursor.snapToSeries = series;. But could not find any settings on amCharts5.

enter image description here

Installing npm on ubuntu server 20.04 causing fullpage.js to stop working

I’m actually hosting my website on a vps using ubuntu server 20.04 and it was working well until I installed npm on it with :
sudo apt install npm
As I said in the title, my website is using fullpage.js and when I install npm fullpage.js is stopped. You can see on the screenshot the before/after installing npm.
After deleting npm, everything went back to normal.
before
after

I tried to delete the link to fullpage.js on my index.html file and the result is the same as after installing npm on the server. I assumed that the problem was coming from this file but I can’t figure why it is happening.

How to include all input value from HTML into req.body: Node.js (Express)

I am trying to get a value of checkbox, “1” in the following html, through req.body. However, in the req.body, username and password values are only included (passwordConfirm is not included in the req.body as well).
How can I include the values of passwordConfirm and checkbox in req.body?

<form action="/register" method="POST">
        
        <label for="username">Username:</label>
        <input type="text" id="username" name="username"><br><br>
    
    
        <label for="password">Password:</label>
        <input type="password" id="password" name="password"><br><br>
    
    
        <label for="passwordConfirm">Confirm Password:</label>
        <input type="password" id="passwordConfirm" name="passwordConfirm"><br><br>
    
    
        <label>?</label>
        <input type="checkbox" id="checkbox" name="checkbox" value="1"><br><br>
    
        <button type="submit">Submit</button>

</form>

index.js

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.post(“/register”, (req, res) => {
console.log(req.body); //only returns {username:”something”, password:”something”}
});

I put <script> in html to include a function that returns the value of checkbox with document object and called the function in a controller.js file for a purpose, but it did not work (I do not know how to use client-side js function in server-side js file).

tab bane bootstrap buttons disappear after clicking on another tab

My tab pane has a grid table that should be displayed in 4 languages the bootstrap buttons only appear in the english pane but disappear when i click on another language pan

This is my view

English pane

Arabic paneThis is what i tried i expect that the buttons appear in every pane

That is my English tab and french tab respectively what am i missing

  <div class="tab-pane fade show active " id="nav-0{{$language->abbreviation}}" role="tabpanel" aria-labelledby="nav-en-tab">
                            <div class="row">
                                <div class="col-12">
                                  <div class="table-responsive">
                                    <table id="zero_config" class="table table-striped table-bordered">
                                        <thead>
                                            <tr>
                                                <th scope="col">Degree</th>
                                                <th scope="col">Degree Type</th>
                                                <th scope="col"></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach($degrees_en as $en)
                                            <tr>
                                                <td name="unit_nameEn">{{$en->degree_name}}</td>
                                             
                                                <td>{{$en->type_inf->degree_type_name}}</td>
                                               
                                                    <td>
                                                        <div class="d-flex">
                                                
                                                
                                                            <!-- Edit Modal -->
                                                            <form action="{{ route('unit.update', $en->degree_id) }}" name="edit_unit" method="POST" id="editUnit{{$en->degree_id}}">

                                                            <div class="modal fade" id="editModal{{$en->degree_id}}" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="editModalLabel{{$en->degree_id}}" aria-hidden="true">
                                                                <div class="modal-dialog modal-xl" role="document">
                                                                    <div class="modal-content">
                                                                    <div class="modal-header">
                                                                        <h2 class="fw-bolder" id="editModalLabel{{$en->degree_id}}">Edit</h2>
                                                                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                                        </button>
                                                                    </div>

                                                                    <div class="modal-body">
                                                                        <div class="row">                          

                                                                          <div class="col-4">
                                                                            <div class="row">
                                                                             
                                                                              <div class="col-12">
                                                                                <div class="form-group">
                                                                                  <label> Degree Type </label>
                                                                                  <select id="type_id" name="type_id" class="select form-select shadow-none" style="width: 100%; height: 36px" required>
                                                                                   
                                                                                        <option value="ss" selected>hbu</option>
                                                                                     
                                                                                   
                                                                                  </select>
                                                                                </div>
                                                                              </div> 
                                                                            </div>
                                                                          </div>

                                                                          <div class="col-4">
                                                                            <div class="row">
                                                                              <div class="col-12">
                                                                                <div class="form-group">
                                                                                    <label> Degree Name </label>
                                                                                    <input type="text" name="unit_nameFr" class="form-control bg-light" placeholder="Add french unit" value="{{ $en->degree_name}}" required>
                                                                                </div>
                                                                              </div>
                                                                              
                                                                            </div>
                                                                          </div>  
                                                                        </div>
                                                                    </div>


                                                                    <div class="modal-footer">
                                                                        <button type="submit" class="btn btn-info float-end" onclick="document.getElementById('editUnit{{$en->degree_id}}').submit();">Save changes</button>
                                                                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                                    </div>
                                                                    </div>
                                                                    {{ csrf_field() }}
                                                                    @method('PUT')
                                                                
                                                                </div>
                                                            </div>

                                                            <div class="ml-auto">
                                                                 <!-- edit button -->     
                                                                <button type="button" id="{{$en->degree_id}}" name="edit_unit" class="btn btn-info" data-bs-toggle="modal" data-bs-target="#editModal{{$en->degree_id}}">
                                                                <span><i class="fas fa-edit"></i>Edit</span>
                                                                </button>
                                                            </div>
                                                            </form>
                                                
                                                            <div class="mr-auto">
                                                              <div class="mr-auto">
                                                                <form action="{{ route('unit.destroy', $en->degree_id)}}" method="post" id="deleteUnit{{$en->degree_id}}">
                                                                  @csrf
                                                                  @method('DELETE')
                                                                  <div class="modal fade" id="deleteModal{{$en->degree_id}}" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel{{$en->degree_id}}" aria-hidden="true">
                                                                    <div class="modal-dialog modal-xl" role="document">
                                                                        <div class="modal-content">
                                                                        <div class="modal-header">
                                                                            <h2 class="fw-bolder" id="deleteModalLabel{{$en->degree_id}}">Delete</h2>
                                                                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                                            </button>
                                                                        </div>
                                                                        
                                                                        <div class="modal-footer">
                                                                            <button type="submit" class="btn btn-info float-end" onclick="document.getElementById('deleteUnit{{$en->degree_id}}').submit();">Yes</button>
                                                                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">No</button>
                                                                        </div>
                                                                        </div>   
                                                                    </div>
                                                                </div>
                                                                  <a class="btn btn-danger" id="delete{{$en->degree_id}}" data-bs-toggle="modal" data-bs-target="#deleteModal{{$en->degree_id}}">Delete</a>
                                                                </form>
                                                              </div>
                                                            </div>
                                                
                                                            </div>
                                                 </td>
                                                
                                            </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
    
                                </div>
                            </div>
                        </div>





///////////////////////////////////////////////////////////////////////////////////////////////////////

@elseif($language->language_id==3))
                        <div class="tab-pane fade show  " id="nav-0{{$language->abbreviation}}" role="tabpanel" aria-labelledby="nav-en-tab" >
                            <div class="row">

                                <div class="col-12">
                                  <div class="table-responsive">
                                    <table id="zero_config" class="table table-striped table-bordered">
                                        <thead>
                                            <tr>
                                                <th scope="col">Degree</th>

                                                <th scope="col">Degree Type</th>
                                                <th scope="col"></th>
                                            </tr>
                                        </thead>
                                        <tbody>
                                            @foreach($degrees_fr as $fr)
                                            <tr>
                                                <td name="unit_nameEn">{{$fr->degree_name}}</td>
                                               
                                                <td>{{$fr->type_inf->degree_type_name}}</td>
                                               
                                                <td>
                                                
                                                    <div class="modal fade" id="editModal{{$fr->degree_id}}" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" role="dialog" aria-labelledby="editModalLabel{{$fr->degree_id}}" aria-hidden="true">
                                                        <div class="modal-dialog modal-xl" role="document">
                                                            <div class="modal-content">
                                                            <div class="modal-header">
                                                                <h2 class="fw-bolder" id="editModalLabel{{$fr->degree_id}}">Edit</h2>
                                                                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                                                                </button>
                                                            </div>
    
                                                            <div class="modal-body">
                                                                <div class="row">                          
    
                                                                  <div class="col-4">
                                                                    <div class="row">
                                                                     
                                                                      <div class="col-12">
                                                                        <div class="form-group">
                                                                          <label> Degree Type </label>
                                                                          <select id="type_id" name="type_id" class="select form-select shadow-none" style="width: 100%; height: 36px" required>
                                                                           
                                                                                <option value="ss" selected>hbu</option>
                                                                             
                                                                           
                                                                          </select>
                                                                        </div>
                                                                      </div> 
                                                                    </div>
                                                                  </div>
    
                                                                  <div class="col-4">
                                                                    <div class="row">
                                                                      <div class="col-12">
                                                                        <div class="form-group">
                                                                            <label> Degree Name </label>
                                                                            <input type="text" name="unit_nameFr" class="form-control bg-light" placeholder="Add french unit" value="{{ $fr->degree_name}}" required>
                                                                        </div>
                                                                      </div>
                                                                      
                                                                    </div>
                                                                  </div>  
                                                                </div>
                                                            </div>
    
    
                                                            <div class="modal-footer">
                                                                <button type="submit" class="btn btn-info float-end" onclick="document.getElementById('editUnit{{$fr->degree_id}}').submit();">Save changes</button>
                                                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                                            </div>
                                                            </div>
                                                            {{ csrf_field() }}
                                                            @method('PUT')
                                                        
                                                        </div>
                                                    </div>
                                                    </td>
                                            </tr>
                                            @endforeach
                                        </tbody>
                                    </table>
                                </div>
                                </div>
                            </div>
                        </div>

How could I change an HTML header through Javascript?

Ok, let’s say I have this HTML code, and I want to change the header from within the js code, how would I? I’ve tried several other solutions from other Q&As but they don’t seem to work, either I’m brain dead or stuck. I want to change the header based on a variable, so something like:

header = variablexyz;
<!DOCTYPE html>
<html lang="en">

<head>
    <style>
        .header {
            padding: 60px;
            text-align: center;
            background: #1746c7;
            color: white;
            font-size: 50px;
        }
    </style>
</head>

<body>
    <div class="header">
        <h1>header</h1>
        <p>-randomly generated username-</p>
    </div>
    <script src="script.js"></script>
</body>

</html>

spinner load animation not going away after page is loaded

Im testing out this simple loading animation while the page loads, after the page should be displayed or in this case, a video. Problem is that the animation keeps on going forever despite the page/ video already being loaded . The video is being embed via youtube.
Here is the code

note : Youtube video ID is an example, it does not lead anywhere but the video does load

HTML

<div class = "loadelement"><span class = "spinner"> </span></div> 
   <iframe width = "100%" height = "530"
   src = "https://youtube.com/embed/EXAMPLE" title="Youtube video player "
    frameborder = "0" allow = "accelerometer; autoplay ; clipboard-write ; encrypted-media ; gyroscope ; picture-in-picture" allowfullscreen>
</iframe>

CSS

.loadelement {
position : absolute ; top : 0 ; left : 0 ; 
height: 100vh ; width: 100%;
background: #fff ; display : flex ; 
align-items : center ; justify-content : center ; 


}

.spinner {

width : 80px ; height : 80px ; 
border : 8px solid #f3f3f3 ; 
border-radius : 50% ; 
border-top : 8px solid #01101a ;
animation: spin 2s linear infinite;
}

@keyframes spin {
0% {
 transform: rotate(0deg);
}
100% {
    transform : rotate(360deg);
}

}

Javascript

let loaderel = document.querySelector(".loadelement");
window.addEventListener("load", function() {
loaderel.style.display = "None";
});

Been trying to figure out the problem myself, any help would be greatly great. Thanks everyone.

How to use GCP DLP with a file stream

I’m working with Node.js and GCP Data Loss Prevention to attempt to redact sensitive data from PDFs before I display them. GCP has great documentation on this here

Essentially you pull in the nodejs library and run this

const fileBytes = Buffer.from(fs.readFileSync(filepath)).toString('base64');

// Construct image redaction request
const request = {
  parent: `projects/${projectId}/locations/global`,
  byteItem: {
    type: fileTypeConstant,
    data: fileBytes,
  },
  inspectConfig: {
    minLikelihood: minLikelihood,
    infoTypes: infoTypes,
  },
  imageRedactionConfigs: imageRedactionConfigs,
};

// Run image redaction request
const [response] = await dlp.redactImage(request);
const image = response.redactedImage;

So normally, I’d get the file as a buffer, then pass it to the DLP function like the above. But, I’m no longer getting our files as buffers. Since many files are very large, we now get them from FilesStorage as streams, like so

return FilesStorage.getFileStream(metaFileInfo1, metaFileInfo2, metaFileInfo3, fileId)
      .then(stream => {
        return {fileInfo, stream};
      })

The question is, is it possible to perform DLP image redaction on a stream instead of a buffer? If so, how?
I’ve found some other questions that say you can stream with ByteContentItem and GCPs own documentation mentions “streams”. But, I’ve tried passing the returned stream from .getFileStream into the above byteItem[‘data’] property, and it doesn’t work.

Validation is not working with useState hook

I am trying to validate my form so that it does not send if there is no name, or email input. I am using emailjs for the form functionality and everything is working. I’ve used this code before for validating forms when using material UI. Not sure why it’s not working.

    const form = useRef();
    

    // Validations
    const [name, setName] = useState("");
    const [error, setError] = useState("");

    const handleError = (e) => {
        setName(e.target.value);
        if (e.target.value.length < 1) {
            setError("Enter name");
        }
    }

    // send email

    const sendEmail = (e) => {
        e.preventDefault();

        emailjs.sendForm('service_utmpeng', 'template_nctmzld', form.current, 'HY5KJwrbo9eTeAd62')
            .then((result) => {
                console.log(result.text);
            }, (error) => {
                console.log(error.text);
            });
        e.target.reset()
    };
           <form ref={form} onSubmit={sendEmail}>
                <Grid container>

                           
                        {error ?
                                <p style={{ color: '#D35E3C' }}>{error}</p> : ''}
                                
                     <Grid item>

                            <TextField onChange={handleError} id="standard-basic" label="Name" name="name" variant="standard" />
                     

                     </Grid>

                   
                    <Grid item>
                        <Button type="submit" />
                    </Grid>
                </Grid>
            </form>