Retrieve multiple values using ajax and php, without Jquery - javascript

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.

Related

Update a php variable with AJAX Javascript

I have 2 php files, the first is BAConsult.php which is the main file, and the other is BAConsultRecordsAJAX.php. This line of code is in BAConsultRecordsAJAX.php:
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
}
In BAConsult.php I have this:
echo $skincareinuse;
Is it possible to bring over the $skincareinuse value from the BAConsultRecordsAJAX.php page, to the $skincareinuse variable on the BAConsult.php page?
Such that, lets say whenever I do a click on the table row, the value of $skincareinuse will be updated and shown by the echo, without the page refreshing?
[EDITED TO SHOW MORE OF MY CODES]
This is BAConsult.php file, where my main code is.
<?php echo $jsonvariable; ?>//Lets say i want to store the JSON data into this variable
function showconsultationdata(str) { //face e.g and checkboxes for that date selected.
if (str == "") {
document.getElementById("txtHint2").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("txtHint2").innerHTML = xmlhttp.responseText;
var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
$("textarea#skinconditionremarks").val(a.skinconditionremarks);
$("textarea#skincareremarks").val(a.skincareremarks);
var test = a.skincareinuse;
//I want to store this ^^ into the php variable of this page.
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
This is my BAConsultRecordsAJAX.php page.
$q = $_GET['q']; //get dateconsulted value
$consult="SELECT * FROM Counsel where nric='$_SESSION[nric]' and dateconsulted='$q'";
$consultresult = mysqli_query($dbconn,$consult);
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse=explode(",",$row['skincarecurrentlyinuse']);
$skincondition=explode(",",$row['skincondition']);
$queryResult[] = $row['skincareremarks'];
$queryResult[] = $row['skinconditionremarks'];
}
$skincareremarks = $queryResult[0];
$skinconditionremarks = $queryResult[1];
echo "<div id='arrayoutput'>";
echo json_encode(array('skincareremarks'=>$skincareremarks
'skinconditionremarks'=>$skinconditionremarks
'skincareinuse'=>$skincareinuse,
'skincondition'=>$skincondition));
echo "</div>";
You don't actually want to transfer the variable from BAConsultRecordsAJAX.php to BAConsult.php, but to BAConsult.js (I suppose that's the name of your JS file).
In reality, even that's what you wanted to do, it's impossible, because your main PHP is processed before the page even loads. What you can do, however, is overwrite the rendered value with a new one with the use of JavaScript.
To do that, send an AJAX request to BAConsultRecordsAJAX.php requesting the variable's value as shown below:
In JavaScript:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// Check if the AJAX request was successful
if (xhttp.readyState === 4 && xhttp.status === 200) {
var td = document.getElementById("your table td value's id");
var td.innerHTML = xhttp.responseText; // gets the value echoed in the PHP file
}
xhttp.open("POST", "BAConsultRecordsAJAX.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(""); // You don't need to send anything to the PHP file
In PHP:
<?php
echo $skincareinuse;
?>
[EDIT]:
If you are using inline JavaScript use the following code:
<script type = "application/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// Check if the AJAX request was successful
if (xhttp.readyState === 4 && xhttp.status === 200) {
var td = document.getElementById("your table td value's id");
td.innerHTML = xhttp.responseText; // gets the value echoed in the PHP file
}
xhttp.open("POST", "BAConsultRecordsAJAX.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(""); // You don't need to send anything to the PHP file
</script>
[EDIT 2]:
To pass a JSON object to PHP file via an AJAX request you have to make it a string. That requires the following code:
var JSONstring = JSON.stringify(yourJSONobject);
Then you can pass it in your PHP file with the AJAX request by putting it inside send() as shown:
xhttp.send("json_object=" + JSONstring);
Then in PHP, in order to use it, you have to decode it:
<?php
$json_object = json_decode($_POST["json_object"]);
// Now it's ready to use
?>
[About the code]:
Notes about the first file:
First of all, you have put your plain JavaScript code inside a PHP file and therefore it will not work. You have to wrap it in <script type = "application/javascript></script>
I don't have a clue what you are trying to do here:
Code:
var a = JSON.parse($(xmlhttp.responseText).filter('#arrayoutput').html());
It seems like you are trying to filter out and parse the innerHTML of #arrayoutput.
If the response is a JSON string, not HTML, so you absolutely can't do that. The logic of this above line is flawed.
How I would write your code:
function showconsultationdata(str) {
var xmlhttp;
if (!str) {
$("#txtHint2").empty();
} else {
xmlhttp = new XMLHttpRequest();
// Providing support for a 15-year-old browser in 2016 is unnecessary
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$("#txtHint2").html(xmlhttp.responseText);
var a = JSON.parse(xmlhttp.responseText);
$("textarea#skinconditionremarks").val(a.skinconditionremarks);
$("textarea#skincareremarks").val(a.skincareremarks);
var test = a.skincareinuse; // The variable you want
// Its saved in "text" and can use something like:
// $("#element").html(test); to have it replace your current text
}
};
xmlhttp.open("GET","BAConsultRecordsAJAX.php?q="+str,true);
xmlhttp.send();
}
}
Notes about the second file:
I don't know if the query works for you, but it probably shouldn't, because:
$_SESSION is an associative array and you pass nric, whereas it should be "nric".
As $_SESSION is an array, the proper method to insert its value to your query is: {$_SESSION["nric"]}.
To ensure that you don't become the victim of an SQL Injection, use parameterised queries or at least sanitise somehow the received data, because GET is relatively easy to hack. Check the improved code later on how to do it.
How I would write your code:
$q = $_GET['q']; //get dateconsulted value
$dbconn = mysqli_connect("localhost", "root", "") or die("Error!");
mysqli_select_db($dbconn, "database") or die("Error!");
$consult = "SELECT * FROM Counsel where nric='{$_SESSION["nric"]}' and dateconsulted = ?";
if ($stmt = mysqli_prepare($dbconn, $consult)) { // By using a prepared statement
mysqli_stmt_bind_param($stmt, "s", $q); // you eliminate the chances to have
if (mysqli_stmt_execute($stmt)) { // an SQL Injection break your database
$consultresult = mysqli_stmt_get_result($stmt);
if (mysqli_num_rows($consultresult) > 0) {
while ($row = mysqli_fetch_array($consultresult)) {
$skincareinuse = explode(",",$row['skincarecurrentlyinuse']);
$skincondition = explode(",",$row['skincondition']);
$queryResult[] = $row['skincareremarks'];
$queryResult[] = $row['skinconditionremarks'];
}
$skincareremarks = $queryResult[0];
$skinconditionremarks = $queryResult[1];
$array = array('skincareremarks'=>$skincareremarks
'skinconditionremarks'=>$skinconditionremarks
'skincareinuse'=>$skincareinuse,
'skincondition'=>$skincondition);
echo "<div id='arrayoutput'>";
echo json_encode($array);
echo "</div>";
mysqli_stmt_close($stmt);
mysqli_close($dbconn);
exit;
}
}
}
Obviously you may change the values to suit your requirements, you must have jquery installed, the time value could be anything you want
$.ajaxSetup({ cache: false });
setInterval(function() {
var url = "pagethatrequiresrefreshing.php";
$('#divtorefresh').load(url);
}, 4000);
Using include will most likely work. From the docs:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward.
BAConsultRecordsAJAX.php
while($row = mysqli_fetch_array($consultresult)) {
$skincareinuse[] = explode(",",$row['skincarecurrentlyinuse']);
}
include "BAConsult.php";

