I have the following PHP code which encodes a PHP array:
Code
$js_array = json_encode($tmp);
Output
{
"frfgt55":["ABC","frfgt55","Aberdeen"],
"vfrgt6":["ABC","vfrgt6","Birmingham"],
"vbgtfdh67":["XYZ","vbgtfdh67","Leeds"],
"vfe5gb":["XYZ","vfe5gb","Bristol"],...
}
What I am struggling with is to then access this within a jQuery script. I know I should be making use of $.getJSON but I am struggling with its implementation as my Ajax knowledge is limited. I cannot see how this would access the variable that as been encoded.
Ajax code
$.getJSON('../_client/index.php', function(data) {
/* data will hold the php array as a javascript object */
});
Any advice, feedback and comments welcomed.
If I well understood your needs you can access data with:
$.getJSON('../_client/index.php', function(data) {
/* data will hold the php array as a javascript object */
console.info(data.frfgt55); //accessing the first item of the array
});
EDIT
In order to handle success and error code I suggest you to use the promise interface and so replace the current $.getJSON() code with:
$.getJSON('../_client/index.php')
.success(function(response) { console.info(response); alert("success"); })
.fail(function(jqXHR, status, error){ console.info(error); alert("error"); });
If I am correct then check this code it will help you
$.getJSON('../_client/index.php', function(data) {
for(var key in data) { // In comment check first loop data for each record.
// key = 'frfgt55'; // For 1st loop
var yourArrayRecord = data[key]; // For 1st loop <- ["ABC","frfgt55","Aberdeen"]
var perticularValue1 = yourArrayRecord[0]; // For 1st loop <- "ABC"
var perticularValue2 = yourArrayRecord[1]; // For 1st loop <- "frfgt55"
var perticularValue3 = yourArrayRecord[2]; // For 1st loop <- "Aberdeen"
}
});
Related
So basically what I'm doing is auto filling a textbox using AJAX to grab information from a PHP script that calls a C function.
This is what I've found in theory: (Assuming receiving only one value)
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response) {
$('#v1').val(response);
});
}, 5000);
});
Now, if this works, which I believe it will. If I receive an array of values, then the input inside of function cannot be response, correct? So what would I have to change it to make it an array?
Just to be clear, my PHP script is using echo to output its information. I'd rather output in such a more "standard" manner as in V1 = 120, V2 = 120, etc. but PHP is new to me and that I am currently researching. Thank you.
EDIT:
Just to make it clearer
Would something like this work?
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response[]) {
$('#v1').val(response[0]);
$('#v2').val(response[1]);
$('#v3').val(response[2]);
});
}, 5000);
});
Since you echo on PHP side, the response just can be a string.
But if that string if formed as a valid JSON, you will be able to use it like you wish.
So on PHP side, make sure the json format is valid:
$array = [120,340,800];
echo json_encode($array);
Then in JS... You received a string... You have to parse it to make it an array.
$(document).ready(function(){
window.setInterval(function(){
var ajaxurl = 'php/portserverclient.php',
$.post(ajaxurl, NULL, function (response[]) {
var responseArray = JSON.parse(response);
$('#v1').val(responseArray[0]);
$('#v2').val(responseArray[1]);
$('#v3').val(responseArray[2]);
});
}, 5000);
});
Per the OP update, you could try something like this to map each item of the array up to its corresponding text box you could do.
$.post(ajaxurl, NULL, function (response) {
for (var i = 0; i < response.length; i++) {
$("#v" + (i + 1)).val(response[i]);
}
});
This would map each index of the array returned from the JSON endpoint, to a corresponding text box.
If the JSON being returned from your endpoint is a valid JSON array, your response variable should already be an array!
Send your array as json:
echo json_encode(array($value1, $value2, $value3));
JS
$.post(ajaxurl, NULL, function (response) {
// selectors in same index order as response array
$('#v1, #v2, #v3').val(function(i){
return response[i];
});
},'json');
The easiest way (for me) to communicate between javascript and PHP is JSON.
So your PHP script have to generate an answer in this format.
PHP code
// At the top of your PHP script add this
// that will tell to your browser to read the response as JSON
header('Content-Type : application/json', true);
// Do your logic to generate a PHP array
echo json_encode($yourArray);
HTML code
<div class="someClass"></div>
Javascript code
var container = $('.someClass');
$.post(ajaxurl, NULL, function (response) {
console.log(response); // for debuging
for (let i = 0; i <= response.length; i++) {
let myItem = response[i];
container.append('<p>' + item + '</p>');
}
});
It's cleanest to generate dynamically the p elements because you don't know how many results your PHP file will return you.
I'm not sure of the javascript code, you maybe will received a json string that you have to transform to a Javascript Array
Before link you javascript to php script, try some call with postman (or others http client) to ensure that your 'webservice' is working as excepted
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
having a little trouble with my variable scope in jQuery, how come if I do the console.log outside the .each loop I get an empty array on $stockData ? (if i do it inside the .each, it works just fine, logs the array each time a value is added)
$(document).ready(function(){
// stock data will contain all the merged data from the database and yahoo queries
var $stockData = new Array();
// get data from yahoo and merge with dbData, add to stockData array
$.getJSON( "/get_portfolio.php", function(dbData) {
$.each( dbData, function(index) {
var stock = dbData[index]
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%3D%22"+stock.stock_symbol+"%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys",
crossDomain: true
}).success(function(data){
var quote = data.query.results.quote;
$.extend(quote, stock);
$stockData.push(quote);
}); // end success
});// end each
}); // end getJSON
console.log($stockData);
}); // end document.ready
when you call
$.getJSON( "/get_portfolio.php", function(dbData) { ... });
this part:
function(dbData) { ... }
doesn't run right away. JavaScript says: "oh you did a http request? I'll hold onto this function you gave me and run it after the request is done". And the rest of your code will keep on running, so this:
console.log($stockData);
will run first. So the actual order of execution here is:
you run getJSON
console.log runs
the HTTP request finishes and your callback runs
put the console.log inside the getJSON block, right after your .each loop:
$(document).ready(function(){
// stock data will contain all the merged data from the database and yahoo queries
var $stockData = new Array();
// get data from yahoo and merge with dbData, add to stockData array
$.getJSON( "/get_portfolio.php", function(dbData) {
var requestsDone = 0;
$.each( dbData, function(index) {
var stock = dbData[index]
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%3D%22"+stock.stock_symbol+"%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys",
crossDomain: true
}).success(function(data){
var quote = data.query.results.quote;
$.extend(quote, stock);
$stockData.push(quote);
if(++requestsDone == dbData.length) done();
}).error(function(){
if(++requestsDone == dbData.length) done();
});
});// end each
function done() {
console.log($stockData); // put this here
}
}); // end getJSON
}); // end document.ready
You need to wait getJSON function be completed, try this:
$(document).ready(function(){
// stock data will contain all the merged data from our database and yahoo queries
var $stockData = new Array();
// get data from yahoo and merge with dbData, add to stockData array
$.getJSON( "/get_portfolio.php", function(dbData) {
$.each( dbData, function(index) {
var stock = dbData[index]
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%3D%22"+stock.stock_symbol+"%22&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys",
crossDomain: true
}).success(function(data){
var quote = data.query.results.quote;
$.extend(quote, stock);
$stockData.push(quote);
}); // end success
});// end each
console.log($stockData);
}); // end getJSON
});
I will start by saying that I am learning how to program in jquery/javascript, and am running into an issue using JSON.parse(). I understand the format, and why people use it... but have not been able to get it to work in any of my code projects.
I have read in books/online on here in how to use it, but I think I read too much on it. I am now confused and second guessing what I know about it.
With that said, my jquery/javascript class I am taking is asking me to use it for an assignment, through AJAX using MAMP/localhost as the server.
The two codes below are for the section that I need to fill in the //TODO information. One is javascript (client-side), the other is php (server-side). I think that I've set the other //TODO information correctly, but I keep getting a token error for the JSON part.
I looked on here for a solution, but again, I think I've confused myself badly and need help. Appreciate any feedback, insight, or information.
-Javascript-
var calculateMpg = function () {
// These lines are commented out since the server will perform these checks
// if (!checkNumber("miles") || !checkNumber("gallons")) {
// return;
// }
var miles = $("#miles").val();
var gallons = $("#gallons").val();
console.log("ajax request issued.");
var result;
$.ajax({
url: "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons,
cache: false,
dataType: "text",
success: function(msg) {
console.log("ajax response received.");
// TODO: parse the JSON string returned from the server (see JSON.parse())
JSON.parse("result");
if (result.status === 'success') {
// TODO: get the mpg value returned from the server and display it to the user.
$("#mpg").val($_GET("result"));
console.log("JSON Working!");
}
else {
// TODO: get the name of the variable with the error. Hint: look at the 'fail' result from service.php
$_GET[fail(id)];
// TODO: report the error to the user using invalidNumber() function.
alert("{status: 'failure', variable: <variable name>}");
}
}
});
};
$(document).ready( function () {
$("#miles").blur(function () {
checkNumber("miles");
});
$("#gallons").blur(function() {
checkNumber("gallons");
});
$("#calculate").click(calculateMpg);
$("#miles").focus();
});
-PHP-
<?php
if ($_GET) {
if ($_GET['action'] == 'calculateMPG') {
$miles = htmlspecialchars($_GET['miles']);
$gallons = htmlspecialchars($_GET['gallons']);
// validate miles
if (strlen($miles) == 0) {
fail("miles");
}
$miles_chars = str_split($miles);
for ($i=0; $i< count($miles_chars); $i++) {
if ($miles_chars[$i] < "0" || $miles_chars[$i] > "9") {
//error_log("miles_chars check failed at: " + $i);
fail("miles");
}
}
// validate gallons
if (strlen($gallons) == 0) {
fail("gallons");
}
$gallons_chars = str_split($gallons);
for ($i=0; $i< count($gallons_chars); $i++) {
if ($gallons_chars[$i] < "0" || $gallons_chars[$i] > "9") {
fail("gallons");
}
}
// validate $miles and $gallons calling $fail along the way
$result = $miles/$gallons;
if ($result) {
success($result);
} else {
fail("mpg");
}
exit ;
}
}
function fail($variable) {
die(json_encode(array('status' => 'fail', 'variable' => $variable)));
}
function success($message) {
die(json_encode(array('status' => 'success', 'message' => $message)));
}
Edited Additional 1
I have made changes to the JSON information in regard to 'var result' (thanks to several of the responses here). I'm starting to understand JSON a bit better.
Another question I have (now) is how to isolate a part of the JSON message from the whole being transmitted?
A piece of the 'JSON.parse(msg)' returned DOES include the answer to the equation miles/gallons, but I don't know how to... extract it from the JSON.
The solution to the equation miles/gallons appears in the 'msg' output.
Thanks.
Edited Additional 2
This question has been solved! While perusing around stackoverflow for a solution to the question in my previous edited section, I found my answer here: JSON response parsing in Javascript to get key/value pair.
The answer is this: under the //TODO section asking for the mpg value, I put the following code - $("#mpg").val(result.message); - which says that in the JSON section of the variable result, take the part of the JSON marked 'message', the value being the equation solution.
Thank you to all who responded with their solutions to my problem. I appreciate the fast responses, the great suggestions, and the information in understanding JSON.
-ECP03
JSON.parse() requires that you send it a valid JSON string.
"result" is not a valid JSON string. In your success function you have defined a parameter msg - what does this contain? Try console.log(msg) at the beginning of your success function and look at the console output.
You have two options:
Option 1: -- Parse the string returned.
Change JSON.parse("result"); to:
var result = JSON.parse( msg );
Option 2: -- Request JSON instead of plain text - no need to parse
Use $.getJSON() which is shorthand for:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
Instead of parsing the JSON yourself, jQuery already provides you with a convenient function that will parse JSON:
var path = "service.php?action=calculateMPG&miles="+miles+"&gallons="+gallons;
$.getJSON(path, function (data) {
if (data.status == 'success') {
console.log('Success! Message:', data.message);
} else {
console.log('Failed :( Variable:', data.variable);
}
});
For your original code, what you would need to do is call JSON.parse(msg) in your success callback, which would return a JavaScript object with the values you sent from your PHP script. By specifying dataType: 'json' in the $.ajax call, jQuery does this for you. The $.getJSON method does this and some other things for you.
You need to use the result returned by the success function:
var result = JSON.parse(msg);
Then, you could do stuff like result.status.
When you put JSON.parse("result") you're saying "parse the string 'result'," which doesn't make any sense. However, if you say JSON.parse(msg) you're saying "Parse the variable that was returned from the ajax action," which makes sense.
JSON.parse() is used to convert your json data to object, then you can manipulate it easly.JSON.parse(msg); instead of JSON.parse("result").
For example:
var json = '{"value1": "img", "value2":"img2"}'
var obj = JSON.parse(json);
for ( k in obj ) {
console.log(obj[k])
}
This is totally wrong: JSON.parse("result");. .parse() expects a JSON string, e.g. the string that came back from you ajax request. You're not providing that string. you're providing the word result, which is NOT valid JSON.
JSON is essentially the right-hand side of an assignment expression.e.g.
var foo = 'bar';
^^^^^---this is json
var baz = 42;
^^---also json
var qux = ['a', 'b', 'c'];
^^^^^^^^^^^^^^^---even more json
var x = 1+2;
^^^---**NOT** json... it's an expression.
What you're doing is basically:
var x = parse;
^^^^^^---unknown/undefined variable: not JSON, it's an expression
For one part of our study-project we need to compare an array of Strings with a xml database. So my idea was to divide in 2 parts (because we need the compare-function twice). First I loop through the array with $.each and then I pass the value to another function that makes an ajax request to the xml, compares the value with each data in xml and if something found, it pushes it to an array which should be returned at the end.
In one function the jquery.each() is called:
function doSomething(){
liste = ["test1","test32","test22"];
$.each(liste, function(index, value){
var checkIt = compareDataBase(value);
if(checkIt.length>0) //do Something
});
}
and this is the function that compares the value and returns an array:
function compareDataBase(foo){
var lists = [];
$.ajax({
type:"GET",
url: "data/database/datenbank.xml",
dataType:"xml",
success: function(xml){
$(xml).find('product').each(function(index, element){
var current_product = $(this).text();
if(current_product.indexOf(foo)>-1)lists.push(current_product);
});
},
error: function(){
console.log("Fehler bei Produkte auslesen");
}
});
return lists;
}
But sadly that doesn't work. "checkIt" is always undefined because it doesnt wait for the ajax...
I tried to use the $.when function or give the compareDataBase()-function a callback but somehow that didnt work neither (I think because
I declared it wrong)
So maybe someone knows how to make this right?
Thanks for your help!
br sebi
You should use callbacks (or promises which are a variation on callbacks), the following solution example uses callbacks:
function compareDataBase(foo, callback){
var lists = [];
$.ajax({
type:"GET",
url: "data/database/datenbank.xml",
dataType:"xml",
success: function(xml){
$(xml).find('product').each(function(index, element){
var current_product = $(this).text();
if(current_product.indexOf(foo)>-1)lists.push(current_product);
});
// notify the callback with the result lists here
callback(lists);
},
error: function(){
console.log("Fehler bei Produkte auslesen");
}
});
}
function doSomething(liste, index){
if ( index < liste.length )
{
compareDataBase(liste[index], function(checkIt){
if(checkIt.length>0) //do Something
// process next list item using callbacks
doSomething(liste, index+1);
});
}
}
// start the process
doSomething(["test1","test32","test22"], 0);
Note that the example solution processes each list item only after the previous item has been processed (it kind of synchronises the callbacks, each callback will call the next one). One can remove this feature and process all asynchronously as follows:
// process all async
var liste = ["test1","test32","test22"];
for (var i=0; i<liste.length; i++) doSomething([liste[i]], 0);
I'm trying to Loop trough a variable, search for the ID's and then make an ajax call to get the Detailcontent of the different ID's in the Success function I try to loop trough the received content and get the emails out.
It is working but i get the first email twice in my $scope.subContactmail. I think there is a problem with the loop but i don't get it. Was trying to figure it out the whole night and unfortunately no idea came trough. The idea should be that if the first loop is finished it will start with the second loop. But at the moment the first loop goes trough the second as well.
Problaby your pros out there can help me with this problem.
Looking forward for your help!
Here is the specific part of my angular app file:
//find all contract relations id's from customer
$scope.contactrelation = function (input) {
$http.post('http://localhost/mamiexpress/mamiAPI/includes/php/searchContactsRelation.php', input).
success(function(data, status, headers, config) {
$scope.subContactDetails = [];
$scope.subContactmail = [];
$scope.subContactId = data;
console.log($scope.subContactId);
//GET ALL the subcontact ID's from the selected item
var i=0;
var subContactIdlenght = $scope.subContactId.length;
while (i < subContactIdlenght) {
console.log($scope.subContactId[i].contact_sub_id);
var number = $scope.subContactId[i].contact_sub_id;
i = i + 1;
//Send the ID to the API and get the user Details
$http.post('http://localhost/mamiexpress/mamiAPI/includes/php/searchContactswithID.php', number).
success(function(data, status, headers, config) {
$scope.subContactDetails.push(data); // store it in subContactDetails
console.log($scope.subContactDetails);
//HERE COULD BE THE PROBLEM!!
// I want this loop to start when the first loop is finished but i have to run this in this success function.
// At the moment i get the first email twice!
//Loop trough ContactDetails and get the emails.
if (i == subContactIdlenght){
var subContactDetailslength = $scope.subContactDetails.length;
for(var p=0; p < subContactDetailslength; p++) {
console.log($scope.subContactDetails[p].mail);
var number = $scope.subContactDetails[p].mail;
$scope.subContactmail.push(number);
};
};
}).
error(function(data, status, headers, config) {
$scope.errormessage = data;
console.log(data);
});
};//ENDWHILE
console.log(data);
}).
error(function(data, status, headers, config) {
$scope.errormessage = data;
console.log(data);
});
you have 2 solutions
Use the promise API (recommended):
something like that
var wheatherPromise = $http.get(...);
var timePromise = $http.get(...);
var combinedPromise = $q.all({
wheather: wheatherPromise,
time: timePromise
})
combinedPromise.then(function(responses) {
console.log('the wheather is ', responses.wheather.data);
console.log('the time is ', responses.time.data);
});
OR
simply do the following:
make ur $http request in a seperated function or (AJS service is
recommended).
call that function in a for loop based on ur list
declare a scope variable holds an empty array inside the function
push response objects in the array
avoid defining $http.get inside a for loop which cause unexpected behavior
I think what you need is promises/deferred API here.