sending of json data between client and php server - php

this is the server side code
<?php
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 01 Jan 2016 00:00:00 GMT');
header('Content-type: application/json');
$id = $_GET['id'];
$data = array("Hello", $id);
echo json_encode($data);
?>
and this is the client side code
<html>
<head>
<script src="jquery-1.1.1.min.js"></script>
<script language="javascript">
function show(json) {
alert(json);
}
function run() {
$.getJSON("/localhost/jserver1.php",
{ id: 567 },
show);
}
window.onload=run;
</script>
</head>
<body>
JSON Test Page.
</body>
</html>
What i want to do here is i want to send messages between client and server using php and json. when i run the server side code i am getting the output as hello with the id given in the url in the localhost,but when i run the client side code i am getting only the body of the html page,I am not getting the alert with the input id that is there in the run method.Please someone tell me what is the problem

Instead of
$.getJSON("URL",
{ id: 567 },
show
);
window.onload=run;
Use -
$.getJSON("URL",
{ id: 567 },
function(response){
show(response);
});
window.onload=run();

Try removing the / in front of /localhost/jserver1.php and adding http://.
Currently it refers to localhost/localhost/jserver1.php

Still very bad code, you should split up your files. But here we go:
<?php
if($_GET['id']) {
$id = $_GET['id'];
$data = array("Hello", $id);
echo json_encode($data);
} else {
?>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript">
function show(json) {
alert(json);
}
function run() {
$.ajax({
url : '/whatever/this/page/is',
type : 'GET',
data : 'id=567',
success: function(res) {
show(res);
}
});
}
window.onload=run;
</script>
</head>
<body>
JSON Test Page.
</body>
</html>
<?
}

Try with this code
function show(json) {
alert(JSON.stringify(json));
}

Related

How do I get response data from php with ajax (one file)?

