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()
Related
Im trying to send an array, populated using javascript on client-side, to a php file in the backend.
MAIN.JS
var list = iterateItems();
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", list)
.done(function(list){});
});
function _ajax(url,data) {
var ajax = $.ajax({
type : "POST",
datatype : "string",
url : url,
data : data
})
return ajax;
}
function iterateItems() {
// array is an array populated in this function, returned to be sent to ticket.php
return JSON.stringify( array );
};
TICKET.PHP
<?php
var_dump(json_decode($_POST['list']));
?>
And executing this, I'm getting this result:
Notice: Undefined index: list in D:\127.0.0.1/prog1/final/class/ticket.php on line 2
NULL
Im not understanding why im getting an undefined index.
I tried googling this, but most responses seem to point in the direction of using some kind of HTTPS method, which is what I'm trying to achieve via POST.
Any help will be greatly appreciated. Thank you.
The 'list' undefined issue might be due to the structure of the JSON array you pass.
Try the below code and check if it works. If not let's check further :)
var list = {'list': iterateItems()};
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", list)
.done(function(list){});
});
function _ajax(url,data) {
var ajax = $.ajax({
type : "POST",
datatype : "json",
url : url,
data : data
})
return ajax;
}
function iterateItems() {
// array is an array populated in this function, returned to be sent to ticket.php
return JSON.stringify( array );
};
Your PHP Code:
<?php
var_dump(json_decode($_POST['list']));
PHP can't parse JSON parameters automatically. $_POST will only be filled in from a URL-encoded string or a FormData object.
$.ajax will URL-encode an array automatically for you.
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", array)
.done(function(list) {});
function _ajax(url, data) {
var ajax = $.ajax({
type: "POST",
dataType: "string",
url: url,
data: {list: data}
})
return ajax;
}
In PHP you then don't need to call json_decode(). The value of $_POST['list'] will be the array.
I am retrieving list from ajax, when it become success, I wants to add those list values to DropDownList Items, So I want to iterate the data until last value and then add it to DropDownList
Here is my code What i tried
$.ajax({
type: "POST",
contentType: "application/json;charset=utf-8",
url: "GPCreateCheque.aspx/getOpenRequestNo",
dataType: "json",
success: function (data) {
alert(data.length);
for (var i = 0; i<data.length; i++) {
$(".tbDDLReqNo").append(new Option(data.d[i], data.d[i]));
}
},
error: function (result) {
alert("Error");
}
})
In alert box it is showing undefined
UPDATE
I return the list<string> from [webmethod]
use data.d.length
alert(data.d.length);
for (var i = 0; i<data.d.length; i++) {
$(".tbDDLReqNo").append(new Option(data.d[i], data.d[i]));
}
You need to do data = JSON.parse(data); before treating your data like an array. It's just a string up to that point.
Update: if your data is not the array itself, but instead an object that contains an array named d, you need to work with that. It depends on your data structure.
Check the response from network tab in Chrome Developer Console or similar tool. May be response code is 200 but response data is missing.
On the other hand you want to itarete data in for loop but you try to append data.d[i]. If you want to append data.d[i] you have to itarete data.d in for loop.
First time question, hoping for some advice:
Code on webpage:
<form id="inbound" action="javascript:validateinbound();">
<input type="submit" value="Go!" id="inbound">
<script>
function validateinbound() {
$('#inbound:input').each(function () {
var iv = $(this).val();
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
var response = JSON.stringify(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+response);
}
});
});
});
};
</script>
</form>
This returns a string that I would like to work with that looks like this:
Answer:
[{"id":"1","answer":"Pull logging","question_id":"5","feature_id":"1","answer_id":"9"}]
Ideally what I would like to do is only select the 'value' to the maxmail_answer 'key' (hopefully those are the right terms?) to the webpage instead. Right now there is only one value but there will be more in the future so something that could parse this string for a specific key and only output those values.
Visually I would see:
Answer: Pull logging ( and then another Answer: for each value I pull out )
First time ever using this site and these languages so total noob and would appreciate some guidance.
Thanks!
You do not to stringify the JSON response, you can get the value of the key you want using the object notation . as follows:
function validateinbound() {
$('#inbound:input').each(function () {
var iv = $(this).val();
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
//var response = JSON.stringify(data); // no need for this line
$('#response').delay(3600).fadeIn(600);
// catch the answer here
// your result returns within an array so you need to catch the first index
$('#response').append("<p>Answer: </p>"+response[0].answer);
}
});
});
});
};
Besides, ids are unique, you can only access a single element via id selector #, you do not need a .each
What you are receiving from your server is an array of objects in the JSON format. The sample that you have put has the length of "1" and therefore, if want to reach the "id" of the first array, it would be like this:
// var response = JSON.stringify(data); (// don't stringify it!
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+data[0].id);
You need here a loop to go through your array of results and display each result
success: function(data) {
var response = JSON.stringify(data);
$('#response').delay(3600).fadeIn(600);
$.each(response,function(index,value){//the each loop
$('#response').append("<p>Answer: </p>"+value.answer);//get the answer using . notation
});
}
Json.stringify() returns your javascript object as json data, but i think in your case your response is a json data which you need to manipulate. Json.parse() does this for you and you can access your answer as a property of the javascript object.
success: function(data) {
var response = JSON.parse(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+response[0].answer);
}
if your json data has multiple result and you need to work through all of them use a loop.
$.each(response,function(index, object){
var response = JSON.parse(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+object.answer);
});
First of all. Thank you to everyone who commented on this to help me get started in the right direction. I was able to get what I needed working!! Here is the solution:
<form id="inbound" action="javascript:validateinbound();">
<input type="submit" value="Go!" id="inbound">
<script>
function validateinbound() {
$('#controlpanel:input').each(function () {
var iv = $(this).val();
$('#response').html("");
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
var newdata = JSON.stringify(data);
var response = JSON.parse(newdata);
$('#response').delay(3600).fadeIn(600);
$.each(response, function(array, object) {
$('#response').append("<p>Answer: </p>"+object.answer);
});
}
});
});
});
};
</script>
</form>
I needed to parse the data correctly. So I used JSON.stringify to get the data into a string that JSON.parse could use to manipulate the data. But function(index,object) wouldn't work because my output was not an index, but an array. So when changing to function(array,object) this allowed me to get my data just the way that I needed.
Again thanks to everyone for their help!
I am constructing a Javascript object. I am using the id of user who is logged in (from a session variable) and storing it as an attribute with AJAX.
I wanted to post the resulting object as JSON via AJAX to a PHP file which then inserts the document into a MongoDB database:
var numpages=$('.page').length;
var book=new Object();
$.ajax({
type: 'json',
url: '../scripts/getUser.php',
method: 'GET',
success: function(data){
var user=JSON.parse(data);
book.user=data.username;
}
});
book.title=title;
book.pages=new Array();
var page;
var link;
for (var i=0;i<numpages;i++){
var numlinks=$('#p'+i+' .link').length;
page=new Object();
page.text=$('#p'+i+' .textarea').text();
page.links=new Array();
for (var j=0;j<numlinks;j++){
link=new Object();
link.text=$('#p'+i+'l'+j+' .linktext').text();
link.locale=$('#p'+i+'l'+j+' .locale').text();
page.links.push(link);
}
book.pages.push(page);
}
$.ajax({
data: JSON.stringify(book),
url: '../scripts/addstory.php',
method: 'POST',
success: function(msg) {
//var story=JSON.parse(msg);
console.log(msg);
//alert(msg);
}
});
}
Here is the PHP:
<?php
$dbhost = 'localhost';
$dbname = 'story';
$m = new MongoClient("mongodb://$dbhost");
$db = $m->$dbname;
$collection = $db->stories;
$story=$_POST['json'];
if (isset($story)){
$collection->save($story);
}
?>
The document is being inserted into the database but I get this:
Notice: Undefined index: json
You have two problem, first being that ajax is async unless you specify the async flag to false which you probably don't want to do so:
book.owner=data.username;
Is likely to actually be empty when you come to JSON encode in the second ajax call.
To solve this you can use JQuery promises like so:
$.get().done(function(data){
/// extra processing
}).then(function(){ $.get() // etc });
This will ensure that one Ajax calls runs after the other.
As for the missing index you don't actually need to stringify your data at all instead you can just do:
$.get('some_url', {book: book})
And JQuery will actually serialize it for you ready for PHP.
This
JSON.stringify(book),
creates an object something like:
{"title":"East of Eden","author":"John Steinbeck"}
better completely remove the JSON.stringify() bit and just pass the book variable
And it in the ajax call it should be type: "POST", not method: "POST"
So in your php script you can do
$_POST['title'];
$_POST['author'];
Hope that helps
If you want to work exclusively with JSON, you should set your content-type header to application/json and then read that content from PHP raw input:
The javascript:
$.ajax({
data: JSON.stringify(book),
url: '../scripts/addstory.php',
method: 'POST',
contentType: 'application/json',
success: function(msg) {
alert(msg);
}
});
The PHP:
$story = file_get_contents('php://input');
So really you just need to add one line of code and change another.
The reason $_POST['json'] was not being populated is that nowhere did you define a query string (or let jQuery define for you) that has a key json.
You could have, for example done something like this:
data: {'json': JSON.stringify(book)}
And that would have populated $POST['json'], but again if all you are looking to do is pass around a JSON string and directly insert it into Mongo, there is no reason to use form-encoding for this at all, just work with raw POST data.
Note also the problem mentioned by #Sammaye about needing to properly work with event delegation.
I have a php file somejson.php that echos a json encoded array
{"jsonone":"first json","jsontwo":"second json"}
I'm trying to access the response with jquery ajax to use this data outside the score of the ajax call. It keeps giving me all kinds of object(Object) or undefined errors.
I'm guessing it's something as easy as wrong syntax, but it's bugging me I thought I'd ask
var mydata = {};
$.ajax({
url: 'somejson.php',
async: false,
dataType: 'json',
success: function (json) {
mydata = json;
mydata[jsonone] = json.jsonone;
mydata[jsontwo] = json.jsontwo;
alert(json[jsonone] . json[jsontwo]);
alert(mydata[jsontwo] . mydata[jsontwo]);
}
});
//later will do some stuff with mydata jsonone and jsontwo
What are all the things I'm doing wrong here?
Yep, simple syntax errors :-)
You need to put quotes around your hash keys and use the '+' operator to concatenate strings:
var mydata = {};
$.ajax({
url: 'somejson.php',
async: false,
dataType: 'json',
success: function (json) {
mydata = json;
mydata['jsonone'] = json.jsonone;
mydata['jsontwo'] = json.jsontwo;
alert(json['jsonone'] + json['jsontwo']);
alert(mydata['jsontwo'] + mydata['jsontwo']);
}
});
I think your problem comes from the dots in your alert statements.
String concatenation in javascript is done using + not . like in php.
alert(json['jsonone'] + json['jsontwo']);
alert(mydata['jsontwo'] + mydata['jsontwo']);
Also, the array indexes should be strings (enclose in single or double quotes).