php javascript code to call php function from javascript - javascript

Below is my textbox code
<input id="society_name" onBlur="showsociety(this.value)" />
<input id="societyid" name="society" />
Below is my javascript which call addressdata.php page...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js" type="text/javascript"></script>
<script>
function showsociety(str)
{
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest();}
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var data = JSON.parse(xmlhttp.responseText);
for(var i=0;i<data.length;i++)
{
document.getElementById("societyid").value = data[i].societyid;
}
}
}
xmlhttp.open("GET","addressdata.php?q="+str,true);
xmlhttp.send();
}
</script>
Addressdata.php page
<?php
require_once('includes/config.php');
$q = $_GET['q'];
$city = $database->getRows("SELECT SM.id AS societyid,SM.society from societymaster SM WHERE SM.society = :society", array(':society'=>"$q"));
$info = array();
foreach($city as $row)
{
$cID = $row['societyid'];
$info[] = array('societyid' => $cID);
}
echo json_encode($info);
?>
I need to fetch id in multiple textbox like above given ex...in my form.
So is this possible to convert all php code to function in addressdata.php and call this function only from javascript...
FOR EX - i need to make whole php code of addressdata.php file as it is in function and call tis with below javascript on textbox blur event..

If I understood you correctly you want to add more text input elements into your page and be able to use this whole process of showing society on each of this elements.
The problem is not converting php code into a function (which would bring nothing).
What you want is to be able to tell showsociety() function which input element should it work on.
In the easiest case you can add additional parameter to the fucntion:
showsociety(str, id) {...}
And use this ID to search for correct element on the page.
[...]
document.getElementById(id).value = data[i].societyid;
[...]
.
<input id="society_name" onBlur="showsociety(this.value, this.id)" />
It can be done better but I think with such simple solution you should not have much problems.
Hope it helped.

Related

Retrieve multiple values using ajax and php, without Jquery

Website coding surely is awesome and I recently rialized that JavaScript and Ajax are really essential elements in order to build a outstanting website. I've done the research on internet, but the results weren't that useful. Every code included Jquery, which I don't comprehend. Also JSON is slightly unclear regarding the objects, etc.
W3schools published a few examples on how to generate an Ajax code that reacts with a PHP file. This data is retrieved through 'resonseText'. However this element only retrieves one unselected PHP string.
Is there a method to select specific variables or values from the PHP file and accordingly send it back to the Javascript (Ajax) file, so I can subsequently utilize them for further Javascript coding.
Thank you in advance. (It would greatly help, since Ajax is such a complex form of JavaScript.)
My Ajax code, to send data to the PHP file
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 (this.readyState == 4 && this.status == 200) {
var XMLResponse = this.responseText ;
document.getElementById("nameInputNote").innerHTML = "Status: " + XMLResponse ;
}
} ;
xmlhttp.open("GET","ajaxIndex.php?rq1="+valueNameInput,true) ;
xmlhttp.send() ;
The PHP code:
<?php
$rq1 = $_GET['rq1'] ;
if (empty($rq1) ) {
} else {
$sql1 = "SELECT userName FROM users WHERE userName = '{$rq1}' " ;
if ($result1 = mysqli_query($connection, $sql1) ) {
$resultsSql1 = mysqli_num_rows($result1) ;
if ($resultsSql1 == 0) {
echo "vacant" ; //select this value with JS
$permission = "true" ; //and select this value separately with JS
} else {
echo "occupied" ; // or in this senario: select this value
$permission = "false" ; // and this value
// In this case the $permission variable is needed to determine whether a form should be submitted or not.
}
}
}
Try with
let src = <?php echo json_encode($yourVar); ?>;
And then use that variable. Other ways you can do that is to use axios, cookie or VueJS and pass data into component. Hope that helps.

xmlhttp.open does not seem to do anything in MVC structure