I'am trying to get php response data with ajax. I want to check if there is a specific string in testing.txt from my input and if the string is found, php should echo "1" but no matter what I try AJAX always says the output isn't 1
This is my code:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
if (in_array($_POST['table'], $file)) {
echo "1";
} else {
echo "0";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text);
};
function post(vally) {
var table = vally;
$.post('test.php', {table:table}, function(data) {
})
.done(function (data) {
if (data == 1) {
console.log("the output is 1")
} else {
console.log("the output isn't 1")
}
});
console.log('posted');
}
</script>
</body>
</html>
testing.txt:
abc
def
ghi
The response I get if i console.log(data):
0<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text);
};
function post(vally) {
var table = vally;
$.post('test.php', {table:table}, function(data) {
})
.done(function (data) {
if (data == 1) {
console.log("the output is 1")
} else {
console.log(data)
}
});
console.log('posted');
}
</script>
</body>
</html>
I have tried using .done(), .fail() and .always() but I always get the output isn't 1(I am using JQuery 3.2.1).
Can someone tell me what I'm doing wrong?
EDIT: I would like to point out something I haven't before. I'm looking for a one page solution. I know that it can easily be done with two pages but I was wondering if there was a one page solution.
The problem is the Ajax request is sent to the home page, so it receives everything after '0' or '1'. Split that.
Move your PHP code in anoter file, say 'ajax.php'
And change your $.post() settings to call ajax.php instead of test.php.
So the Ajax request will only receive the '0' or '1' string.
Notice how your AJAX response is the entire page, prepended with the single digit that you're looking for. You don't need to send the whole page to the browser twice. Move your PHP logic into its own file with nothing but that logic. Let's call it checkTable.php for the sake of demonstration:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
if (in_array($_POST['table'], $file)) {
echo "1";
} else {
echo "0";
}
}
?>
Then make your AJAX call to that page:
$.post('checkTable.php', {table:table})
Then the response will contain only what that PHP code returns, not the whole page. (It's worth noting that this PHP code will return an empty response if table isn't in the POST data.)
Aside from that, your code is currently returning a 0 for whatever input you're providing, so it's still going to be true that "the output isn't 1". For that you'll need to double-check your input and data to confirm your assumptions.
Because I wanted everything in one file I decided to use data.slice(0, 1); to trim off everything except the first character which will be a 0 or 1, and thanks to David for reminding me that there may be a whitespace issue, which there was. Now I added text.trim() to remove all of the whitespace from the input and array_filter(array_map('trim', $file)); to remove all of the whitespace from the strings written in the file.
This is the finished code:
<?php
if (isset($_POST['table'])) {
$file = file("testing.txt");
$file = array_filter(array_map('trim', $file));
if (in_array($_POST['table'], $file) == true) {
echo "1";
} else {
echo "0";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<input type="text" name="text" id="text">
<button id="button">NEXT</button>
<script type="text/javascript" src="jquery.js"></script>
<script>
var text;
document.getElementById('button').onclick = function () {
text = document.getElementById('text').value;
post(text.trim());
};
function post(vally) {
var table = vally;
console.log(vally);
$.post('test.php', {table:table}, function(data) {
var cut = data.slice(0, 1);
if (cut == 1) {
console.log("the output is 1")
} else {
console.log(cut);
}
});
console.log('posted');
}
</script>
</body>
</html>
I would like to thank everyone who helped me resolve my issue, which has been bugging me for the last 2 days.

How to filter a JSON page feeding data to Select2?

I'm trying to populate a Select2 box with data from a t-sql query. The query is run on a PHP page which translates the output to JSON and is called in the javascript of the main page.
The main page looks like this:
<?php
header('Content-type: text/html; charset=UTF-8');
require('db.php'); // Bring in the database connection
include("auth.php"); // Make sure the user is logged in to an account
?>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" http-equiv="Content Type" charset="utf-8"/>
<!-- JQuery -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- SELECT 2 -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
</head>
<body style="background-color: #F5F5F5;">
<select class="js-data-example-ajax">
</select>
<script>
$('.js-data-example-ajax').select2({
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json'
// Additional AJAX parameters go here
}
});
</script>
</body>
</html>
My JSON page looks like this:
<?php
require('db.php'); // Bring in the database connection
include("auth.php"); // Make sure the user is logged in to an account
$search = $_GET['search'];
//JSON Table Stuff
$sql = "SELECT DISTINCT [IN] AS id, Nom as text
FROM dbo.[TFM_NumérosIN2012]
;";
$stmt = sqlsrv_query($con,$sql);
$result = array();
do {
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
$result[] = $row;
}
} while (sqlsrv_next_result($stmt));
sqlsrv_free_stmt($stmt);
$data2 = json_encode($result);
echo '{ "results":' . $data2 . '}';
?>
The data output by the JSON page looks like this:
{ "results":[{"id":2,"text":"SMITH Sean"},{"id":3,"text":"CHARLES charley"},{"id":4,"text":"TFC Madrid"},{"id":5,"text":"VAN DAMME jean claude"}]}
The data is loading into the select list without any problems. However, I've tried to filter the data multiple ways and nothing has worked. I've tried adding a data parameter and passing a search variable to the php/JSON page and referencing in the $sql variable as a where clause, but this doesn't return anything
To try and filter the data I changed the javascript to this:
$('.js-data-example-ajax').select2({
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term
}
// Query parameters will be ?search=[term]&type=public
return query;
}
}
});
But this breaks my select and and it displays a message 'The results could not be loaded.'
Does anyone know what I'm doing wrong here?
Cheers,
At the end of your php file just echo the following line :
echo json_encode($result);
In your html/js file :
<link href='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js'></script>
<select name='js-data-example-ajax' class='js-data-example-ajax'></select>
$(document).ready(function()
{
$('.js-data-example-ajax').select2({
placeholder: "Search for product",
minimumInputLength: 1,
width: '250px',
ajax: {
url: 'http://10.1.248.41/TFM-Project/ImportINjson.php',
dataType: 'json',
data: function (params) {
var query = {
search: params.term,
type: 'public'
}
console.log("query : "+query.search);
return query;
},
processResults: function (response) {
console.log("response : "+response);
return {
results: $.map(response, function(obj) {
console.log("response obj.id: "+obj.id);
console.log("response obj.text: "+obj.text);
return { id: obj.id, text: obj.text };
})
};
},
cache: false
}
});
});

Retrieve data from database in PHP and display them in JQuery on the same page

