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

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));
}

Related

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

What goes into Responce in jQuery AJAX?

I'm sorry to add this broad question here, but I cannot seem to google it myself, I tried, and I really can't grasp the idea behind this, so here goes.
So I have a web-site that uses AJAX to login a user without full page reload. I kind of understand how AJAX works, and I'm sorry for my ignorance, but in my case:
$.ajax({
url: './',
type: 'POST',
data: {auth: auth, login: login, pass: pass}
success: function(res){
// Code that checks if **res** is a specific string
},
error: function(){
alert("Error!");
}
I understand that this sends POST request to the same page with 3 parameters. What I don't understand is what specifically does it get as a responce? In my case, in res is the $_SESSION element that contains the string message.
My question is: how do I know what gets in the responce? If I would just echo something in my function, would that get in the responce? Is there like a documentation about what can be passed to the arguments of success function?
I'm really confused about this.
The "res"... or commonly "data" in most examples, is simply the reply data from your page that your posting to..
So say in the case of PHP... you yes would simply echo anything back to it.
commonly people use JSON, so with php you would create a array with all the data you want to send back and then simply do
YOUR PAGE THAT SENDS THE POST
<script>
// JUST USING SUCCESS HERE ATM (Tthis does not show the full ajax command)
// Refer to original question for full javascript
success: function(res){
var myData = $.parseJSON(res);
if(myData.hasOwnProperty('name')){
alert(myData.name);
}
if(myData.hasOwnProperty('object1') && myData.object1.hasOwnProperty('items')){
alert(myData.object1.items.one);
}
},
</script>
YOUR PHP PAGE THAT RESPONDS
<?php
$myResponse = array();
$myResponse['name'] = "John Doe";
$myResponse['number'] = 123456789;
$myResponse['other'] = "and so on";
$myResponse['object1'] = array();
$myResponse['object2'] = array();
$myResponse['object1']['name'] = "john";
$myResponse['object1']['items'] = array();
$myResponse['object1']['items']['one'] = "one one 1";
$myResponse['object1']['items']['two'] = "two two 2";
$myResponse['object2']['name'] = "jane";
echo json_encode($myResponse);
?>
By using a "multidimensional" array in php, you can then treat each part of the array as a separate section/object
This might help: http://www.thecave.info/pass-a-php-array-to-javascript-as-json-using-ajax-and-json_encode/
Well, I think that what you "echo" is what you will retrieve in the "res",
try to see it in the console with:
console.log(res);
Or with an alert
alert(res);
try console.log(res); and check the browser console
ctrl + shift + k (firefox)
f12 (Chrome & IE)
For you task I would recommend using getJSON, instead of .ajax. It's just a shorthand for the same function, but really handy.
$.getJSON('/ajax-get-session/login/value/pass/value', function(json){
if (!json.error) { //check if there wasn't error on the server side
console.log(json.session);
} else {
console.log(json.error);
}
});
And on the server side.
$response = array();
try {
$response['session'] = $_SESSION;
}
catch (e) {
$response['error'] = e;
}
echo json_encode($response)

post json data to php and echo result

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.

Run PHP Query with Ajax return data in modal

This is my first fully attempting to use ajax. I have looked all over Google and cannot seem to find an answer. I am not even sure if what I am trying to do is possible.
I am trying to populate a modal window with data from a mysql table.
Using this javascript below, I an able to print the DATA-ID in a modal window with an HREF click:
<script type="text/javascript">
$(document).on("click", ".open-RestrictModal", function () {
var myId = $(this).data('id');
$(".modal-body #Id").val( myId );
});
</script>
I would like to add to this code is the ability to run a PHP/MySQL query, get the results, and print it in the modal window.
I think I have to use AJAX, but I am not sure. How can I add to the existing code the ability to send the javascript variable to an AJAX page and return the results in a modal window?
Please help.
It doesn't appear that you are even using ajax here, assuming you are using the jQuery library you can build a call like this:
function some_ajax_call(your_param) {
$.ajax({
type: "POST", // We want to use POST when we request our PHP file
url : "some/url/to/your/file.php",
data : { query : your_param }, // passing an array to the PHP file with the param, value you passed, this could just be a single value i.e. data: your_param
cache: false, // disable the cache optional
// Success callback if the PHP executed
success: function(data) {
// do somethig - i.e. update your modal with the returned data object
$('.modal-body #id').val(data);
}
});
}
You can then write you file.php file to handle the query
<?php
// Capture the variable we passed in via AJAX
$param = $_POST['query'];
// Build a query
$query = "SELECT * FROM some_table WHERE val ='" . $param . "'";
// I assume you know how to run a query, this would be fetching an assoc array
$results = $DB->run__query($query);
// Check we have some results, then echo back to the AJAX call
if(sizeof($results) > 0) {
echo $results;
}
echoing at the $results array at the end of our PHP script if we have any results will populate the data array in our success callback with the returned rows, you can then perform any DOM manipulation in the success callback to update your modal, hope this helps.

AJAX Transferring page PHP

This is the structure I have:
A router.php, based on $_POST['c'] generates the controller file name, includes the file and calls the $_POST['a'] method of it.
I have a gridview. The only way to open a details page when the user clicks the row is to use AJAX, since only javascript can handle the clicking. I don't want to have a button column - I want a row click.
So I have my javascript doing this:
$( document ).ready(function() {
// Handler for .ready() called.
$("tr" ).click(function() {
var id = $('td[name=id]').attr('id');
var c = $('input[name=c]').attr('value');
var a = $('input[name=a]').attr('value');
$.post("Router.php", { id: id, c: c, a: a }, function(data){
window.location.href = "Router.php";
});
});
});
I have my Router.Php:
if (array_key_exists('c', $_POST)) {
$controller = $_POST['c'];
};
if (array_key_exists('a', $_POST)) {
$action = $_POST['a'];
};
echo $controller;
echo $action;
I can never get the post values. I think I'm thinking about AJAX wrong - what AJAX is suppose to do is to just get a response and render it somewhere on the browser. What I'm using it for is to pass POST data and call a method within a PHP file. The reason for this is because I don't want to pass the id in the url.
Any way to fix this?
The following part of your code issues 2 requests to the server. A POST and then a GET.
$.post("Router.php", { id: id, c: c, a: a }, function(data){
window.location.href = "Router.php";
});
Most probably you are getting what you want on the first request, but the result that you see on your screen is the outcome of the second request, which is just a GET without params.
The result of the post is being written using echo $controller; and echo $action; and these are returned in (data) but you don't do anything with that. You just redirect the client to Router.php.

Categories