How to get values from url to js? - javascript

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.

Related

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

Decode multidimensional array and insert into mysql

I have trouble with getting a value from an xmlhttp request after sending it with ajax to a php file and insert it into an mysql database. I get from the yahoo finance api the output you can see in the html snippet. After that the value of this html element should be sended to the file insertvolume.php.
After successful sending I save the data into an variable named $jsonString and decode it. Then I try to insert a specific value from the array into my mysql database but it wont work. I think the problem is that the value is into any other arrays but I dont know how to write that. I only need that array named results Any hints?
the html:
<div id="output">{"query{"count":1,"created":"20160215T09:15:04Z","lang":"deDE","resu‌​lts":{"quote":{"symbol":"ZN","Ask":"2.05","LastTradeRealtimeWithTime":null,"Chang‌​ePercentRealime":null,"ChangeFromYearHigh":"-0.45","LastTradeWithTime":"4:00pm<b>‌​1.81</b>",astTradePriceOnly":"1.81", "Volume":"500","HighLimit":null,"LowLimit":null,"DaysRange":‌​"1.781"}}}}</div>
javascript:
var outputt = $('#output').text();
$.ajax({
type: "POST",
dataType: "json",
url: "insertvolume.php",
data: {myData: outputt},
success: function(data){
//alert('Items added');
}
});
some pice of code from insertvolume php:
$jsonString = $_POST['mydata'];
$jsonArray = json_decode($jsonString, true);
$jsonArray1 = $jsonArray['query']['results']['quote'];
if ($stmt = $mysqli->prepare('INSERT INTO volume ( stocksymbol, volume, time) VALUES ( ?, ?, now())')) {
/* bind parameters for markers */
$stmt->bind_param($jsonArray1['symbol'], $jsonArray1['volume']);
/* execute query */
$stmt->execute();
/* close statement */
$stmt->close();
}
After decoding the data you cannot retrive the json data directly. We should create object for that. Here i am giving you the reference link of how to access values of json.
Get value from JSON array in PHP
In javascript code it is written as
var outputt = $( "#output" ).val();
But the div is not having the value. The content is present inside the div. So change the line code to
var outputt = document.getElementById('output').textContent and try.
Now you are able to access the array in javascript. But we are unable to access the data of output code from your line.
In ajax call remove the line
contentType: "application/json; charset=utf-8",
and then execute. It will work

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.

Pass javascript class to php as json / alternative way

I am beginner in this stuff, but I am learning quite quick so I would appreciate any kind of help.
On example i have something object like
function shape(name, size)
{
this.name = name;
this.size = size;
// some functions
}
and I am creating an array of this (this is just example)
var shape1 = new shape("Square", 10);
var shape2 = new shape("Circle", 5);
var array_of_shapes = [shape1, shape2];
I need to send all shapes (name and size values in this case) into php in json or any other format that will allow me to send it to MySQL database
I don't know how jQuery / Ajax works, so I am trying to avoid this way if possible
I am not sure if title is correct when I am calling this a "class" actually
When you got shapes values in array.. now you can send all values on server using AJAX..
$.ajax({
url: 'http://www.domain.com/xyz',
dataType: 'json',
data : JSON.stringify(array_of_shapes),
success: function(data){
//server response in data variable
}
})
and on the server side you can receive json data as
<?php
$json_data = file_get_contents("php://input");
$json_array = json_decode($json_data, true);
echo '{msg: "data posted"}';
die;
?>
kinldy follow and check the link hopefully you will get to understand what you are trying to achieve.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_native_JSON
after value get returned as json you can save it to PHP variable.

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.

Categories