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","results":{"quote":{"symbol":"ZN","Ask":"2.05","LastTradeRealtimeWithTime":null,"ChangePercentRealime":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
Related
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.
I have created a script that adds items on click into an array.
$(document).ready(function()
{
var array_ids = [];
$('.add').click(function()
{
array_ids.push($(this).parent().siblings('.row_id').html().trim());
alert(array_ids);
});
});
Items are coming from mysql database so I am storing primary keys of items. keys are stored in array like this manner
1,2,3,4,5
Now I want to access this array in php so that I could store in database one by one.
I thought to doing some ajax and this is my code
$('.show').click(function(e)
{
//e.preventDefault();
$.ajax(
{
method: 'POST',
url: 'createsale.php',
data: {items: array_ids},
success: function()
{
alert('done');
}
});
});
I get the done alert but couldn't manage to get it stored in database. Can anyone tell how do I insert those items in mysql?
Send the value from Javascript by using Json {"key":value} or array [1,2,3]. While getting them to use them in PHP, you can use json_decode() to convert the Json or array from Javascript to PHP.
If you want your information from PHP to Javascript, Just use the funtion json_encode() that will send a json string.
Ref: json_encode, json_decode
your createsale.php file should has something like this below code to receive array Data & dont forget to escape your data using mysql_real_escape_string before doing any mysql query
<?php
if(isset($_POST["items"]) && $_POST["items"] !=""){
$arr = $_POST["items"];
//convert JS array to PHP array
$arr = json_decode($arr,true);
//then you have your PHP array => new array(1,2,3,...);
/* use for/forEach loop
for($i=0;$i<count($arr);$i++){
do the task
}
*/
}
?>
I am trying to UPLOAD multiple file using Post jQuery method but I get an error of undefined index when trying to view the array result. Tried to search the answers but still unable to do it. What is the correct way to do this. Below are the example of my codes,
HTML
<input type="file" name="others[]" multiple="multiple">
jQuery
$(document).ready(function(){
$("#submit").click(function(){
var array = [$("input[name='others']").val()],
others = {
"upload[]": array,
},
id = $("input[name='id']").val();
$.post('updated-file-others.php',
{
others : others,
id : id
}, function(data){
$("#result_post").html(data);
});
});
});
PHP
if(isset($_POST['id'])){
$id = $_POST['id'];
$others = array($_FILES['upload']['name']);
}
echo "<pre>"; print_r($others); echo "</pre>";
A couple of things
$("input[name='others']") doesnt match others[] in your HTML. Why dont you use an id and match it?
You might need to ensure that you have
enctype="multipart/form-data" inside your form.
whats the output of $("input[name='id']").val(); You have not provided any clue in your code.
Refer to php documentation on file upload - Uploading multiple files
Refer to this stackoverflow question - Multiple file upload in php
I would suggest formatting your desired array as a JSON string, and then using php_decode to convert it to an array.
$json = '["apple","orange","banana","strawberry"]';
$ar = json_decode($json);
echo $ar[0]; // apple
More info about JSON with PHP can be found here:
http://www.dyn-web.com/tutorials/php-js/json/decode.php
The file upload via ajax using $.post doesn't work this way, to achieve this, you must configure the ajax call as follows:
$.ajax({
type: 'POST',
url: your_url,
data: new FormData($('#form-id').get(0)),
processData: false, //set it to false to send a DOMDocument, or other non-processed data
contentType: false //pass false to tell jQuery to not set any content type header
}).done(function (data) {
alert('success');
})
This will send you the entire form to the server, and there you can process the files and other fields as you want.
You can read a little more about the processData and contentType configuration in the jQuery ajax documentation
Please let us know if this work for you,
Greetings
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.
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.