I'm trying to add an auto-complete function to a text field.
This used to work, but then I switched to an MVC structure and now I can't get it back to work.
PHP/HTML:
echo '<br><br>Add member:<br>'
. '<form method="post"><input type="text" name="username" oninput="findUsers(this.value)" list="livesearch">'
. '<datalist id="livesearch"></datalist>'
. '<input type="submit" value="Add">'
. '</form>';
JavaScript:
<script>
function findUsers(str) {
if (str == "") {
document.getElementById("livesearch").innerHTML = "no suggestions";
xmlhttp.send();
} 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("livesearch").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","/user/search/?q="+str,true);
xmlhttp.send();
}
}
</script>
/user/search opens a function called search in the class User in the UserController.php file
class UserController extends Controller
{
public function search()
{
$response = "hello";
echo $response;
}
}
So this should put the "hello" message in the livesearch datalist.
But for some reason just nothing is happening.
If I replace the xmlhttp.open by window.open, the page does load normally and shows the hello message. But that is obviously not what I want.
Figured out the exact problem:
My xmlhttp.responseText is also returning the header of my website, which is already loaded in the MVC structure.
How would I work around this?
Is it an option to just edit the string and get the last part in javascript?
Or are there better solutions?
Used JavaScript to grab the last part of the string (so without the header)
It does what it's supposed to do now, but feels like a pretty "dirty" solution.
Also had to add the <option value=""> tag, which was in my code, but not in my testcode.

ajax query on secondary page

