-1

I have array = ["h1","h2","h3","h4"] in index.html with JavaScript

how can I send it to PHP file with ajax

ali shgh
  • 9
  • 1
  • 1
    Please read all of [ask]. Notice that the very first tip says: "**Search and Research**". There are many existing pages on Stack Overflow which demonstrate how to pass data from the clientside to the serverside -- we want you to use this site as a knowledge repository primarily. If there is no trace of the advice that you seek, THEN you should post a new question. – mickmackusa Oct 31 '20 at 05:47

1 Answers1

1

In my code answers below, replace "yourfilename.php" with the PHP file you are wanting to post to, and replace "yourArrayInJavascript" with your actual JavaScript array variable.

If you are using jQuery:

$.ajax({
    type: "POST",
    url: "yourfilename.php",
    data:JSON.stringify(yourArrayInJavascript),
    success: function(html){
        console.log(html);
    }
});

If you are wanting a vanilla JavaScript answer:

fetch('yourfilename.php', {
    method: 'POST',
    body: JSON.stringify(yourArrayInJavascript),
    headers: {
        'Content-type': 'application/json; charset=UTF-8'
    }
})
.then(function (response)  {
    return response.text();
})
.then(function (data)  {
    console.log(data);
});
  • Please avoid answering questions that have been answered on Stack Overflow many times. These "mega-duplicates questions" should be closed instead of answering so that 1. askers learn that all basic questions are already answered and 2.Stack Overflow doesn't need to stockpile heaps of the same content. Please read all of [answer]. When a question asks for a basic technique, before thinking of how to answer, see if you can find a suitable existing page to close the new page with. On the old page, if you can add new, unique, valuable insights to the old page -- answer there instead. – mickmackusa Oct 31 '20 at 05:45