Today I need some help concerning one of my work. I'm trying to display, in JQuery, some data I retrieved, in PHP, from my database.
I need to display the data in JQuery for some reasons...
My PHP and my JQuery are on the same page, index.php, but my problem is that my ajax won't display my data and no error appears so I don't know exactly where is my mistake.
Here is my code:
<?php
require 'inc/db-connect.php';
$title = array();
try{
$sql = "SELECT * FROM events";
$req = $db->query($sql);
}catch(PDOException $e){
echo 'Erreur: '.$e->getMessage();
}
while($res = $req->fetch()){
array_push($title, $res['title']);
}
echo json_encode($title);
$req->closeCursor();
?>
<!DOCTYPE html>
<html lang="fr">
<?php include('inc/head.html'); ?>
<body>
<div id="stage">
/**
* ALL MY HTML GOES HERE
**/
</div>
<!-- END STAGE -->
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
data: "",
dataType: 'json',
success: function(data){
console.log(data);
},
error: function(){
console.log('Failed to load data');
}
});
});
</script>
</body>
</html>
So when I load my page, my JQuery does the "console.log('Failed to load data')" which means there is an error but I can't find it.
Somebody can help me please ?
Thnx,
Antho
EDIT 1:
It seems there is no problem with my PHP request because the echo display the data I retrieve from the database. Apparently the error comes from my ajax request.
I've set the URL parameters on 'index.php' but doesn't work neither.
EDIT 2:
After some researches it seems impossible to make a PHP request and an ajax request on the same page. So I'll try something else...
What you are currently doing is this:
you are creating an output that looks like this:
{"your json is": "here"}
<html>
... rest of html
<script> doing an ajax request to get the json </script>
...
</html>
Now there are multiple problems.
There is json before the html output
there is an ajax call that tries to get the file you just outputted,
but there is html after the json, so it does not understand the json
To fix this you could put it in 2 different files.
getmyjson.php
<?php
require 'inc/db-connect.php';
$title = array();
try{
$sql = "SELECT * FROM events";
$req = $db->query($sql);
}catch(PDOException $e){
echo 'Erreur: '.$e->getMessage();
}
while($res = $req->fetch()){
array_push($title, $res['title']);
}
header('Content-type: application/json');
echo json_encode($title);
$req->closeCursor();
exit();
index.php
<html lang="fr">
<?php include('inc/head.html'); ?>
<body>
<div id="stage">
/**
* ALL MY HTML GOES HERE
**/
</div>
<!-- END STAGE -->
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "getmyjson.php"
data: "",
dataType: 'json',
success: function(data){
console.log(data);
},
error: function(){
console.log('Failed to load data');
}
});
});
</script>
</body>
</html>
or you could put it in one file and use conditions to split it up
<?
if(isset($_GET['getmyjson']))
{
// output json (incl header)
exit();
}
else // why an else when you already did an exit.. just to be safe when you or someone else is modifying the code
{
// output your main page with the ajax script that calls "url: '?getmyjson=true'"
}
Set the header of the content to type of json... Here is an example of setting header type.
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
Any malformed JSON is rejected and a parse error is thrown.

How do I send data to my PHP script using AJAX?

