pass an input text into parameter - javascript

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.

Related

Ajax calls in symfony framework

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 :)

Cannot click on the content which is loaded through ajax function

Currently, I cannot load the second content using ajax. Actually, I have loaded the first content using ajax. In order to go to the second content, i need to call the ajax function but after i click to load the second content using ajax it does not work. I have checked my code, its working fine if i directly call the second ajax function, unless i call the first ajax function after that the ajax is not working again. Are there any ways to solve this problem.
This is the first ajax code:
function showMusic(str) {
if (str == "") {
document.getElementById("albums").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("albums").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getAlbums.php?q="+str,true);
xmlhttp.send();
}
}
The above function works. The above function is at another php file
This is the second ajax code:
$(document).ready(function(){
function showArtistDetails(str) {
if (str == "") {
alert("hi");
document.getElementById("artist").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
alert("hi1");
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
alert("hi2");
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("artist").innerHTML = xmlhttp.responseText;
alert("hi3");
}
};
xmlhttp.open("GET","getArtist.php?title="+str,true);
alert("hi4");
xmlhttp.send();
alert("hi5");
}
}
$("#clickme").click(showArtistDetails);
});
This is the php code which is at another php file:
echo "<td id=\"clickme\">" . $row['CDTitle'] . "</td>";
I have been trying to solve this for the past 2 days but i am unable to solve it. Some are saying its a bug. But i really i dont know what causes this problem. Thanks in advance.

how to compare ajax response text with some string without jQuery

I am trying to get a value back through if it found value in database sends/echo result value in it does found sends back/echo 'not_found'.
When I try to compare in the following script it always goes inside if, and never goes to else.
I also tried NULL, FALSE instead not_found does not work.
function showHint(str) {
var xmlhttp;
var url= "check_album.php?q="+str;
document.getElementById("txtHint1").innerHTML=(url);
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) {
if(xmlhttp.readyState.responseText !='not_found') {
document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
} else {
document.getElementById("txtHint3").innerHTML='no result';}
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
}
and this is check_album.php code which sending result back
require_once('../php/classes/class.add_album.php');
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$album_name = $_GET["q"];
//make new object
$objfile = new add_album();
//call object method with post method value we got and save result in result
$file_found=$objfile->find_album($album_name);
if ($file_found)echo $file_found;
else echo 'not_found';
}
Try this.
if(xmlhttp.responseText !='not_found' ){
document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
} else
{
document.getElementById("txtHint3").innerHTML='no result';
}
This is because response text may have unwanted spaces Try to trim that response
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g,"");
};
if(xmlhttp.responseText.trim() !='not_found' ){
document.getElementById("txtHint2").innerHTML=xmlhttp.responseText;
}else{
document.getElementById("txtHint3").innerHTML='no result';
}

Getting value from ajax calling using xmlhttp request

I am making a request using post method. I am not able to find the value of response text. May be i lack the knowledge on how to get the response text. If a data exist in a database i am trying to tell the user that he is able to post the data otherwise he will get an alert that he need to change the name.
Here is my ajax call:-
function checkAddedNew(univ_name,term_no,dept_name,uid,year)
{
var getName=document.getElementById("add_new_name").value;
var getTitle=document.getElementById("add_new_title").value;
var hasSpace=getTitle.indexOf(' ');
if(hasSpace >= 0)
{
alert("Please fill up the title without space");
}
else
{
if(getName&& getTitle)
{
var r=confirm("Do you want to add?");
}
else if(!getName && getTitle)
{
alert("Please fill up the name");
}
else if(getName && !getTitle)
{
alert("Please fill up the title");
}
else
{
alert("Please fill up the form.");
}
if (r==true )
{
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)
{
alert(http.responseText);
location.reload();
}
}
xmlhttp.open("POST","../addnew/check",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("title="+getTitle+"&name="+getCourseName+"&name="+univ_name+"&term_no="+term_no+"&department_name="+dept_name+"&uid="+uid+"&year="+year);
}
}
}
and i am here getting the response xmlhttp.readyState==4 && xmlhttp.status==200 .And here is my controller :-
function check()
{
$title = $this->input->post('title');
$name=$this->input->post('name');
$university_name=$this->input->post('university_name');
$term_no=$this->input->post('term_no');
$department_name=$this->input->post('department_name');
$uid = $this->input->post('uid');
$year=$this->input->post('year');
$CI =& get_instance();
$log_username=$CI->session->userdata('username');
$now = time();
$human = unix_to_human($now);
$this->load->model('model');
$isUnique=$this->model->checkNew($name,$title,$log_username,$human,$term_no,$university_name,$year,$department_name,$uid);
if($isUnique)
{
$this->course_model->insertNewCourse($course_name,$course_title,$log_username,$human,$term_no,$university_name,$year,$department_name,$uid);
}
}
The variable http is not defined, it should be xmlhttp
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert(xmlhttp.responseText);
//or
//alert(this.responseText);
location.reload();
}
}
You have alert(http.responseText); but you never define http. Your object is called xmlhttp.

Javascript does not return servlet response

I have wriiten welcome screen which basically use below javascript to call creditCheck servlet. Within servlet, there is method which will check the username and password. Servlet returns value properly. alert is not getting generated after servlet excutation within javascript.
however if execute simple servlet ( not doing anything, just printing variables), it will generate alert.
below is my javascript within JSp file:
############################################
<script type="text/javascript">
function getXmlHttpRequestObject(){
var xmlHttp = false;
if (window.XMLHttpRequest){
return new XMLHttpRequest(); //To support the browsers IE7+, Firefox, Chrome, Opera, Safari
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP"); // For the browsers IE6, IE5
}
else {
alert("Error due to old verion of browser upgrade your browser");
}
}
var xmlhttp = new getXmlHttpRequestObject(); //xmlhttp holds the ajax object
function servletPost() {
if(xmlhttp) {
var username = document.getElementById("uname");
var password = document.getElementById("pass");
xmlhttp.open("POST","CredCheck",true);
xmlhttp.onreadystatechange = handleServletPost;
req.onreadystatechange = callback;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("uname=" + username.value + "&pass=" + password.value );
}
}
function handleServletPost() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
else {
alert("Ajax calling error");
}
}
}
</script>
#
I have changed xmlhttp.open("POST","CredCheck",true); to
xmlhttp.open("POST","CredCheck",false);
xmlhttp.onreadystatechange = handleServletPost;

Categories

Resources