post json data to php and echo result - javascript

I'm a struggling learner of php and javascript and Have been searching frantically for a solutionbut to no avail. I am trying to send a json object/string from one page to another using php and then echo the results in that new page (eventually to generate a pdf using tcppdf) . So basically some javascript generates an object, pageStructure, in one page, which I then stringify:
var jsonString = JSON.stringify(pageStructure);
alert(jsonString);`
The alert pops up fine.
I now want to send (post) this to another php file getdata.php and then play around with it to construct a pdf.
I have tried posting with forms but updating the value of an input in the form with jsonString won't work.
**ADDITION - EXPLANATION OF MY PROBLEM HERE
I created a form as follows:
<form action="getdata.php" method="post">
<textarea type="hidden" id="printMatter" name="printMatter" value=""></textarea>
<button type="submit"><span class="glyphicon glyphicon-eye-open" ></span></button>
</form>
I have some code after constructing jsonString to set the value of the textarea to that value:
document.getElementById('printMatter').value = jsonString;
alert(document.getElementById('printMatter').value);
A submit button activates the form which opens the getdata.php page but I noticed two things:
(1) before sending the jsonString string is full of escapes () before every quote mark (").
(2) when getdata.php opens, the echoed jsonString has changed to include no \s but instead one of the values ('value') of an object in the json string (a piece of svg code including numerous \s) - for example (truncated because the value is a very long svg string, but this gives the idea):
{"type":"chartSVG","value":"<g transform=\"translate(168.33333333333334,75)\" class=\"arc\">...
has changed to integers - for example:
{"type":"chartSVG","value":"12"}
I don't understand how or why this happens and what to do to get the full svg code to be maintained after the form is posted.
**
I have tried using jquery/ajax as follows:
$.ajax({
url: 'getdata.php',
type: 'post',
data: {printMatter: jsonString},
success: function(){
alert('it worked');
},
error: function(){
alert('it failed')}
})
I'm getting the success response but I end up on the same page instead of getting the new php file to just echo what it is being sent!
The php script contains the following:
<?php
echo $_POST['printMatter'];
?>
But this doesn't work. Nor does trying to add a header to the php page (e.g. header('Content: application/json'). I end up staying on my original page. How do I get this to leave me on the new page (getdata.php) with an echo of the json string?
Can anyone explain what I am doing wrong or how I can get what I want?
Thank you so much.
**ADDITION
This is indicative of how I get the jsonString object:
function item(type,value) {
this.type = type;
this.value = value;
}
for (i=0;i<thePage[0].length;i++) {
pageid = thePage[0][i].id;
var entry = new item("page",pageid);
pageStructure.push(entry);
}
var jsonString = JSON.stringify(pageStructure);
So I end up with a series of pages listed out in the jsonString.

Try changing $_POST to $_GET since your AJAX request is doing a HTTP GET and not a HTTP POST.

UPDATE
This doesn't leave me on the page I want to be on. I don't want to refresh the page but just redirect to a new page that receives the posted json data.
By this is essentially a page "refresh", though perhaps "refresh mislead you because it can imply reloading the current URL. What i meant by refresh was a completely new page load. Which is essentially what you are asking for. There are a few ways to go about this...
If you data is pretty short and will not violate the maximum length for a URI on the webserver then you can jsut use window.location:
// send it as json like you are currently trying to do
window.location = 'getdata.php?printMatter=' + encodeURIComponent(jsonString);
// OR send it with typical url-encoded data and dont use JSON
window.location = 'getdata.php?' + $.serialize(pageStructure);
In this case you would use $_GET['printMatter'] to access the data as opposed to $_POST['printMatter'].
If the data has the potential to produce a long string then you will need to POST it. This gets a bit trickier since if we want to POST we have to use a form. Using JSON and jQuery that is pretty simple:
var form = '<form action="getdata.php" method="post">'
+ '<input type="hidden" name="printMatter" value="%value%" />'
+ '</form>';
form.replace('$value%', jsonString);
// if you have any visual styles on form that might then you may
// need to also position this off screen with something like
// left: -2000em or what have you
$(form).css({position: 'absolute'})
.appendTo('body')
.submit();
If we wanted to just send this as normal formdata then it would get more complex because we would need to recursively loop over pageStructure and create input elements with the proper name attribute... i wouldn't got that route.
So the final way (but i dont think it would work because it seems like youre tryign to generate a file and have the browser download it) would be to send it over AJAX and have ajax return the next url to go to:
JS
$.ajax({
url: 'getdata.php',
type: 'post',
data: {printMatter: jsonString},
type: 'json',
success: function(data){
window.location = data.redirectUrl;
},
error: function(){
alert('it failed')}
});
getdata.php
// do something with the $_POST['printMatter'] data and then...
$response = array(
'redirectUrl' =>$theUrlToGoTo
);
header('Content-Type: application/json');
print json_encode($response);
You are using AJAX. By nature AJAX will not refresh the page for example if you do this:
$.ajax({
url: 'getdata.php',
type: 'post',
data: {printMatter: jsonString},
success: function(data){
alert('it worked');
alert('You sent this json string: ' + data);
},
error: function(){
alert('it failed')}
});
Also note that i changed your type from 'get' to 'post'... The type set here will in part determine where you can access the data you are sending... if you set it to get then in getdata.php you need to use $_GET, if you set it to post then you should use $_POST.
Now if you actually want a full page refresh as you implied then you would need to do this another way. How you would go about it i cant say because you havent provided enough of an idea of what happens to get your jsonString before sending it.

Related

Php file called by ajax isn't echoing javascript code

I'm trying to create a page where a user can upload a file and select the people they want to email it to. Once they click submit, I prevent page refresh and reset their inputs in the form. Now I want to place their previously entered information into a table on the same page (different section of the page).
If you did want to proceed with this concept, you would capture the output of the PHP script in a done() function, insert it in an element on the page, and run eval(). Like this...
$.ajax({
type: "POST",
url: "../FileDrop/dbSystem.php",
data: {tags: JSON.stringify(tags), file:
$('input[name=fileName]').val()};
}).success(function(result) {
$( '#element' ).html(result);
$( '#element script' ).each( () => { $(this).html().eval() })
});
But it would make alot more sense to return data that you use to execute the javascript in your page - that is, keep all that logic together rather than splitting some of it off into a PHP file.
<?php
// php process that checks for 'valid'...
// create a json response
$output = array('valid' => 1);
echo json_encode($output);
?>
.... and in your JS
.success(function(result) {
// result is a stringified JSON object. We need to convert it into an actual JSON object with parse()
result = JSON.parse(result);
// might not matter, but result.valid will be a number which JSON converts into a string. By adding the + right before the variable, that tells JS to use it as a number for the comparison
if (+result.valid == 1) {
$(".outputDiv").show();
}
});

How to get values from url to js?

I am having the trouble to find a solution how I can get the values from the object which is requested from link from my web..
The thing is that I was created method in PHP to get the data from the database of the values of one object which I have to parse in my modal window so I don't have to refresh page to get details about my product.
Here is PHP code to get the details which perfectly works and my URL returning the $data object with values.
Controller.php
public function orderinfo($id){
$orderInfo = $this->adminsModel->getOrderInfo($id);
$data=['orderInfo'=>$orderInfo];
$this->view('admin/orderinfo',$data);
}
And the model function for php:
public function getOrderInfo($id){
$this->db->query("SELECT * FROM ORDERS WHERE id ='$id'");
$row = $this->db->single();
return $row;
}
And the thing is that I learned easily how to get id in javascript of my object which has the id in database.
here is code to get id and i understand it how it works:
HTML:
<a class="fa fa-file-audio-o edu-back-restart" href="#"
data-toggle="modal" data-target="#InformationproModalftblack"
id="<?php echo $activeOrders->id; ?>"
onclick="showDetails(this)">INFO</a>
NOTWORKING CODE:/mytry/
Javascript to get object id and to get object and its values (object and values is my problem):
<script>
function showDetails(a) {
$("#"+a.id).click(function () {
alert(a.id);
});
//NOT WORKING-How to get object from url?
$.ajax({
url: "localhost/test/orderinfo/280",
method: "GET",
datatype: Object,
success: function(response){
var customer =response;
console.log(response);
}
});
}
</script>
I don't know how to get whole object from that url with js or ajax and i don't know how to get object values as : id, name, street..
Thank you so much for you help...
sorry if i have some mistakes in explanation the problem.
When you are running the ajax call, the URL field should be referencing the PHP script that you are trying to run, e.g:
url: "localhost/test/orderinfo/Controller.php",
Next, make sure the PHP script is calling the orderinfo() function at some point. If you have this function in a larger script and don't have any logic for invoking it, I would recommend putting the function in a smaller PHP file whose sole purpose is to return the output of that query. For example:
//Whatever you need to import to make your query calls
//Whatever variables you need to initialize for your query calls
$temporary_id = "ABC123";
public function orderinfo($id){
$orderInfo = $this->adminsModel->getOrderInfo($id);
$data=['orderInfo'=>$orderInfo];
$this->view('admin/orderinfo',$data);
}
return orderinfo($temporary_id);
If you could provide any information about the object you are returning as well as the output of that console log, that would be extremely helpful.
Edit: Just noticed the comments, you could pass the id value in as data:
url: "localhost/test/orderinfo/Controller.php",
data: {'id':id_variable},
And then in the PHP, get the id value using $_SESSION['id'];.
Alternatively, you could pass it as a URL parameter:
url: "localhost/test/orderinfo/Controller.php?id=ABC123",
data: {'id':id_variable},
And get in the PHP using:
$id = $_GET['id'];
The value of the ID should be stored in that PHP variable as ABC123.
Hope this helps.
The best way for sending data from PHP to JS is encoding them as JSON object with json_encode.
public function orderinfo($id){
$orderInfo = $this->adminsModel->getOrderInfo($id);
$data=['orderInfo'=>$orderInfo];
$this->view('admin/orderinfo',json_encode($data));
}
so in your JS you can decode it with parseJSON like
<script>
function showDetails(a) {
$.ajax({
url: "/test/orderinfo/280",
method: "GET",
datatype: JSON,
success: function(response){
var obj = jQuery.parseJSON(response);
console.log(obj);
}
});
}
</script>
Note that you don't need to return whole $data in this object, and probably you even should not do it for performance and security reasons.
Instead, just prepare the object with only the data required for JS and send them as shown.

Failing to send to $_POST but $_SESSION says something else

I do not know what is happening with my code, when I run it, sometimes SESSION says there is an array is stored and sometimes it doesn't. I am using a debugger to check the session. When I use isset($_POST), the return value is always false. I am using ajax to pass an array to php.
<?php
session_start();
if(isset($_POST['jExam'])){
$decode = json_decode($_POST['jExam']);
$_SESSION['receive'] = $decode;
$product = $_SESSION['receive'];
}
else{
echo "Failed to hold<br>";
}
?>
Javascript:
$(document).ready(function(){
$(".class").click(function(event)){
event.preventDefault();
window.location.href = 'example.php';
var jExample = JSON.stringify(array);
$.ajax({
data:{'jExam':jExample},
type: 'POST',
dataType: 'json',
url: 'example.php'
});
});
EDIT:
Figured out why the arrays are stored into SESSION, once I click on the button that opens the other page, and then type in the page before in the url, the array is stored into the SESSION. Don't know why. Still can't figure out why ajax is not sending to post.
EDIT 2:
I created a file that handles the request called handle.php. So the php script on top is added into handle.php instead of the webpage. But I am getting a "Parse error: syntax error, unexpected 'if' (T_IF)". The code is still the same on top.
handle.php:
<?php
session_start();
if(isset($_POST['jExam'])){
$decode = json_decode($_POST['jExam']);
$_SESSION['receive'] = $decode;
$product = $_SESSION['receive'];
}
else{
echo "Failed to hold<br>";
}
?>
EDIT 3:
I am using the ajax to pass an array to php in order to store it into session, in order to use the array in another page. The problem is that the array is not passing into $_POST. What I am hoping is that the array can actually pass so I can use it on another page.
SOLVED:
All i did was add a form that has a hidden value. And the value actually post
<form id = "postform" action = "cart.php" method = "post">
<input type = "hidden" id="obj" name="obj" val="">
<input type = "submit" value = "Show Cart" id = "showcart">
</form>
In the Javascript:
$(document).ready(function(){
$("#showcart").click(function(){
var json = JSON.stringify(object)
$('#obj').val(json);
$('#obj').submit();
});
});
Thank you for everyone at has answered but hope this helps others.
If example.php is the php file which handles the request, you need to change your js code to
$(document).ready(function(){
$(".class").click(function(event)){
event.preventDefault();
var jExample = JSON.stringify(array);
$.ajax("example.php", {
data:{'jExam':jExample},
type: 'POST',
dataType: 'json'
});
});
And you should add the complete-Parameter if you want to handle the response.
Your mistake is, you are redirecting the page using window.location.href before you even send your request. Therefore, your request never gets sent and the PHP-File is called directly instead, not via AJAX, not with the nessecary data. Therefore, you are missing the data in the PHP-File.
You will want to try and make this setup a bit easier on yourself so here are a few things that can help you simplify this. You may or may not have some of these already done, so disregard anything you already do:
Use a config file with concrete defines that you include on 1st-level php files
Just pass one data field with json_encode()
Don't send json as a data type, it's not required, troubleshoot first, then if you need to, make it default as the send type
Use a success function so you can see the return easily
Make functions to separate tasks
/config.php
Add all important preferences and add this to each top-level page.
session_start();
define('URL_BASE','http://www.example.com');
define('URL_AJAX',URL_BASE.'/ajax/dispatch.php');
define('FUNCTIONS',__DIR__.'/functions');
Form:
Just make one data that will send a group of data keys/values.
<button class="cart" data-instructions='<?php echo json_encode(array('name'=>'Whatever','price'=>'17.00','action'=>'add_to_cart')); ?>'>Add to Cart</button>
Gives you:
<button class="cart" data-instructions='{"name":"Whatever","price":"17.00","action":"add_to_cart"}'>Add to Cart</button>
Ajax:
Just send a normal object
$(document).ready(function(){
// Doing it this way allows for easier access to dynamic
// clickable content
$(this).on('click','.cart',function(e)){
e.preventDefault();
// Get just the one data field with all the data
var data = $(this).data('instructions');
$.ajax({
data: data,
type: 'POST',
// Use our defined constant for consistency
// Writes: http://www.example.com/ajax/dispatch.php
url: '<?php echo URL_AJAX; ?>',
success: function(response) {
// Check the console to make sure it's what we expected
console.log(response);
// Parse the return
var dataResp = JSON.parse(response);
// If there is a fail, show error
if(!dataResp.success)
alert('Error:'+dataResp.message);
}
});
});
});
/functions/addProduct.php
Ideally you would want to use some sort of ID or sku for the key, not name
// You will want to pass a sku or id here as well
function addProduct($name,$price)
{
$_SESSION['cart'][$name]['name'] = $name;
$_SESSION['cart'][$name]['price'] = $price;
if(isset($_SESSION['cart'][$name]['qty']))
$_SESSION['cart'][$name]['qty'] += 1;
else
$_SESSION['cart'][$name]['qty'] = 1;
return $_SESSION['cart'][$name];
}
/ajax/dispatcher.php
The dispatcher is meant to call actions back only as an AJAX request. Because of the nature of the return mechanism, you can expand it out to return html, or run several commands in a row, or just one, or whatever.
# Add our config file so we have access to consistent prefs
# Remember that the config has session_start() in it, so no need to add that
require_once(realpath(__DIR__.'/../..').'/config.php');
# Set fail as default
$errors['message'] = 'Unknown error';
$errors['success'] = false;
# Since all this page does is receive ajax dispatches, action
# should always be required
if(!isset($_POST['action'])) {
$errors['message'] = 'Action is require. Invalid request.';
# Just stop
die(json_encode($errors));
}
# You can have a series of actions to dispatch here.
switch($_POST['action']) {
case('add_to_cart'):
# Include function and execute it
require_once(FUNCTIONS.'/addProduct.php');
# You can send back the data for confirmation or whatever...
$errors['data'] = addProduct($_POST['name'],$_POST['price']);
$errors['success'] = true;
$errors['message'] = 'Item added';
# Stop here unless you want more actions to run
die(json_encode($errors));
//You can add more instructions here as cases if you wanted to...
default:
die(json_encode($errors));
}

two event functionality in one php file

Hi I'm new to php and jquery. Pardon my php vocabulary.
I have two events in my js file.
1) onsubmit: submits the user entered text to result.php which queries database and displays result. (result.php?name=xyz)
2) onkeyup: makes an ajax call to the same result.php which queries a url and gets json data. (result.php?key=xyz)
My question is if I can check for isset($_GET['key']) in result.php, query url and return json and the rest of the php is not parsed.
Basically is there anything like return 0 as in case of C programming.
The question may seem silly, anyway I can have 2 different php files, but I want to know if it's possible.
Thanks in advance :)
<form action = "result.php" method = "get">
<input type = "text" id = "name" >
<input type = " submit">
</form>
<script>
$('#name').on('keyup',function (e){
input_val = $(this).val();
$.ajax({
url: "result.php?key=" + input_val,
success: function(data){
alert(data);
}
});
});
</script>
If I well understand, you want to know a way to use only one PHP script being able to process either Ajax and "normal" (returning whole page) tasks.
So if yes, this can be easily achieve, using the following schema:
//... some initialization, if needed
if (isset($_GET['key'])) {
// ... do the job for creating the expected Ajax response, say $ajax_response
echo $ajax_response;
exit;
// nothing else will happen in the current script execution
}
// otherwhise you can do all "normal" job here, as usual...
From your question if i have understood properly , you want to return boolean from PHP to Ajax , you can just echo "success" or "failure" based on if condition , and catch that in ajax response and process it in JS.
You can use exit; or die(); to terminate php script. http://php.net/manual/en/function.exit.php

Passing JavaScript ID Value to PHP for download

I am pretty new to PHP but I am learning fast.. I have been trying to use AJAX to Pass An ID to PHP.
With this ID I use SQL to get the path of a file from the database than use it to download the file.
However after some research this is not possible and I couldn't understand alternives... maybe there is a workaround?
These are my JavaScript function; I used JSON because I was passing an Array of IDs because I intend to use it in future for multiple downloads. I get the IDs from a table row click.
$('.btnDownload').click(function() {
$.ajax({
url: 'scripts/downloadFile.php',
type: "POST",
data: {id: JSON.stringify(fileID)}
});
});
And my PHP to attempt to download the file;
<?php
$data = $_POST['id'];
$data = json_decode("$data", true);
$countArray = count($data);
$counter = 0;
while($countArray > $counter){
$getID = $data[$counter];
// My sql connections and queries, jumped to the fetch part
$filePath = $fetch['filePath'];
header('Content-Type: application/zip');
header('Content-Disposition: attachment; filename='.basename($filePath));
readfile($filePath);
exit;
$counter++;
}
?>
How ever this script alone works when I give a static path and run it with my browser.
I would like some help on alternatives on achieving the results.
To solve the problem relating to the popup not popping up, try something like this instead of ajax:
$('.btnDownload').click(function(event) {
var url = 'scripts/downloadFile.php?id=' + JSON.stringify(fileID);
window.location.href = url;
event.preventDefault();
})
The user should be presented with a "save file" dialog and the browser will remain on the same url due to the disposition headers set by the php file.
The parameter that you're passing to downloadFile.php is called id, not ID (for example: data: {id: JSON.stringify(fileID)})
You need to update your PHP assignment to use the correct key as follows:
$data = $_POST['id'];
Mega.co.nz uses a similar approach. It requests the downloads per AJAX in order to allow a custom download progress bar. Once the download is finished, it is copied (technically it is downloaded from cache onto disk). You could do it somewhat like the following code. Of course, if you want to implement a custom progress bar, you'd need to fetch the unfinished response and update respectively.
$('.btnDownload').click(function(){
$.ajax({
url : 'scripts/downloadFile.php',
type : 'POST',
data : {id : JSON.stringify(fileID)}
})
.done(function( response ){
location.href = 'data:,' + btoa(response);
});
});
btoa converts the input into a Base64 encoded string which you can then use in conjunction with the Data URI Scheme to issue a download.

Categories