Passing multiple POST parameters using ajax for php

I am trying to pass several parameters using the POST method using AJAX to my PHP file so that I can query the MySQL database.

HTML file:

<div class="dropdown dropdown-dark"> <select class="dropdown-select" id="searchselect11" required> <option value="faculty">Faculty</option> <option value="dept">Dept.</option> <option value="course">Course</option> <option value="year">Year</option> <option value="name">Name</option> </select> </div> <td style="padding:5px;"> <input type="text" id="searchtext11" required></td> <button id="searchgo1" onclick="searchone()"></button> 

This is a Javascript file in which I successfully access the dropdown value and text value and save it in the sv and searchtext11 respectively. But the problem is to pass two values ​​to a PHP file. The problem is the_data variable, which is passed in xmlhttp.send(the_data);

The searchone() function is as follows:

 function searchone() { //alert("hi"); var xmlhttp; var sel = document.getElementById('searchselect11'); var sv = sel.options[sel.selectedIndex].value; var searchtext11= document.getElementById("searchtext11").value; var the_data = 'select='+sv+'text='+searchtext11; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("POST", "searchone.php", true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xmlhttp.send(the_data); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4) { document.getElementById("searchresults").innerHTML = xmlhttp.responseText; } } } 

This PHP code only works if

 var the_data='select='+sv; 

searchone.php

 <?php if (isset($_POST['select'])) { $str = $_POST['select']; // get data echo $str; } ?> 

How can I get both a dropdown and a text value for my PHP file so that I can generate an SQL query using these variables.

+6
source share
2 answers

You need to use ampersand as if it were GET. In addition, you must encode the text to make sure that it does not contain characters that may have special meaning.

 var the_data = '' + 'select=' + window.encodeURIComponent(sv) + '&text=' + window.encodeURIComponent(searchtext11); // ^ ^^ 

You do not need to decrypt the server side manually, because you already make it clear that the POST data is x-www-form-urlencoded .

+8
source

add to this line:

 var the_data = 'select='+sv+'&text='+searchtext11; 
+3
source

Source: https://habr.com/ru/post/948387/


All Articles