how to get the response from the php page? - javascript

I need to send the textbox value on anchor tag click to checkID.php and display the response sent from php page in html page. I tried using javascripts. But the page is redirected to checkID.php page. need to display in the very same html page.
<a href="#" onclick="javascript:fillContent('checkID.php'); ">
Check Availability
</a>
In form action I speceified as checkID.php.
Following is the javascript I used
<script language="javascript">
function fillContent(resource)
{
xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", resource, true);
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4) {
el = document.getElementById('availabilityResponse')
el.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
</script>
below is my php code
<?php
require_once('lib/nusoap.php');
$client=new nusoap_client("http://localhost/server.php?wsdl");
$error = $client->getError();
if ($error) {
return $error;
}
$alias=$_POST['id'];
$response = $client->call("checkAvailability", array("id" => $alias));
if($client->fault)
{
return $client->faultstring;
}
else
{
$error = $client->getError();
if ($error) {
return $error;
}
else {
return $response;
}
}
?>
how to get response and display in html page?

Not sure why its getting redirected, but in your PHP file -
Instead of
return $response;
Use
echo $response;
Always use echo instead of return in ajax cases

That code should not redirect to that page. Cancel the click action and see if that helps.
onclick="fillContent('checkID.php');return false"

I suggest you to use jquery. Its very simple
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$("#myID").on("click",function(){
$.ajax({ url: 'checkID.php',
type: 'post',
success: function(output) {
$("#availabilityResponse").html(output);
}
});
})
</script>
</head>
<body>
Check Availability
</body>
</html>

Related

Receiving data from JavaScript into PHP

Working example below, hopefully this will help others learn!
I'm using AJAX in javascript to send a JSON string to PHP.
I'm not familiar with AJAX, javascript or php, so this is taking me a while to get started.
I have a html file with a username field, password field, and login button.
Then I have a javascript file that takes the username pass and sends it to a php file.
I know the php file is being accessed because I am seeing the test echo in console.
I just cant figure out how to access the data I'm sending to the php.
script.
function attemptLogin(){
var inputUserName = JSON.stringify(document.getElementById("userName").value);
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', 'ajax.php', true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send(inputUserName);
}
ajax.php
<?php
echo"TestInPHP";
?>
For now all I want to do is echo the username back to console, I'm sure the syntax is something simple, I just cant figure out what it is.
Here is an edit for the working code thanks to SuperKevin in the
comments below. This code will take the string in the username and
password fields in HTML by the JS, send it to PHP and then sent back
to the JS to output to the browser console window.
index.html
<input type="text" name="userID" id="userName" placeholder="UserID">
<input type="password" name="password" id = passW placeholder="Password">
<button type="button" id = "button" onclick="attemptLogin()">Click to Login</button>
script.js
function attemptLogin(){
var inputUserName =
JSON.stringify(document.getElementById("userName").value);
// console.log(inputUserName);
var inputPassword = JSON.stringify(document.getElementById("passW").value);
var cURL = 'ajax.php?fname='+inputUserName+'&pass='+inputPassword;
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', cURL, true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send();
}
ajax.php
<?php
echo $_GET['fname'];
echo $_GET['pass'];
?>
Here's a simple example of how you would make a vanilla call.
This is our main file, call it index.php.
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "delete.php", true);
xhttp.send();
</script>
Here's our server script. delete.php
<?php
echo "HELLO THERE";
Now, if you wanted to pass data to your script you can do the following:
xhttp.open("GET", "delete.php?fname=Henry&lname=Ford", true);
xhttp.send();
To access this data you can use the global $_GET array in php. Which would look like this:
$fname = $_GET['fname'];
$lname = $_GET['lname'];
Obviously, you have to sanitize the data, but that's the gist of it.
For a much more in depth tutorial visit W3Schools Tutorial PHP - AJAX.
You can see all the data sent to your php with :
<?php
print_r($_GET); //if it's send via the method GET
print_r($_POST); //if it's send via the method POST
?>
So, in your case it will be something like :
<?php
echo $_GET['username'];
?>
If you're not using jQuery then don't pay attention to my answer and stick to the pure javascript answers.
With jQuery you can do something like this:
First Page:
$.ajax({
url: 'sportsComparison.php',
type: 'post',
dataType: 'html',
data: {
BaseballNumber = 42,
SoccerNumber = 10
},
success: function(data) {
console.log(data);
});
which will send the value 42 and 10 to sportsComparison.php with variable names BaseballNumber and SoccerNumber. On the PHP page they can then be retrieved using POST (or GET if that's how they were sent originally), some calculations performed, and then sent back.
sportsComparison.php:
<?php
$BaseballValue = $_POST["BaseballNumber"];
$SoccerValue = $_POST["SoccerNumber"];
$TotalValue = $BaseballValue * $SoccerValue;
print "<span class='TotalValue'>".$TotalValue."</span>";
?>
This will return a span tag with the class of TotalValue and the value of 420 and print it in the console.
Just a simple way to do ajax using jQuery. Don't forget commas in the parameter list.

passing data using post array in java-script

i am try to load B.php from A.php after execution in the function and pass some data using a post array from A.php to B.php within same time.
code list as follows
A.php
<script type="text/javascript">
alert_for_the_fucntion();
window.location.href = "B.php";
function alert_for_the_fucntion() {
$.post("B.php", {action: 'test'});
}
</script>
B.php
<?php
if (array_key_exists("action", $_POST)) {
if ($_POST['action'] == 'test') {
echo 'ok';
}
}
?>
for testing purpose i tried to echo something in the B.php. but currently this is not working. have i done any mistakes? or is there any possible method to do this.
Your code does this:
Tells the browser to navigate to B.php (using a GET request)
Triggers a POST request using XMLHttpRequest
The POST request probably gets canceled because the browser immediately leaves the page (and the XHR request is asynchronous). If it doesn't, then the response is ignored. Either way, it has no effect.
You then see the result of the GET request (which, obviously, doesn't include $_POST['action']) displayed in the browser window.
If you want to programmatically generate a POST request and display the result as a new page then you need to submit a form.
Don't use location. Don't use XMLHttpRequest (or anything that wraps around it, like $.ajax).
var f = document.createElement("form");
f.method = "POST";
f.action = "B.php";
var i = document.createElement("input");
i.type = "hidden";
i.name = "action";
i.value = "test";
f.appendChild(i);
document.body.appendChild(f);
f.submit();
If you want to process the results in JavaScript then:
Don't navigate to a different page (remove the line using `location)
Add a done handler to the Ajax code
e.g.
$.post("B.php", {action: 'test'}).done(process_response);
function process_response(data) {
document.body.appendChild(
document.createTextNode(data)
);
}
Try this:
Javascript:
<script type="text/javascript">
window.onload = alert_for_the_fucntion;
function alert_for_the_fucntion() {
$.post("B.php",
{
action: 'test'
},
function(data, status){
if(status=="success"){
alert(data);
}
}
);
}
</script>
PHP
<?php
if(isset($_POST['action'])){
echo $_POST['action'];
}
?>

PHP header(Location:'index.php') and javascript not being executed

My problem is, when the user logout. The login page is being called and the index page is showing but the url is saying
https://mysite/logout.php
instead of
https://mysite/index.php
which means my javascript files included in the index.php ain't being loaded, so you cant log in again without refreshing the page manually.
Link in home.php the page you reach after login
<p class="mc-top-margin-1-5">Logout</p>
I have the following logout page (logout.php)
<?php
session_start();
require_once 'php/class/class.user.php';
$user = new USER();
if(!$user->is_logged_in())
{
$user->redirect('index.php');
exit;
}
if($user->is_logged_in()!="")
{
$user->logout();
$user->redirect('index.php');
exit;
}
?>
my user functions as follow (class.user.php)
public function is_logged_in()
{
if(isset($_SESSION['userSession']))
{
return true;
}
}
public function redirect($url)
{
header("Location: $url");
}
public function logout()
{
session_destroy();
}
what am I missing?
Your function is_logged_in() returns a boolean, TRUE, but you are checking the return value with:
if($user->is_logged_in()!="")
That is, checking if it's an empty string.
Also, and more importantly, is_logged_in() doesn't return anything if the user is not logged in. That function should be something like:
public function is_logged_in()
{
if(isset($_SESSION['userSession']))
{
return true;
}
else { return false; }
}
And the check should be something like:
if(!$user->is_logged_in())
so i ended up with a not very nice solution:
I changed the link in home.php
`<p class="mc-top-margin-1-5">Logout</p> `
To a button
<button id="btn-logout">Logout</button>
and added its functionality in a jquery function
$(function(){
$("#btn-logout").bind('click', function () {
window.location.href = "http://example.com/logout.php";
})
});
my logout.php ended up looking like
<?php
session_start();
unset($_SESSION['user_session']);
session_destroy();
?>
<html>
<head>
<script>
window.location.href = "https://example.com/index.php";
</script>
</head>
<body>
</body>
</html>
So going from refresh page in php using header. I ended up with js and jquery. Its not a nice solution above, but it works!

Upload progress bar using session in PHP 5.4 with codeigniter

With reference to this tutorial. Tracking upload progress with php . I want to make it work in Codeigniter. I am not getting point to start to make it work in CI. I want to upload files and also track progress.
In my CI view
<?php $arr = array("id"=>"myform");
echo form_open_multipart("welcome/uploads",$arr); ?>
<input type="hidden" value="myForm" name="<?php echo ini_get("session.upload_progress.name"); ?>">
<table>
<tr>
<td>file</td>
<td><input type="file" name="images[]" multiple></td>
</tr>
<tr>
<td>name</td>
<td><input type="text" name="naam"></td>
</tr>
<tr>
<td></td>
<td><input type="submit"></td>
</tr>
</table>
<?php echo form_close(); ?>
<div id="bar_blank">
script
function toggleBarVisibility() {
var e = document.getElementById("bar_blank");
e.style.display = (e.style.display == "block") ? "none" : "block";
}
function createRequestObject() {
var http;
if (navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
http = new XMLHttpRequest();
}
return http;
}
function sendRequest() {
var http = createRequestObject();
http.open("GET", "<?php echo base_url().'index.php/welcome/progress' ?>");
http.onreadystatechange = function () { handleResponse(http); };
http.send(null);
}
function handleResponse(http) {
var response;
if (http.readyState == 4) {
response = http.responseText;
document.getElementById("bar_color").style.width = response + "%";
document.getElementById("status").innerHTML = response + "%";
if (response < 100) {
setTimeout("sendRequest()", 1000);
}
else {
toggleBarVisibility();
document.getElementById("status").innerHTML = "Done.";
}
}
}
function startUpload() {
toggleBarVisibility();
setTimeout("sendRequest()", 1000);
}
(function () {
document.getElementById("myForm").onsubmit = startUpload; //error is here
})();
According to above tutorials, its in core php. When submitting form CI request to controller dashboard/addRoom and my page gets refresh anyhow. But in tutorials, Form redirects to PHP_SELF (same php file). I am not getting any idea on it. Please help me.
Controller
function progress()
{
session_start();
$key = ini_get("session.upload_progress.prefix") . "myForm";
if (!empty($_SESSION[$key])) {
$current = $_SESSION[$key]["bytes_processed"];
$total = $_SESSION[$key]["content_length"];
echo $current < $total ? ceil($current / $total * 100) : 100;
}
else {
echo 100;
}
}
public function uploads()
{
if(!empty($_FILES['images']['name'][0]))
{
//uploadinf file code
}
}
If you want to do it with only jQuery then i have used jQuery Form Submit Plugin, which will give you the progress and more. As you said in comments you don't need any plugin then follow these steps and implement like the tutorial suggesting.
Lets assume you have controller dashboard and method addRoom is displaying the your html form:
class Dashboard extends CI_Controller {
function addRoom() {
// Detect URI: http://example.com/dashboard/addRoom/upload_file
$upload_req = $this->uri->segment("3");
if( $upload_req == "upload_file" ) {
// Do the file upload Actions
}
// Generate Form
$this->load->view("Generate_view");
}
}
View:
<?php
$ar = array("class"=>"form-horizontal");
echo form_open_multipart('dashboard/addRoom/upload_file',$ar);
?>
<input type="text" name="fileName">
<input type="file" name="upload">
<input type="submit" value="add">
<?php echo form_close(); ?>
In this case your form is still on the same controller and method even you submit or not.
Update: According to updated answer, please use codeigniter default libraries for Session and File Uploads, In case of JS error, use console tab(Chrome) to debug error, or if you are using firefox then use firebug extension to debug Javascript.
If you just want to show upload progress there are many plugins available to do so, I don't know why you specifically mentioned Session in you title.
Here is a very nice and simple plugin which will work with any PHP framework with ease.
Code Sample
<script>
/*jslint unparam: true */
/*global window, $ */
$(function () {
'use strict';
// Change this to the location of your server-side upload handler:
var url = window.location.hostname === 'blueimp.github.io' ?
'//jquery-file-upload.appspot.com/' : 'server/php/';
$('#fileupload').fileupload({
url: url,
dataType: 'json',
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').text(file.name).appendTo('#files');
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
$('#progress .progress-bar').css(
'width',
progress + '%'
);
}
}).prop('disabled', !$.support.fileInput)
.parent().addClass($.support.fileInput ? undefined : 'disabled');
});
</script>
You're missing (I don't see it in your code) that the tutorial in your question declare and use an hidden iframe in the target attribute of the the upload form, this is a way to handle uploads preventing the form page to refresh (the action url will be loaded into the iframe).
google for hidden iframe upload (and eventually for formdata upload which nowadays should be a better way to handle uploads and show progress with few javascript)
here an old example which use the hidden iframe Ajax File Upload Response Handling
update
You should change the code in your view to $arr = array("id"=>"myForm")
Currently I see it is array("id"=>"myform") (all lowercase)
getElementById is case sensitive and you use .getElementById("myForm").onsubmit
When you use some javascript and something isn't working as expected the browser's javascript console is the first place to look, you should see an error like (chrome):
Uncaught TypeError: Cannot set property 'onsubmit' of null
This is because getElementById fail to find an element with id myForm and return null, in the html/DOM it is really named myform.
update
So, I got the thing working, instead of welcome controller I've created a new Upload controller (uppercase because I'm using CI 3 dev, should be easy to adapt it to old versions), below the working files.
The url will be http://your-host/optional-dir/index.php/upload.
application/controllers/Upload.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Upload extends CI_Controller {
public function index() {
$this->load->helper(array('form', 'url'));
$this->load->view('upload');
}
function progress() {
session_start();
$key = ini_get("session.upload_progress.prefix") . "myForm";
if (!empty($_SESSION[$key])) {
$current = $_SESSION[$key]["bytes_processed"];
$total = $_SESSION[$key]["content_length"];
echo $current < $total ? ceil($current / $total * 100) : 100;
} else {
echo 100;
}
}
public function uploads() {
if(!empty($_FILES['images']['name'][0])) {
//uploadinf file code
}
}
}
application/views/upload.php:
<!DOCTYPE html>
<html>
<head>
<title>upload</title>
<style>
#bar_blank {
border: solid 1px #000;
height: 20px;
width: 300px;
}
#bar_color {
background-color: #006666;
height: 20px;
width: 0px;
}
#bar_blank, #hidden_iframe {
display: none;
}
</style>
</head>
<body>
<?php $arr = array("id"=>"myForm", "target"=>"hidden_iframe");
echo form_open_multipart("upload/uploads",$arr); ?>
<input type="hidden" value="myForm" name="<?php echo ini_get("session.upload_progress.name"); ?>">
<table>
<tr>
<td>file</td>
<td><input type="file" name="images[]" multiple></td>
</tr>
<tr>
<td>name</td>
<td><input type="text" name="naam"></td>
</tr>
<tr>
<td></td>
<td><input type="submit"></td>
</tr>
</table>
<?php echo form_close(); ?>
<iframe id="hidden_iframe" name="hidden_iframe" src="about:blank"></iframe>
<div id="status"></div>
<div id="bar_blank">
<div id="bar_color"></div>
</div>
<?php include_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'upload.js.php'); ?>
</body>
</html>
./application/views/upload.js.php:
<script>
function toggleBarVisibility() {
console.log('toggleBarVisibility');
var e = document.getElementById("bar_blank");
e.style.display = (e.style.display == "block") ? "none" : "block";
}
function createRequestObject() {
console.log('createRequestObject');
var http;
if (navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http = new XMLHttpRequest();
}
return http;
}
function sendRequest() {
console.log('sendRequest');
var http = createRequestObject();
http.open("GET", "<?php echo base_url().'index.php/upload/progress' ?>");
http.onreadystatechange = function () { handleResponse(http); };
http.send(null);
}
function handleResponse(http) {
console.log('handleResponse');
var response;
if (http.readyState == 4) {
response = http.responseText;
document.getElementById("bar_color").style.width = response + "%";
document.getElementById("status").innerHTML = response + "%";
if (response < 100) {
setTimeout("sendRequest()", 1000);
} else {
toggleBarVisibility();
document.getElementById("status").innerHTML = "Done.";
}
}
}
function startUpload() {
console.log('startUpload');
toggleBarVisibility();
setTimeout("sendRequest()", 1000);
}
(function () {
console.log('init');
document.getElementById("myForm").onsubmit = startUpload; //error is here
})();
</script>
notice
I'm using a raw include_once for convenience, because php base_url is used inside the javascript, probably would be better have a small inline javascript in the view's html which declare a javascript variable with the base_url value then include the static javascript from an assets directory as usual.
the tutorial i have seen actually you have to write AJAX in your view, and call the controller via ajax not via form submission with button. so than your page will not get refreshed. take a close look on the tutorial you have provided the link, and when you scroll down you will see javascript where it send HTTP requests via AJAX for example
function createRequestObject() {
var http;
if (navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
}
else {
http = new XMLHttpRequest();
}
return http;
}
this is a 1 function where it create XMLHttpRequests to get response from file where you have to get response via XMLHttpRequest from your controller.
Regards

