I need to send two parameter to my javascript and get the parameters in the php file how I can do it ?
My html :
<form method="post" action="testButtonSup.php">
<p>
Veuillez choisir le service<br />
<input type="radio" name="service" value="ncli" id="ncli" checked ="checked" /> <label for="ncli">Ncli</label>
<input type="radio" name="service" value="fcli" id="fcli" /> <label for="fcli">Fcli</label>
</p>
<p>
<label for="client">Veuillez choisir le fournisseur :</label><br />
<select name="client" id="client" onchange="showUser(this.value, service)">
<?php
// echo '<option value=""/></option>';
while ($donnees = $reponse->fetch())
{
echo '<option value='.$donnees['refCustomer'].'>'.$donnees['legalCompanyName'].' </option>';
$idClient = $donnees['refCustomer'];
//$value = $donnees['refCustomer'];
}
$reponse->closeCursor();
?>
</select>
</p>
<p>.....
I want to send to the function showUser(this.value, service) two parameters
: the id of the select and the value of the radio button "service" whic is up
My function :
function showUser(str, service) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getTableBuffer.php?q="+str+"&service="service,true);
xmlhttp.send();
}
}
I tried like this but it doesn't work.
in my php file it didn't recognize the parameter.
It works with only the id of the select.
Without jQuery, a smallish function to get the value of a radio button from the collection to use in the ajax parameters.
function radiovalue(name){
var col=document.querySelectorAll('input[type="radio"]');
for( var n in col )if( n && col[n] && col[n].nodeType==1 && col[n].type=='radio' ){
if( col[n].hasAttribute('name') && col[n].getAttribute('name')==name ){
if( col[n].checked ) return col[n].value;
}
}
return false;
}
eg:
---
xmlhttp.open("GET","getTableBuffer.php?q="+str+"&service="+radiovalue('service'),true);
If you can use jQuery (which I recommend to handle ajax request) you can do it this way:
function showUser(str, service) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
$.ajax({
url: 'getTableBuffer.php',
type: 'GET',
data: {q:str, service:service}
}).done(function(response){
// Code to execute once the call has been executed
$('#txtHint').html(response.responseText);
});
}
}
Related
I wanna make ajax calls in symfony2. I already done with ajax with flat php and i have no idea how to set up in this symfony framework.
<html>
<head>
<script>
function showBook(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
function showAuthor(str){
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getAuthor.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<form action="">
Book name: <input type="text" id="txt1" onkeyup="showBook(this.value)">
<br><br>
Author name:<input type="text" id="txt1" onkeyup="showAuthor(this.value)">
</form>
<br>
<div id="txtHint"><b>book info will be listed here...</b></div>
</body>
</html>
Where should i pass this request?? to controller??
how to set routes??
is there any way to use flat php instead of controller??
You would pass the request to a controller action exposed using a route:
http://symfony.com/doc/current/book/routing.html
Then in your html code, if you are using twig and including javascript in a script tag, you can do
xmlhttp.open("GET","{{ path("route_name", {"parameter_name":"parameter_value"}) }}");
If you want to access the route in an attached .js file, you can use FOSJsRoutingBundle to generate the route url
If you are in a form, you can do something like :
$(document).submit(function () {
var url = $('form').attr('action');
var data = $('form').serialize();
$.post(url, data, function (data) {
window.location.href = data.redirect;
})
.fail(function () {
$('form').replaceWith(data.form);
});
});
You just need to send the correct url :
$(document).on('click', 'a', function () {
var url = window.location.href;
$.get(url, function (data) {
$('.container').replaceWith(data);
});
});
It is also possible to use a routing generate, simply add:
"friendsofsymfony/jsrouting-bundle": "dev-master" to your composer.json.
AppKernel.php :
new FOS\JsRoutingBundle\FOSJsRoutingBundle()
Then config it in your routing.yml :
fos_js_routing:
resource: "#FOSJsRoutingBundle/Resources/config/routing/routing.xml"
And finally use "expose" arg in your routing :
#Route("/{table}/index", name="beta.index", options={"expose"=true})
I use annotation routing
In your JS :
var url = Routing.generate('beta.index', { 'table': 'foo' });
Hope it'll help you :)
I am trying to display contents of a php file on my html page using ajax.
I have an html file with the following ajax code :
get_ajax.html
<form action="">
First name: <input type="text" id="txt1" onblur="show users(this.value)">
</form>
<p>Username: <span id="txtHint"></span></p>
<script>
function showHint(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = newXMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "user.php?u="+str, true);
xhttp.send();
}
</script>
user.php
<?php
echo $_GET["u"];?>
It doesn't display the username on my get_ajax.html page.
Is there something wrong with my code?
First check the existence of user.php and verify the proper path,by the way why don't use Jquery,it is easy and straight forward.
Here is an example using jquery :
var str = 'something';
$.get('user.php',{u:str},function(serverResponse){
$("#txtHint").html(serverResponse); //this should add the value something to the DOM
});
Appears you have type in your code as below
- onblur , you are making a call to "show users(this.value)"
- there is a space between "show" and "user" , even u correct the space , you dont have a function "showuser" anywhere.
- your function to make the ajax call is "showHint"
- next you need a space between "new" and "XMLHTTpRequest()"
<form action="">
First name: <input type="text" id="txt1" onblur="showHint(this.value)"/>
</form>
<p>Username: <span id="txtHint"></span></p>
</form>
<script>
function showHint(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "user.php?u="+str, true);
xhttp.send();
}
</script>
In the below JavaScript, I am unable to send radio button data to PHP. Example: if radio button "Mother" is selected, the selected value of "Mother" should be send through ajax. But my problem is that I am unable to send the selected radio button value from ajax. I Google'd it, but I am unable to solve it. Can you share the code for solving this problem.
This is the JavaScript code:
<script language="JavaScript">
var HttPRequest = false;
function doCallAjax() {
var test = $("#txtUsername").val();
var test2 = $("#txtPassword").val();
if(test=='')
{
alert("Please Enter Register Number");
}
else if(test2=='')
{
alert("Please Enter Date Of Birth");
}
else
{
HttPRequest = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
HttPRequest = new XMLHttpRequest();
if (HttPRequest.overrideMimeType) {
HttPRequest.overrideMimeType('text/html');
}
} else if (window.ActiveXObject) { // IE
try {
HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!HttPRequest) {
alert('Cannot create XMLHTTP instance');
return false;
}
**// iam using this For Validation to send data to different urls based on selection**
var game1 = $('input[type="radio"]:checked').val();
if (game1 === "Mother") {
var url = 'http://localhost:9999/check.php';
}
else if (game1 === "Father") {
alert('Father');
}
else {
HttPRequest = false;
alert('select 1');
}
**this is Where ima stucked**
var pmeters = "tUsername=" + encodeURI( document.getElementById("txtUsername").value) +
"&tPassword=" + encodeURI( document.getElementById("txtPassword").value );
"&game=" + $('input[type="radio"]:checked').val();
HttPRequest.open('POST',url,true);
HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
HttPRequest.setRequestHeader("Content-length", pmeters.length);
HttPRequest.setRequestHeader("Connection", "close");
HttPRequest.send(pmeters);
HttPRequest.onreadystatechange = function()
{
if(HttPRequest.readyState == 3) // Loading Request
{
document.getElementById("mySpan").innerHTML = "Now is Loading...";
}
if(HttPRequest.readyState == 4) // Return Request
{
if(HttPRequest.responseText == 'Y')
{
window.location = 'success.html';
}
else if (HttPRequest.responseText == 'z')
{
document.getElementById("mySpan").innerHTML = "";
window.alert("bad registernumber or dob");
}
else if (HttPRequest.responseText == 'b')
{
document.getElementById("mySpan").innerHTML = "";
window.alert("userexist");
}
}
}
}
}
</script>
This is html code
<br/>
<input type="radio" name="game" value="Mother">Mother
<br />
<input type="radio" name="game" value="Father">Father
<br />
<input type="radio" name="game" value="Self">Self
<br />
<input type="radio" name="game" value="Other">Other
<br />
</table>
<br>
<input name="btnLogin" type="button" id="btnLogin" OnClick="JavaScript:doCallAjax();" value="Login">
First I would suggest you to use jQuery, because it is really simplier and better.
Then you can use the following code to post the checkbox/radio value:
$("#game").val()
Here you can find the really simple syntax for Ajax with jQuery.
Please remove $('input[type="radio"]:checked').val() and replace with a var game. Before that please use below code to get value of checked radio button in var game.
var elements = document.getElementsByName("game");
var game;
for(var i = 0; i < elements.length; i++ ){
if(elements[i].checked){
game = elements[i].value;
}
}
So now your code will look like
var pmeters = "tUsername=" + encodeURI( document.getElementById("txtUsername").value) +
"&tPassword=" + encodeURI( document.getElementById("txtPassword").value );
"&game=" + game;
I have a HTML form with two dropdown menus. First dropdown is prepopulated from database with PHP, second one is linked with first one and uses AJAX to update values according to the selection from first one.
How can I make the URL to change after selecting something from the dropdown menu? E.g. after selecting something from first dropdown, URL would be something like http://myurl.com/form.php/option1 and after second choice http://myurl.com/form.php/option1+option2.
My code:
Scripts:
<script>
function kuvaRingkond(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
}
else {
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("txtHint").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","getringkond.php?q="+str,true);
xmlhttp.send();
}
}
</script>
function AjaxFunction()
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Teie brauser ei toeta Ajaxit!");
return false;
}
}
}
function stateck()
{
if(httpxml.readyState==4)
{
var myarray = JSON.parse(httpxml.responseText);
// Remove the options from 2nd dropdown list
for(j=document.form.kandidaat.options.length-1;j>=0;j--)
{
document.form.kandidaat.remove(j);
}
var optn = document.createElement("OPTION");
optn.text = 'Vali kandidaat';
optn.value = '0';
document.form.kandidaat.options.add(optn);
for (i=0;i<myarray.data.length;i++)
{
var optn = document.createElement("OPTION");
optn.text = myarray.data[i].Eesnimi + ' ' + myarray.data[i].Perekonnanimi;
optn.value = myarray.data[i].KandidaadiID;
document.form .kandidaat.options.add(optn);
}
}
}
// end of function stateck
var url="dd.php";
var erakond_id=document.getElementById('s1').value;
url=url+"?erakond_id="+erakond_id;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
//alert(url);
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
Form:
<form role="form" name="form" method="POST" action="haaletamine_form.php">
<div class="form-group">
<label for="erakond">
Erakond:
</label>
<?php
require "connection_pdo.php";// connection to database
echo "<select class ='form-control' name=erakond id='s1' onchange=AjaxFunction();>";
echo "<option selecter='selected'>Vali erakond</option>";
$sql="select * from erakonnad "; // Query to collect data from table
foreach ($dbo->
query($sql) as $row) {
echo "<option value=$row[ErakonnaID]>$row[ErakonnaNimi]</option>";
}
echo "</select>";
?>
</div>
<div class="form-group">
<label for="kandidaat">
Kandidaat:
</label>
<select class="form-control" name=kandidaat id='s2' onchange="kuvaRingkond(this.value)">
<option selecter="selected">
Vali kandidaat
</option>
</select>
</div>
<div id="txtHint">
<b>
</b>
</div>
<button type="submit" class="btn btn-default">
Kinnita valik
</button>
</form>
Thanks!
This is how I would do it.
HTML
<select id="select-list">
<option>Option One</option>
<option>Option Two</option>
<option>Option Three</option>
</select>
jQuery
$(document).ready(function() {
$('#select-list').on('change', function() {
var nSelectOption = $('#select-list').find(':selected').text();
switch(nSelectOption) {
case "Option One":
window.location.href = 'http://google.com';
break;
case "Option Two":
window.location.href = 'http://google.com';
break;
case "Option Three":
window.location.href = 'http://google.com';
break;
}
});
});
i have an input text , and i want when i click in a button it takes that value and pass it in a parameter in a url , this is my code so far :
<div id="landmark-1" data-landmark-id="1">
<form name ="data">
<label>enter your name :</label>
<input type= "text" placeholder="ID" name="ID" value="" style="width:206px;" />
<input type="submit" value="Suivant" onclick="showUser(this.form)" >
</form>
</div>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
and this is my javascript code :
<script>
function showUser(frm)
{
var str = frm.ID.value;
if (str==""){
document.getElementById("txtHint").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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://localhost/filename/page.php?q="+str,true);
xmlhttp.send();
}
</script>
but when i enter a name, it just add : ?ID=name in the url of the current page ! it doesn't send the parameter in the url i want ..
Change your code from: onclick="showUser(this.form)" to onclick="return showUser(this.form)"
and
if (str==""){
document.getElementById("txtHint").innerHTML="";
return;
}
to
if (str==""){
document.getElementById("txtHint").innerHTML="";
return false;
}
Your form is being submitted even if there is no ID entered. The return false prevents the form submission.
Here is a revised AJAX call. It is a bit more complicated than the w3schools example but it is more functional and complete. First the AJAX routine:
function AJAX( url, processFunction ) {
var XHR;
try{
// Opera 8.0+, Firefox, Safari/Chrome
XHR = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
XHR = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
XHR = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser doesn't support AJAX!");
return false;
}
}
}
if( XHR.onreadystatechange ) {
if( XHR.readyState == 4 ) {
if( XHR.status == 200 ) {
//--- we've got the data so process it
processFunction( XHR.responseText );
}
if( XHR.status != "OK" ) {
alert( 'Error : '+XHR.responseText);
}
}
}
//--- open
XHR.open( 'GET', url ); // --- url is from the function call
//--- send
XHR.send();
}
Now the function that will handle the returned data. In this case you simply want to display the text:
function processMyData( data ) {
document.getElementById("txtHint").innerHTML= data;
}
Now for the modified showUser function
function showUser(frm) {
var str = frm.ID.value;
if (str==""){
document.getElementById("txtHint").innerHTML="";
return false;
} else {
AJAX( "http://localhost/filename/page.php?q="+str, 'processMyData' )
}
}
If there is an error in you php file it should show up in the alert box.
If your code still isn't returning anything and there is no error the only other thing that I can think of is that you are not echo/print-ing your data for the AJAX routine to retrieve your text.