How do I use AJAX to communicate with and run code on a server?

I've been learning to use AJAX with the GET request that allows me to access a PHP script with an array of data on a server. I want to be able to send a request that tells the server to run code that will open an application and manipulate some info on this application.
Here is the code I use to firstly communicate with the server, then send a request to the server and finally handle responses from the server.
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
xmlHttp = false;
}
}
if(!xmlHttp)
{
alert("cant create that object hoss");
}
else
{
return xmlHttp;
}
}
function process(){
if(xmlHttp.readyState == 0 || xmlHttp.readyState == 4) //State were object is free and ready to communicate with server
{
food = 'bacon';
xmlHttp.open("GET", "ExecuteMaya.php?food="+food,true); //Creates request that we are sending to server
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process()', 1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200) //Means communication was successful
{
var xmlResponse = xmlHttp.responseText;
var xmldom = (new DOMParser()).parseFromString(xmlResponse, 'text/xml');
var text = xmldom.getElementsByTagName("response")[0];
var message = text.childNodes[0].nodeValue;
foodTextOutput = message;
setTimeout('process()', 1000);
}
else
{
alert('Something went wrong!');
}
}
}
Here is the PHP I was using while I was learning how to use AJAX. I got the following error when I printed the 'xmldom' variable from the above code to the console and inspected it - "error on line 2 at column 1: Extra content at the end of the document". This may be a different question to my original post, but I thought I'd bring up that this error occurred. This then had a knock on effect for the line 'var message = text.childNodes[0].nodeValue;' which produced the error - "Uncaught TypeError: Cannot read property 'childNodes' of undefined".
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>':
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna','bacon','beef','loaf','ham');
if(in_array($food, $foodArray))
echo 'We do have '.$food.'!';
elseif($food == '')
echo 'Enter a food you idiot';
else
echo 'Sorry punk we dont sell no '.$food.'!';
echo '</response>';
?>
The code that I have been working with to learn AJAX may not be relevant, I just thought I'd post it in case I can use some of this code that has already been written.
To sum up, I want to be able to do be able to send a boolean, or whatever is viable with AJAX, to the server that tells it to run a script. This script will then open a Maya application and run some Python code that I have written.
Thank you in advance!
As soon as you call the PHP file, this begins running code on the server. If you want to run an external application from PHP, take a look at the exec() function:
http://php.net/manual/en/function.exec.php
You have jQuery listed in your question tags. Have you compared the javascript and jQuery code?
The advantages of using jQuery are:
less typing,
simpler structure
automatically cross-browser
easily use Promises interface
Have a look at these examples and see if you prefer the jQuery AJAX methodologies:
Three simple examples
dynamic drop down box?
Chain AJAX Requests with jQuery Deferred