php inside javascript alternative

In the code below after user click in cancel button It will call the function botao_excluir(). Inside of this function I want to run the cancela_cielo() php function. But I know that is impossible to run PHP inside JavaScript. So Could someone please tell me a way to do this?
PHP
<?php
$id=$row['id_temp_transaction'];
if($row['status']!=9)
{
echo "<input type = \"button\" name=\"cancel\" value = \"Cancel\" onclick= \"botao_excluir()\" >";
}
?>
JavaScript
<script>
function botao_excluir()
{
var r=confirm("Press OK to confirm the cancel")
if (r==true)
{
<?php cancela_cielo($row['tid'], $row['numero_afiliacao'], $row['chave_utilizada']); ?>
alert("Transaction Canceled")
}
else
{
alert("Cancel aborted")
}
}
You can do this using ajax
this will send the request to page.php as example the request will be executed in php and the data will be returned.
function botao_excluir()
{
var r=confirm("Press OK to confirm the cancel")
if (r==true)
{
xhr = new XMLHttpRequest()
xhr.open("POST","page.php",false);
xhr.send();
// response will be assigned to data variable
data = xhr.responseText
alert("Transaction Canceled")
}
else
{
alert("Cancel aborted")
}
}
you can read more about ajax and php here
http://www.w3schools.com/php/php_ajax_php.asp

Categories

Resources