I'm new to PHP and Javascript/Ajax so please bear with me.
All I need to do is get a variable from Ajax and set it as a variable in php. I'm trying to do this with a super global GET but something is not right. I don't want to this by submitting the form.
Here's my JS:
function myFunction(){
var hora= document.getElementById("hora").value;
$.ajax({
type : 'GET',
url : 'reservation.php',
data : {hora: hora},
success : function(data) {
console.log(hora);//This is because I was curious as to
// what the console would say. I found
// that this sets the super global if I
// change the url to something else that
// doesn't exist. Console would say
// -GET http://localhost/bus/(somepage).php?hora=4
// 404 (Not Found)-
alert(hora);
}
})
}
Here's my PHP:
Hora:
<select name="hora" id="hora" onchange="myFunction()">
<?php
$query = "SELECT * FROM vans";
$horas_result = mysql_query($query);
while ($horas = mysql_fetch_array($horas_result)) {
echo "<option value=\"{$horas["van_id"]}\">{$horas["time"]}</option>";
}
?>
</select>
Asientos Disponibles:
<?php echo $_GET["hora"]; ?>
//Right now I only want to echo this variable..
As you can see, right now I only want to echo this variable, later on I'll be using this to write a query.
Look at the code i post, ajax is used to post/get data without need to refresh the page but if you just want to post the data and give the result in other page use a form instead.
<?php
if (isset($_GET["hora"]))
{
echo $_GET["hora"];
exit;
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Page title</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(document).ready(function()
{
$("#hora").change(function ()
{
$.ajax(
{
type : 'GET',
url : '',
data : $('select[name=\'hora\']'),
success : function(data)
{
$('#ajax_result').html('Asientos Disponibles: ' + data);
},
error: function(xhr, ajaxOptions, thrownError)
{
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
}
)
}
)
}
)
</script>
<select name="hora" id="hora">
<?php
$query = "SELECT * FROM vans";
$horas_result = mysql_query($query);
while ($horas = mysql_fetch_array($horas_result)) {
echo "<option value=\"{$horas["van_id"]}\">{$horas["time"]}</option>";
}
?>
</select>
<div id="ajax_result">
</div>
</body>
</html>
For example, the following script
$.ajax({
type: "POST",
url: "test.php",
data: {value:1}
}).done(function(msg) {
// msg contains whatever value test.php echoes. Whether it is code, or just raw data.
if(msg=="Success") {
alert("hello world");
} else {
alert("Hello Hell")
}
});
Will set the variable $_POST['value'] to 1
and my test.php looks like:
<?php
if($_POST['value'] == "1") {
echo "Success";
} else {
echo "Failure";
}
?>
If you run that example, the webpage will show you an alert box with the text "Hello World"
If you change the value to any other number, it will show you an alert with the text "Hello Hell"
Hope that answers your question.

Download a file built in PHP output buffer from AJAX call

I am trying to build a CSV file in PHP, then call the PHP file from an AJAX call, which will then initiate a download of the CSV file upon success of the AJAX call. This works fine if I save a physical copy of the .csv on the server, but I would like to use php://ouput so I do not have to worry about physical files clogging up the server. Is it possible to initiate a download from returning php://output to AJAX? Here is my code:
HTML/jquery:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript">
$("#download").live("click", function() {
var request = $.ajax({
dataType: 'html',
url: 'php.php',
success: function(response) {
alert('Finished');
}
})
})
</script>
</head>
<body>
<h1 id="download">DOWNLOAD</h1>
</body>
</html>
PHP:
<?php
header('Content-type: application/vnd.ms-excel');
header('Content-disposition: attachment; filename="test.csv"');
$f = fopen('php://output', 'w');
fwrite($f,'this,is,a,test');
fclose($f);
readfile('php://output');
return;
?>
I am not sure how to get this to return a File Save dialog from my AJAX call.
This has to be simple, but I can't seem to find any examples that combines these two issues.
You can do this by creating and sending form via jquery (page not reloaded):
$(document).on('click', '#download', function () {
var form = $(document.createElement('form'));
form.attr('action', 'php.php');
form.attr('method', 'GET');
form.appendTo(document.body);
form.submit();
form.remove();
});
Also you can pass post parameters if need:
$(document).on('click', '#download', function () {
var form = $(document.createElement('form'));
form.attr('action', 'php.php');
form.attr('method', 'POST');
var input = $('<input>').attr('type', 'hidden').attr('name', 'x').val('x value');
form.append(input);
form.appendTo(document.body);
form.submit();
form.remove();
});
The following works, but is highly inneficient as it calls the php.php file twice. Does anybody have any better ideas?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script type="text/javascript" language="javascript" src="jquery.js"></script>
<script type="text/javascript">
$("#download").live("click", function() {
var request = $.ajax({
dataType: 'html',
url: 'php.php',
success: function(response) {
window.open('php.php');
}
})
})
</script>
</head>
<body>
<h1 id="download">DOWNLOAD</h1>
</body>
</html>
Is there anyway to cache 'php.php' for just this instance so that it loads instantly under window.open('php.php'), but will reload contents when I click download next?
Why does window.open(response) not work the same?
look this:
if (!headers_sent()) {
// seconds, minutes, hours, days
$expires = 60*60*24*14;
header('Pragma: public');
header('Cache-Control: maxage=' . $expires);
header('Expires: ' . gmdate('D, d M Y H:i:s', time() + $expires) . ' GMT');
}
Note: this will not work with POST requests, just GET.
To allow for a file download, you can simply call the below code (say on a button's onclick):
window.open(<file-url>);
Hope this helps.

Categories