returning an ajax response - javascript

I have researched this for several days now and I just can't get anything to work. I am using php to query a MySQL database. I'm getting a response via ajax but I need to be able to use the response. For example I need to take the response multiplied by 5. I can show the response in my HTML but I can't do anything to make my script read it as a number. I've tried parseInt Number() and so on. The code as I have it returns the correct number but I can't use it. Here is my code.
$('#checkStockButton').click(function(){
$.ajax({
type: "GET",
url: "mainApple.php",
data: "",
async: false,
success: function(result) {
stockPriceApple = result;
parseInt(stockPriceApple,10)
$('#responsecontainerApple').html(stockPriceApple);
}
});
return false;
});

parseInt returns a number, so you need to do this:
stockPriceApple = parseInt(result,10);
$('#responsecontainerApple').html(stockPriceApple);
As the content of your success function

if you want to read data into your success function, you first have to do: json_encode($result) at server-side (PHP) and then decode it in your java-script success function like: var str = JSON.parse(result); alert str[0]
for example: server side php
function sendjson(){
$data=array(0=>'zero', 1=>'one');
echo json_encode($data);
}
and client side, in your ajax success function:
success: function(html){
var str = JSON.parse(html);
alert(str[0]);
}
or using associative array:
serverside php:
function sendjson(){
$data=array('firstvalueofarray'=>'zero', 'secondvalueofarray'=>'one');
echo json_encode($data);
}
and clientside:
success: function(html){
var str = JSON.parse(html);
alert(str.firstvalueofarray);
}
in both cases the alert box will display 'zero'

Related

Print JSON string from URL

I'm using ajax to parse JSON data from a URL. I need to capture the parsed array into a variable. How would I go about this? Thanks
function rvOffices() {
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET',
data: JSON.stringify(data),
dataType: 'text',
success: function( data) {
// get string
}
});
}
rvOffices();
var rvOfficesString = // resultant string
You can use JSON.parse(data) to convert the desired output to JSON, and then access the objects and array indexes from within that with .object and [array_index] respectively:
function rvOffices() {
$.ajax({
url: 'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type: 'GET',
dataType: 'text',
success: function(data) {
var json_result = JSON.parse(data);
//console.log(json_result); // The whole JSON
console.log(json_result.offices[0].name);
}
});
}
rvOffices();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You also don't need to pass any data, as you're performing a GET request.
Hope this helps! :)
So I guess you are not sure about the ajax call, so lets break it..
Ajax call is a simply method to make a request to remote resource (Get/post/put...) the type of request (GET/POST) depends upon your need.
so if you have an endpoint that return simply data as in your case a simple get/post request is sufficient.
You can send addition data with request to get the data from endpoint (say id of resource (say person) whose other fields you want to get like name, age, address).
here is link for ajax request in jQuery
here is jQuery parse json parse json in jQuery
So for example:
// let's say when you call this function it will make post request to fixed end point and return data else null
function rvOffices() {
var res = null; // let be default null
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET', // type of request method
dataType: 'text', // type of data you want to send if any.
success: function( data) {
res = $.parseJSON(data); // will do the parsing of data returned if ajax succeeds (assuming your endpoint will return JSON data.)
}
});
return res;
}
// lets call the function
var rvOfficesString = rvOffices();
// print the value returned
console.log(rvOfficesString);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can try something like: -
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/offices',
type:'GET',
dataType: 'text',
success: function(response) {
// get string
window.temp = JSON.parse(response);
}
});

how do i send javascript variables to PHP and return the results