php javascript code to call php function from 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.

How to use json and ajax to create a javascript array from a PHP array?

Trying the create a javaScript array from a PHP array of urls to images using JSON and AJAX. Then I want to display the images on a cordova app. I believe my issue is I'm either I'm receiving or sending the Json messages with automatic html tags. My xmlhttp.response is equal the array of urls but it has html tags which are not present in the PHP file. I think because of these tags my JSON.parse isn't working?
This is my PHP stored on a server. I'm returning the urls in json message.
<?php
include("mysqlconnect.php");
$select_query = "SELECT `ImagesPath` FROM `offerstbl` ORDER by `ImagesId` DESC";
$sql = mysql_query($select_query) or die(mysql_error());
$data = array();
while($row = mysql_fetch_array($sql,MYSQL_BOTH)){
$data[] = $row['ImagesPath'];
}
echo json_encode($data);
?>
This is my script in my cordova app. I want to covent the JSON message into a javaScript array and display the first image in the array in the div contents. But I think I'm calling a message which includes html tags so I can't parse the message I could be wrong. I currently get three error alerts because the ready state is not correct.
<html>
<script>
var arr = [];
function importJson(str) {
if (str=="") {
document.getElementById("content").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){
alert(xmlhttp.response);
arr = JSON.parse(xmlhttp.response);
//var arr = (array)json.parse(xmlhttp.response);
for (var i = 0; i < arr.length; i++) {
buildImage(arr[i]);
alert(arr[0]);
}
} else {
alert("Error");
}
}
xmlhttp.open("GET","http://server/~name/folder/content.php);
xmlhttp.responseType = "json";
xmlhttp.send();
buildImage=function(src) {
var img = document.createElement('img');
img.src = src;
document.getElementById("content").appendChild(img);
}
}
window.onload = importJson();
</script>
<body>
<div id="content"></div>
At present, your PHP script is outputting a web page, but the javascript is looking for JSON. To output JSON, you need to set the headers in the php script:
header('Content-Type: application/json');
echo json_encode($data);

Javascript AJAX responseText problem in IE

I'm trying to create a sort of chatbox system with PHP/MySql and AJAX but I'm having difficulties running my script in IE. I tested it in Google Chrome and it worked just fine. But when I test it in IE, the AJAX function that should get all messages from the database each 3 seconds, doesn't work properly. It does call the PHP script each 3 seconds and put the responseText into a div (displaying all messages found each 3 seconds). But the messages shown, are the same always ( untill I close the page and re-run the script ). Also when a new message is added to the database, it does not show up. It seems as if the responseText isn't 'updating'. These are my scripts:
(AJAX)
function getMessages(messengerid, repeat)
{
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)
{
document.getElementById("messages").innerHTML=xmlhttp.responseText;
document.getElementById("messages").scrollTop = document.getElementById("messages").scrollHeight;
}
}
xmlhttp.open("GET","modules/get_messages.php?key=abcIUETH85i236t246jerst3487Jh&id="+messengerid,true);
xmlhttp.send();
if(repeat) {
setTimeout("getMessages("+messengerid+", 1);", 3000);
}
}
(PHP/MySql)
<?php
$key = "abcIUETH85i236t246jerst3487Jh";
if( ($_GET['key'] == $key OR defined('IS_INTERNAL')) AND (int)$_GET['id'] > 0) {
include_once("../config.php");
include_once("../class/system.class.php");
$sys = new system($template_name);
if(!$sys->connect($db)) {
exit();
}
$messages = $sys->getEntries("messages", " WHERE messenger_id = '".(int)$_GET['id']."' ORDER BY id ASC ");
$messenger = $sys->getEntries("messengers", " WHERE id = '".(int)$_GET['id']."' LIMIT 1");
$user1 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id1']."' ");
$user2 = $sys->getEntries("accounts", " WHERE id = '".$messenger[0]['account_id2']."' ");
$displaynames[$user1[0]['id']] = $user1[0]['displayname'];
$displaynames[$user2[0]['id']] = $user2[0]['displayname'];
foreach($messages AS $key => $message) {
if(is_numeric($key)) {
?>
<div class="message">
<b><?=$displaynames[$message['account_id']];?> (<?=date("h:m:s", $message['timestamp']);?>) says:</b> <br />
<?=nl2br($message['message_content']);?>
</div>
<?php
}
}
}
?>
Any help would be much appreciated!
Thanks in advance.
Best Regards,
Skyfe.
Your response is being cached. One way to fix this is to append a unique parameter in your request URL, such as the current timestamp.
Its a common problem with IE it caches the result.Add some dummy random parameter to your ajax call e.g current timestamp
i dont know about php but in jsp you can add the following code to your jsp page
response.setHeader("Cache-Control","no-store, no-cache, must-revalidate");
response.setHeader("Pragma","no-cache");
response.setDateHeader ("Expires", 0);
i know the post is old , i just replied for future viewers :D ;)

Categories

Resources