I'm trying to pass multiple parameters via the POST method using AJAX to my PHP file so that I can make a query to a 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 the Javascript file where I successfully access dropdown value and textbox value and store them in sv and searchtext11 variables respectively. But the problem is to pass the two values to the PHP file. The problem seems to be in the_data variable that 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 works only if
var the_data='select='+sv;
searchone.php
<?php
if (isset($_POST['select'])) {
$str = $_POST['select']; // get data
echo $str;
}
?>
How do i get both dropdown and textbox value to my PHP file so that i can form sql query using those variables.
You need to use an ampersand, just as if it was a GET. Further, you should encode your text to make sure that it doesn't contain any characters that could have a special meaning
var the_data = ''
+ 'select=' + window.encodeURIComponent(sv)
+ '&text=' + window.encodeURIComponent(searchtext11);
// ^ ^^
You don't need to decode manually server-side because you are already letting it know that POST data is x-www-form-urlencoded.
add & in this string:
var the_data = 'select='+sv+'&text='+searchtext11;
Related
I have a series of simple checkboxes.
<select>
<option class="menuoption2" value="gold">Gold</option>
<option class="menuoption2" value="silver">Silver</option>
<option class="menuoption2" value="bronze">Bronze</option>
</select>
I want to get only the checked ones into a PHP variable. However note there is no Submit button. This is on purpose and not allowed by the brief i have been given; my variables' values have to be on display in a simple <div> as soon as the checkboxes are clicked. I cannot have the page refreshed either. I know I can use $_POST - but only if i could submit anything and also I could use jQuery (indeed i have done this before) to do this but ultimately I need those values in that PHP variable, not a JS variable. Any ideas?
HTML
<select onchange="postit(event)">
<option class="menuoption2" value="gold">Gold</option>
<option class="menuoption2" value="silver">Silver</option>
<option class="menuoption2" value="bronze">Bronze</option>
</select>
JS / AJAX
Posts the value to update.php where metal=value
<script type="text/javascript">//<![CDATA[
var xmlhttp;
function postit(event){
var value = event.target.value;
xmlhttp=null;
var Url="update.php"
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp!=null) {
xmlhttp.onreadystatechange=getResponse;
xmlhttp.open("POST", Url, true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.send( "metal=" + value);
} else {
alert("UNEXPECTED ERROR: XMLHttpRequest not supported");
}
}
function getResponse(){
if (xmlhttp.readyState==4){
if (xmlhttp.status==200){
var json = JSON.parse(xmlhttp.responseText);
}
else{
alert("UNEXPECTED AJAX ERROR: : " + xmlhttp.statusText + "HTTP Status: " + xmlhttp.status);
}
}
}
//]]>
</script>
PHP
<?php
$metal = $_POST['metal'];
// This is just to validate the received data,
// mostly needed if you are storing in a database.
$metals = array('gold','silver','bronze');
$status = 'fail';
if($metals[$metal] != null){
$status = 'pass';
//store $metal
}
//To return a value to JS after the update, add the code below
$return['status'] = $status;
header(header('Content-Type: text/json; charset=utf-8');
echo json_encode($return);
?>
No Return Value to JS
Remove these two lines from the JS
var Url="update.php"
xmlhttp.onreadystatechange=getResponse;
Remove the function getResponse()
move global var xmlhttp; into the postit() function as a local var:
From
var xmlhttp;
function postit(){
To
function postit(){
var xmlhttp;
I have some html pages about movies, all containing the same search form. When the user types something in the form, I want the site to jump to movies-overview page. I already made a search function without ajax, but with a simple post request that searches the database en echos a movielist. But now I want the same to happen everytime a user presses a key.
this is the search form:
<form action='films.php' method='post'>
<input id="ZoekBalkSearch" type="search" name="zoekparameter" placeholder="Geef een zoekterm in." onkeyup="gaNaarFilm(this.value)"/>
<input id="ZoekButton" type="submit" value="Zoek"/>
</form>
and this is my ajax code:
function gaNaarFilm(str)
{
if (str.length==0)
{
document.getElementById("ZoekBalkSearch").innerHTML='';
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("ZoekBalkSearch").innerHTML=str;
}
}
xmlhttp.open("POST",'films.php',true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send('zoekparameter='+str);
}
the function is called but it doesn't seem to do anything, could someone please help me? thanks in advance.
fist of all you pass this and not this.value
then a short function i use for ajax is this
var ajax=function(a,b,c){c=new XMLHttpRequest;c.open('GET',a);c.onload=b;c.send()}
this has low support (no ie5 and ie6) but can be extended.
then as u lauche the code directly from your element you can access your value directly inside the ajax.
so:
JS
FormData() stores the whole content of your form
the ajax() function posts to film.php
in film.php u can retrieve the value with $_POST['zoekparameter']
the response executes fu()
this is done by adding a eventListener in javascript to the input field which is keyup.
var ajax=function(){
var fd=new FormData(document.querySelector('#form'));
var c=new XMLHttpRequest||new ActiveXObject("Microsoft.XMLHTTP");
c.open('POST','film.php');
c.onload=fu;
c.send(fd)
},
fu=function(){
document.getElementById("ZoekBalkSearch").innerHTML=this.response;
}
window.onload=function(){
var i=document.querySelector('#form').childNodes[0];
i.addEventListener('keyup',ajax,false)
}
as u can see no need for extra id's, lots of code or passing each input field to a variable in this case every function can access everything without passing parameters... and so it's
easier to modify the code later...
html
<form id="form"><input type="search" name="zoekparameter" placeholder="Geef een zoekterm in."></form>
if you wanna add more fields like year or whatever you just have to add a input and a name
<input type="text" name="year">
you don't need to edit the javascript as FormData does everything for you.
if you don't understand something ask ...
if wanna check compatibility
use caniuse.com
http://caniuse.com/xhr2
http://caniuse.com/queryselector
bonus
shortest way
window.onload=function(){
var s=function(){
var a=new XMLHttpRequest;
a.open('POST','film.php');
a.onload=function(){console.log(this.response)};
a.send('zoekparameter='+i.value);
},
i=document.createElement('input');
i.type='search';
i.addEventListener('keyup',s,false);
document.body.appendChild(i);
}
I'm trying to use AJAX, HTML and PHP all together to provide a seamless experience to the user. I'm having trouble passing the variable to the PHP form right now. It's a little complicated the way I went about it, I'm not sure if there is an easier way as this is my first experiment with AJAX.
To explain in detail:
<div class="block" id="articles"></div>
I have this division which loads the details and loads the article. Inside of this division I'm trying to allow the user to add comments relating to the article.
function viewDets(str) {
if(str == "") {
document.getElementById("articles").innerHTML = "";
return;
}
if(window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("articles").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "viewDets.php?q=" + str, true);
xmlhttp.send();
}
Using this is passes the variable to viewDets which then adds another container:
while($row = mysql_fetch_array($result)) {
$count++;
$taskComments = $row['Annotation'];
$userName = $row['Username'];
$timeStamp = $row['Time'];
echo "Comments";
echo "<p class=\"meta\">$count. $taskComments ($userName) -- $timeStamp</p>";
}
echo "</div></div></div></div></div></div>
<form name=\"inputCom\" method=\"get\">
<div class=\"four column\">
<div class=\"column_content\" id=\"commentInsert\">
<label>Enter Comment</label>
<input type=\"text\" id=\"comment\"value=\"\"></input>
<input type=\"hidden\" id=\"Uname\" value=\"$user\"></input>
<input type=\"hidden\" id = \"taskID\" name=\"taskID\" value=\"$q\" />
<button type=\"button\" id = \"commentSub\" onClick=\"insertComm(comment, Uname, taskID)\" />Enter Comment</button>
</div>
</div>
</form>";
The name of this division is commentInsert and I've set up the AJAX so that on click, it should push the variables to a PHP function that inserts into my database for comments.
The issue that I'm running into is that I can't get the comment to pass to that PHP function.
function insertComm(str, uname, id) {
insertC();
if(str == "") {
document.getElementById("commentInsert").innerHTML = "";
return;
}
if(window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("commentInsert").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "subCom.php?q=" + str, true);
xmlhttp.send();
};
I have been playing around with this function by trying to call things like document.getElementByID and calling that function as insertC(); but with or without the insertC() function I am still having issue passing the 3 variables in the Javascript function to the PHP function, I tried it with just one variable and I still have trouble getting it to pass.
Any help would be greatly appreciated. Sorry for the long post.
I think your problem is onClick=\"insertComm(comment, Uname, taskID)\" assumes that these 3 variables are automatically set based on id. They are not.
Instead, you need to read them from the DOM, for example:
var str = document.getElementById("comment").value;
var uname = document.getElementById("Uname").value;
var id = document.getElementById("taskID").value;
If you add these to the start of insertComm, then you won't need to bother passing in the arguments.
If you want your PHP script to have access to all 3 of these, you'll need to pass in uname and id as well as str when sending your request to subCom.php. Note: it's best practice to encode these parameters using encodeURIComponent, in case the user inserts unexpected characters (like &) which may mess up your request.
... onClick=\"insertComm(comment, Uname, taskID)\" ...
When the button is clicked, comment, Uname and taskID are resolved by document because you're using inline code; although this really shouldn't be relied upon, it works like this:
comment = document.getElementById('comment');
// etc
As such, your function insertComm() is called with DOM elements instead of actual strings. To use them inside your function you would use comment.value for instance:
xmlhttp.open("GET", "subCom.php?q=" + encodeURIComponent(str.value), true);
Also note that I'm using encodeURIComponent() to prevent malformed URL's caused by spaces in the string value for example.
However, it would be considered better if you would pass the identifiers in the HTML like this:
... onClick=\"insertComm('comment', 'Uname', 'taskID')\" ...
And inside your insertComm():
var str = document.getElementById(comment).value;
xmlhttp.open("GET", "subCom.php?q=" + encodeURIComponent(str), true);
The HTML with the select value is:
<select id="value_select" onchange="get_value_js()">
<option>Value 1</option>
<option>Value 2</option
</select>
The JavaScript code:
function get_value_js() {
var the_value = document.getElementById("value_select").value;
}
I don't know how to continue the JavaScript to send the value to, for example, work.php. In work.php, I want to store the value in a PHP variable.
You can use AJAX.
function get_value_js(){
var xmlhttp;
var e = document.getElementById("value_select");
var the_value = e.options[e.selectedIndex].value;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//Do whatever with xmlhttp.responseText;
}
}
xmlhttp.open("GET","work.php?val="+the_value,true);
xmlhttp.send();
}
You can use $_GET['the_value'] to grab the value.
You need to enclose the <select> in a <form> tag like so:
<form id="myForm" method="post" action="work.php">
<select name="value_select">
<option value="1">Value 1 text</option>
<option value="2">Value 2 text</option
</select>
</form>
Please note that i've added value attributes to the <option> tags & added a name attribute to the <select>.
Next, you can submit the form in the following way:
function send()
{
document.getElementById( "myForm" ).submit();
}
Next in work.php:
<?
$value_select = $_POST[ "value_select" ];
echo( $value_select );
?>
You could either send it as an AJAX call if you want to stay on the same page or perform a redirect and pass the value as query string parameter:
window.location.href = '/work.php?value=' + encodeURIComponent(the_value);
Use ajax with jQuery
function get_value_js() {
var the_value =$("#value_select option:selected").val();
$.post('work.php?val='+the_value , function(data) {
//do whatever you want with the result
});
}
I have a page called getvalues.php, I need to call a function which is written in a different php page(fileclass.php) in a class from this page(getvalues.php), but the issue is i need to pass a variable also which is $i, and the value of $i passed should be 1 if we are selecting option B, and $i=2 if option=c, and $i=3 if option=D given in dropdown. I had simply wiritten an onchange event but had not written any code in javascript. Please help Thanks. Here is the code for getvalues.php
<html>
<select id="s" onchange="callsome();">
<option value='B' selected>B</option>
<option value='c'>c</option>
<option value='D'>D</option>
</select></html>
<?php include("fileclass.php")
$obj=new file;
echo $obj->func($i);?>
You could implement this using JQuery or Javascript (I use JQuery in the example because it is shorter and easier to make Ajax calls) :
<html>
<select id="s" onchange="callsome();">
<option value='1' selected="selected">B<option>
<option value='2'>C</option>
<option value='3'>D</option>
</select>
<script>
function callsome() {
var selected = $('select#s option:selected').val();
$.ajax({
type: "POST",
url: "fileclass.php",
data: ({selectedvalue : selected}),
success: function(data) {
alert(data);
}
});
}
</script>
</html>
After that the callsome returns the output of the fileclass.php script and you can use that however you like in your code. From your explanation it was not really clear what is happening in fileclass.php and what you want to do with it, so I hope it helps you.
If you want the function in Javascript only:
<script type="text/javascript">
function callsome() {
var e = document.getElementById("s");
var strVal = e.options[e.selectedIndex].value;
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var data = xmlhttp.responseText;
//use the data as you wish
}
}
xmlhttp.open("GET","fileclass.php?selectedvalue=strVal",true);
xmlhttp.send();
}
</script>
This isn't the way PHP and HTML work.
PHP is rendered on the server. HTML is rendered on the client, after the PHP is completely done. To do what you want to do, you need to have the HTML (possibly Javascript) make a request to the PHP page at fileclass.php.