I have a form with inputs (each with ID param,param1,param3 respectively) and an external php file with a function called getform() that takes three parameters from the form (param, param1, param3 respectively).
A text feild with id results to display the response from php file.
I have placed onclick function on param3.
I need whenever a user types something in param3 it should be sent to php file and the results displayed in the text filed of id results.
here is my code
<script>
function post(){
var param = $('#param').val();
var param2 = $('#param2').val();
var param3 = $('#param3').val();
$.post('curencyconvert.php', {
postparam: param,
postparam2: param2,
postparam3:param3
}, function(data){
$('#results').html(data);
});
}
</script>
my php function in the php file
function Conv($param,$param2,$param3){
//my code here
return $output;
}
if(isset($_POST)){
//Calling the defined function here
Conv($_POST['postparam'], $_POST['postparam2'], $_POST['postparam3']);
}
Add these line below your function code.. and better echo the output in your function instead of returning it.
jQuery(document).ready(function($) {
$('#param3').change(function() {
// put here the code //
} );
})
What errors you get in Console(firbug)?
As stated by other answers $_POST should be used.
What your php code returns if it returns an array or returns an object It can not be put into the Input. Return value must be a
string
PHP code must be :
function Conv($param,$param2,$param3){
//my code here
// take particular field of the DB results or resultset that you want to show in the input.
return $output['name'];
}
I know answer is incomplete because your question is incomplete.
Please let me know errors from the console so that i can help you further
echo instead of return.
if(isset($_POST)){
echo Conv($_POST['postparam'], $_POST['postparam2'], $_POST['postparam3']);
}
Do something like this, it is more clean:
Conv($param, $param2, $param3){
// your code here
return $output;
}
As for the javascript part, jquery ajax is your friend
function post(){
var param = $('#param').val();
var param2 = $('#param2').val();
var param3 = $('#param3').val();
$.ajax({
url: '/path/to/file',
type: 'POST',
data : { postparam: param, postparam2: param2, postparam3: param3 },
}).done(function(data) {
$('#results').html(data);
});
}

I mess up JSON object, arrays and strings

So i´m, trying send data from php to js.
PHP
$balkTypes[] = $stmt->fetchAll();
echo json_encode($balkTypes);
JS
balkTypesData = {}; //Outside Ajaxcall
success: function(result){
balkTypesData = result;
Console.log(balkTypesData);
}
Console
[[{"id":"3","typ":"Bas 200*600","hojd":"200","bredd":"600","rec":"","viktM":"135"},{"id":"2","typ":"Bas 240*600","hojd":"240","bredd":"600","rec":"","viktM":"160"},{"id":"5","typ":"Isol\u00e4tt 240*600","hojd":"240","bredd":"600","rec":"","viktM":"105"},{"id":"4","typ":"Kontur 240*600","hojd":"240","bredd":"600","rec":"","viktM":"105"},{"id":"6","typ":"Passbit","hojd":"0","bredd":"0","rec":"","viktM":"0"}]]
Now, i´d like to search my Json object?!
I´d like to find "viktM" for "typ:Bas 200*600"
//Get balkType weight/m
var searchField = "typ";
var searchVal = "Bas 200*600";
for (var i=0 ; i < balkTypesData.length ; i++){
if (balkTypesData[i][searchField] == searchVal) {
weigth = balkTypesData[i]['viktM'];
console.log(weigth);
}
}
First of all, it seams that i cannot use .lengton "balkTypsData". it gives me 410 hits. Must be all characters?
Second, i cannot find how to access part of my object.
If i use: console.log(balkTypesData[i][searchField]);
I get: "Undefined"
I have also tried to remove the "[i].
So what am i missing?
Be gentle i´m still learning.
Take a look at $.parseJSON() (jQuery) or JSON.parse() (vanilla):
With jQuery
success: function(result){
balkTypesData = $.parseJSON(result);
console.log(balkTypesData);
console.log(balkTypesData[i][searchField]);
}
Without jQuery
success: function(result){
balkTypesData = JSON.parse(result);
console.log(balkTypesData);
console.log(balkTypesData[i][searchField]);
}
When you receive the data from your AJAX request it's not JSON, just a string.
The length result that you're getting is the length of the string, not the amount of elements within the array.
Furthermore you're setting $balkTypes[] which means that you're trying to add 1 entry in the array of $balkTypes however $stmt->fetchAll(); also returns an array so you now have a nested array which is not needed.
In your PHP file change
$balkTypes[] = $stmt->fetchAll()
to
$balkTypes = $stmt->fetchAll()
this will make sure that when you fetch your data it will be an array containing all objects instead of an array containing the array of objects.
Then in your JS, instead of trying to directly read from the string, use JSON.parse() to convert the json string into a collection of JS objects/integers/arrays/strings/booleans
e.g.
success: function(result) {
balkTypesData = JSON.parse(result);
console.log(balkTypesData);
}
EDIT
As pointed out by Armen you could also set the dataType: 'json' in the AJAX request, when the AJAX request returns it will automatically do the JSON.parse() so you can just directly console.log(result); to see the output.
Within the console.log you should now see the nested structure instead of just the string.
From here on your loop which checks the values seems correct and I would not change it unless it tells you that something is wrong.
Docs: JSON.parse();
Set in your jQuery $.ajax request additional attribute dataType: 'json'
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: { params },
success: function( response )
{
// Your data will be already json no need to parse it
console.log(response);
}
});
You are encoding a JSON on the PHP side. You are not decoding it on the JS side.
You should look at JSON.parse()