Background
I've read through several posts and tutorials here on AJAX, and I've gotten it to work great - on one page, but I'm still new to utilizing AJAX so I hit a rough spot that I can't understand how to fix.
I have my main page, ajaxtest.php which contains a drop-down with this code:
<a>
<?php
include('./db.php');
$PM = mysqli_query($con, "SELECT DISTINCT PMName FROM report WHERE PMname <> '' ORDER BY PMName ASC");
?>
<select name="PMName" onchange="showUser(this.value)">
<?php
while ($row = mysqli_fetch_row($PM)) {
$selected = array_key_exists('PMName', $_POST) && $_POST['PMName'] == $row[0] ? ' selected' : '';
printf(" <option value='%s' %s>%s</option>\n", $row[0], $selected, $row[0]);
}
?></select></a>
which pulls this function:
<script>
function showUser(str) {
if (str !==".PM") {
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","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
Sending the selection from the database off to my second page, getuser.php.
The user then sees the rest of the initial page populated with the results of getuser.php, which contains the bulk of my code and the HTML tables populated with the SQL info.
This is working fine.
Issue
My issue stems from the fact that once (and pardon my lack of technical jargon,) getuser.php is populated into the <div> that is inside of ajaxtest.php, I can't utilize any other JavaScript or AJAX functions or the entire page just refreshes as if I were to reload ajaxtest.php again from scratch and it puts me back to the initial blank screen with the dropdown menu.
On getuser.php, within the <form> that surrounds the entire table, there is a submit button:
<form action="" method="POST" onsubmit="test()">
and
<input class="button" name="update"<?= $LineID ?>" type="submit" id="update" value="UPDATE">
and this is supposed to link to my JavaScript test() function that simply reads:
function test() {
alert("yo");
}
but when I click the button, the entire page refreshes instead of executing this function. Why is this?
If I manually go to localhost/getuser.php?q=John%20Doe instead of "having this page load inside of my ajaxtest.php <div>" and click the button, it works just fine and I get the JavaScript alert to pop up. What am I doing wrong here?
Try editing the function test() to return false
function test() {alert("yo"); return false}
and change the line
<form action="" method="POST" onsubmit="test()">
into
<form action="" method="POST" onsubmit="return test()">
Now it shouldn't refresh the page. Function used in onsubmit needs to return true or false.

AJAX - PHP - Content Not Loading

I am new in AJAX.
I am trying to load some content from my PHP file into the load.html. i made the function on the onKeyUp Event of a textbox.
But its always showing "UNDEFINED" as the output . :(
Please help me
The load.html file
<!DOCTYPE html>
<html>
<head>
<script>
function NickName(nick){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status==200 && xmlhttp.readyState ==4){
document.getElementById("divNick").innerHTML = xmlhttp.reponseText;
}
}
xmlhttp.open("GET","myphp.php?key="+nick,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="divNick"></div>
<input type="text" id="text_box" onKeyUp="NickName(this.value)">
</body>
</html>
And the myphp.php file
<?php
if(isset($_GET['key']))
{
$key = $_GET['key'];
$choice1 = "Shifar";
$choice2 = "Nidal";
if($key==$choice1)
{
echo "Shifz";
}
else if($key==$choice2)
{
echo "Steavz";
}
else
{
echo "No Match Found";
}
}
?>
Thanks in Advance.
Shifar Shifz
its because you dint specify the correct function name.
You defined a function named NickName and called another named NicKName
updated to comments
its coming as undefined because of another typo u made xmlhttp.reponseText instead of xmlhttp.responseText
There is typo. your function name is NickName you are calling NicKName. K is capital
Change document.getElementById("divNick").innerHTML = xmlhttp.reponseText;
to document.getElementById("divNick").innerHTML = xmlhttp.responseText;
again a typo. reponseText --> responseText
Try like this :
xmlhttp.open("GET","myphp.php?key="+nick,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.status==200 && xmlhttp.readyState ==4)
{
document.getElementById("divNick").innerHTML = xmlhttp.reponseText;
}
}
I think the order is important and NickName is not NicKName
I can see there is a typo error in your function name. When you call the function you have used NicKName but the function is actually defined as NickName. the (k) is capitalized in your calling statement.
Other advice for you, write Ajax like you have done is a very old approach. And most importantly you will have a great deal of coding for many browsers...you are supposed to deal with all the browsers out there. So why don't you use other ajax approach. I advice you to use jQuery $.ajax. Its very simple and handles all the cross-browser compatibility issues.
For eg. the above line of code could be replaced with....
$('#divNick').load('myphp.php?key='+nick);
Just one line. the other is you can also use the $.ajax which can let you do both POST and GET requests as you wish.
Most important you have said you are new to Ajax. If so why don't you already start reading about jQuery...besides its very rewarding in both by saving you time and when you are done, you will see how many job position require jquery as a skill set.
Hope this will help.
Spelling mistake on your ajax code
Instead of - document.getElementById("divNick").innerHTML = xmlhttp.responseText;
You typed - document.getElementById("divNick").innerHTML = xmlhttp.reponseText;

Acess php variable in javascript and vise versa

Suppose I have php page index.php
<?php
$x=$_POST[sent] // I get some value in #x
?>
<html>
<head>
<script>
function getVar()
{
var x= <How to fetch $x from php code>
alert(x);
}
</script>
</head>
<body>
<button type="submit"> click </buttton>
</body>
</html>
How can I fetch $x in getVar(_) function?
Or another case some variable is in JS then getting it into php code?
Is it possible or not?
Actually I have index.php and through ajax request loading new page url.php. I want to send few variables to url.php and want to access them in JS code in it.
Here is my ajax request:
var id=mydata.id; // Guess I am getting some data here
$.ajax({
url:'url.php'
,async: true
,cache: false
,dataType: 'html'
,success: function(data){
$('body').html(data);
FB.XFBML.parse();
}
I want to send id in ajax request to url.php. I will fetch it as $x and want to use it in JS code.
php to javascript can be done by using
<?php $x = "iam a php variable"; ?>
<script>
function getVar()
{
var x= "<?= $x; ?>";
alert(x); //alerts **iam a php variable**(value of $x from php)
}
</script>
The vise versa can be done via Ajax. Here is the simple example
<script>
function showUser()
{
var str= "iam a javascript variable";
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(xmlhttp.responseText); //alerts response from php
}
}
xmlhttp.open("GET","new.php?q="+str,true); //you can send request through post or get methods
xmlhttp.send();
}
</script>
Here, i am getting a javascript variable in php through ajax using GET.
In new.php, i am just printing out the request received via GET
<?php
print $_GET["q"]; //prints **iam a javascript variable**(value of str from javascript)
?>
Communication between PHP and Javascript is a classic example of client-server communication. In this case, PHP is your server application and Javascript is your client application. There are many protocols established for this communication, but you should take a look at AJAX and RESTful services.
In order to understand what is going on, i suggest that you read this tutorial on HTTP and REST, from a PHP programmer point of view. When designing a client-server application, PHP would "generate" all the content, by applying business logic and communicating with the database, and Javascript would ask PHP for this content on certain events (click, show table, etc). PHP, instead of outputting HTML, would output XML or JSON, so you can parse and show that data in Javascript.
Transfer boths ways:
function getVar($var)
{
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
$phpVar = xmlhttp.responseText;
return $phpVar;
}
}
xmlhttp.open("POST","/yourPage.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("var=" + $var);
}
And then on yourpage.php:
<?
if (isset($_POST["var"])) {
die($_POST["var"]);
}
?>
If you're simply trying to get pass the value of $x variable to JavaScript, then it can be done as follows:
function getVar()
{
var x= "<?php echo htmlspecialchars($x); ?>";
alert(x);
}
Here's a working example:
<?php
$x = $_POST['sent'] // I get some value in #x
?>
<html>
<head>
<script>
function getVar()
{
var x= "<?php echo htmlspecialchars($x); ?>";
alert(x);
}
</script>
</head>
<body>
<button type="submit" onclick="getVar()"> click </buttton>
</body>
</html>
If the $x variable is received by the script correctly, then it will be alertd when you click the button.

Categories

Resources