Pass javascript class to php as json / alternative way - javascript

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.

Related

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.

Communicate php and js

I'm trying to create a js that send data to a php.
My first problem is that I get get back a html code if I insert this to the php.
This is only for understand the idea. So the js should send the "param" to the php and the php should return the result6 variable in this case, but I get a html code...
$('#f_field').change (function()
{
var param = 28;
$.post('check_mutet.php', param, function(result6) {
alert(result6);
});
});
while check_mutet.php contains this
<?php
$result6=666;
echo $result6;
Thank you for your help, as you can see I'm rather noob :)
param is a plain string (it starts out as a number, but will be converted to a string by the time it gets through to HTTP).
This will be available as STDIN in PHP, which you can read as described in answers to this question.
However, you should encode the data into a structured format that is easier to use.
The traditional format for this is application/x-www-form-urlencoded, which is the default format sent by HTML forms.
If you pass an object to jQuery post, it will encode the data in that format for you:
var param = 28;
var data = { example: param };
$.post('check_mutet.php', data, function(result6) {
Then you can read it through the POST superglobal in PHP:
<?php
$result = $_POST['example'];

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

Retrieving JS data in PHP

I am recording the information using the data() method
optionScope.data().stage = 'a';
where optionScope = $(this);
where I would like to store this value in my php code:
<?php
include("functions/db.php");
$format = "Online Course";
$stage = GETTING THIS DATA;
$topic = "Idea Generation";
$resources = "select * from resources where format LIKE '".$format."' and stage LIKE '%".$stage."%' ";
$run_query = mysqli_query($con, $resources);
while($row = mysqli_fetch_array($run_query)) {
$stage = $row['stage'];
echo "$stage <br>";
}
?>
Update:
How the data is being sent
optionScope.data().stage = 'b';
$.ajax({
url: "functions/contact.php",
type: "post",
data: {stage: optionScope.data().stage}
});
How the data is being retrieved
<?php
$stage = $_POST['stage'];
echo $stage;
?>
you can use the AJAX method. This is the only way you can transfer your JS data into PHP script.you will get the Jquery data in GET or POST variables.
jQuery AJAX has the various method you can choose as per your requirement.
http://api.jquery.com/category/ajax/
You can't directly transfer data between JS and PHP (unless you use string interpolation inside <script> tags which is a big no-no), since JS deals in the client-side and PHP on the server-side.
You need to make a request to the server and then manipulate the data there.
Take a look at AJAX requests.
For the easiest implementation of this, see JQuery's AJAX method.

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)

Categories