Display data from an array

In index.php page i have a script that fetches data from demo.php and displays the result in a div.
<div class="leftbox">
<?php
echo "<div id='proddisplay'>";
echo "</div>";
?>
</div>
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'demo.php',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
$('#proddisplay').html(returndata);
console.log(returndata);
},
error: function() {
console.error('Failed to process ajax !');
}
});
};
in demo.php script i get the result from
print_r($result);
the result that i get in the div is
Array ( [0] => 1st value [1] => 2nd value [2] => 3rd value [3] => 4th value )
I wish to get individial data from this array so that i can use each data seperately and wherever i want in the index.php page, but i am not able to do so. can anyone tell how can i fetch individual values from array for index page
P.S:
i have an option to display the format in demo page in the form of result[0] and so on for every index value and call it as it is in the index page but that bounds me with the css. I wish to use any css in index page and just call the values in index page.
I tried using result[0] in index page but it displayed no result i tried assigning the values of an array to a variable and then call these variables to index page but that also didn't displayed any result
The simplest way to loop through values in an array is to use foreach.
foreach
foreach($result as $value){
print($value);
}
http://php.net/manual/en/control-structures.foreach.php
http://www.w3schools.com/php/php_looping_for.asp
Either access each value individually - for example $result[0]. Or if you want to loop over the entire array you can use foreach
Example:
foreach($result as $val){
//do something with $val
}
PHP Arrays
Simply assign values of indexes to variables like below:
$first_value = $result[0];
$second_value = $result[1];
$third_value = $result[2];
$fourth_value = $result[3];
and so on in same sequence.
As you're using Ajax to get the data, you need to pass the array back as a JSON string. Add another parameter, dataType: 'JSON' to your Ajax call, this tells jQuery you're expecting a JSON string as a response and it'll automatically convert the JSON into an array for you when passing the result to the success function.
Then in your data.php value you need to run echo json_encode($result); to pass result back to the Ajax success function as a JSON string. jQuery converts it back from a JSON string to an array for us (that's why we add the dataType). Then in your Ajax success function you console.log(resultdata.0) you'll get value1, and console.log(resultdata.1) will give you value2.
convert your array to json
echo json_encode($result);
in your script
var onSubmit = function(e) {
var txtbox = $('#txt').val();
var hiddenTxt = $('#hidden').val();
$.ajax({
type: 'post',
url: 'test2.php',
dataType: 'json',
data: {
txt: txtbox,
hidden: hiddenTxt
},
cache: false,
success: function(returndata) {
$('#first').html(returndata[0]);
$('#second').html(returndata[1]);
$('#third').html(returndata[2]);
$('#fourth').html(returndata[3]);
console.log(returndata[0]);
},
error: function() {
console.error('Failed to process ajax !');
}
});
};
first,second,third,fourth will be the id of the div or the area where you wish to display the result

jquery trouble with getJSON call

Got some basic problem again.
I need to modify a function that previously returned a in code written object.
Im now trying to get the object from json through $.getJSON
function getEventData() {
var result = '';
$.getJSON("ajax.php?cmd=getbydate&fromdate=&todate=", function(data) {
result = data;
});
return result;
}
Problem is that result isn't set in the callback function for obvious reasons.
Do you guys have a solution for this?
Edit:
Ok i got an answer that was removed.
I just had to change it abit..
This is the answer that works:
function getEventData() {
var result = '';
url = "ajax.php?cmd=getbydate&fromdate=&todate=";
$.ajax({
url: url,
async: false,
dataType: 'json',
success: function(data) {
result = data;
}
});
return result;
}
You should program your application in an asynchronous way, which means, that you should use callback functions for you application flow, too, or continue in the getJson callback function. You can also make the request synchronously which should then be able to return the value (or at least assign it and block the function till the callback is completed), but this is not recommended at all:
function getEventData() {
var result = '';
result = $.ajax({
url: "ajax.php?cmd=getbydate&fromdate=&todate=",
async: false,
dataType: "json",
data: data,
success: function(data) {
return data;
}
});
return result;
}
Are you sure that the server returns valid json? It will be better to validate it using a tool like jsonlint. Also make sure that application/json is used as content type for the response.

Categories

Resources