I have an AJAX call that returns the data from PHP
echo json_encode( $json_response);
and the result is as follows
[{"name":"Sprouts.......}]
I then loop through it with JQUERY
$.each($.parseJSON(data), function(i, obj) {
var name = (obj.name);
var address = (obj.address);
});
This works perfectly fine, but I am trying to add a name (child) to it so that I can have other children. I used the following
json_encode(array('storedata' => $json_response))
to add the name storedata which returns
{"storedata":[{"name":"Sprouts....
I have tried looping through with
$.each($.parseJSON(data.storedata), function(i, obj) {
var name = (obj.name);
var address = (obj.address);
});
but something is wrong with the syntax because the data.storedata is undefined.
What is the correct syntax and/or correct way to do this. Thank you for any and all help.
The problem is that you are trying to access storedata before parsing the string into an object, so you need to replace $.parseJSON(data.storedata) with $.parseJSON(data).storedata:
$.each($.parseJSON(data).storedata, function(i, obj) {
var name = (obj.name);
var address = (obj.address);
});
Related
So i am trying to learn Ajax with jQuery, to retrieve some information. At the moment, I have problem to get the information. My code is very simple at the moment, just because I want to learn how it works. This is my HTML code.
<h2>Hello world</h2>
<p id="response"></p>
My jQuery code:
$(function(){
$('h2').on('click', function() {
$.ajax({
url: "ajax.php",
type: "get",
datatype: "json",
success: function(data){
$.each(data, function(i, key){
$("#response").html(key['name'])
});
},
error: function(data){
console.log("tjohejsan");
}
})
});
});
So when I click on h2 it should retrieve data. What I want is to make a call from my database to get information about the users.
So my php code looks like this:
$sql = "SELECT * FROM moment2";
$result = mysqli_query($db,$sql) or die("Fel vid SQL-fråga");
$array = array();
while($row = $result->fetch_assoc())
{
$array[] = $row;
}
echo json_encode($array);
At this point, this is where it fails. I don't know really where the problem is. Because I want an associative array.
I would appreciate it if you could assist me, because as I mentioned, I don't really know how to solve it from here.
Thanks in advance!
EDIT: I realised I had a typo while writing this. changing data['name'] to key['name']
You have issue in the jquery each function. Replace the success function as
success: function(data){
$.each(data, function(i, key){
$("#response").html(key['name'])
});
},
It is because jquery each function has key and value as argument, so only replace "data" by "key" in your this line: $("#response").html(data['name'])
There are a couple places that you are going to run into trouble with this. Here is a JSFiddle for you to reference with my tips below:
https://jsfiddle.net/MrProvolone/zgw9ymv3/2/
There are a few things to consider...
1). Your returned data needs to be converted using parseJSON(), which is a built in jQuery function. This will convert your JSON string into a JavaScript object.
2). When you are looping through your object, you need to include the number (i) that you are trying to access
3). Because we are making a new object variable, we don't need the "key" designator in your $.each() function call... so it becomes $.each(data, function(i){}); instead of $.each(data, function(i, key){});
3). When you are trying to write out your html, you must grab what is already in the container, then add your new html to it, and finally write it all back out to the container.
Here is a step by step:
Instead of:
success: function(data){
$.each(data, function(i, key){
$("#response").html(key['name'])
});
}
We need to add the parsing (and remove the "key" variable per #3 above) so it becomes this:
success: function(data){
var parsed = jQuery.parseJSON(data);
$.each(data, function(i){
$("#response").html(key['name']);
});
}
Now we have a new variable to work off of (parsed) so we need to change both the $.each line, and the .html() line to make sure it uses that new variable....
So this:
$.each(data, function(i, key){
$("#response").html(key['name']);
});
Becomes this:
$.each(parsed, function(i){
$("#response").html(parsed['name']);
});
But that still won't work. We are looping through the object, so when we try to access a value, we have to specify which element in the object we are trying to get to. So anywhere in your loop that looks like this:
parsed['keyname']
becomes this:
parsed[i]['keyname']
So now we have:
$.each(parsed, function(i){
$("#response").html(parsed[i]['name']);
});
At this point you should be getting some html in your container. However, you will notice that you are only getting the value of the last row of your data. That is because you are overwriting ALL of your html in the container in each loop, instead of adding to what is already there. We need to make a new variable to fix this. So this:
$.each(parsed, function(i){
$("#response").html(parsed[i]['name']);
});
Becomes this:
$.each(parsed, function(i){
var oldhtml = $("#response").html();
$("#response").html(oldhtml + '<br>' + parsed[i]['name']);
});
Now you will see each result, with a html line break between each one.
Hope this helps!
In your js, on the success callback, you are using the wrong data, and not appending the data retrieved to the html Tag
Here is an essai
success: function(data){
if(typeof data != "object"){
data = JSON.parse(data);
}
$.each(data, function(i, key){
$("#response").append(key['name'])
});
}
I am trying to populate a table from mysql based on a select box option using jquery ajax, so far this is my jquery code. I can show the result on the alert box but i dont know how to send it to php so that i can loop thru the array and create the table.
// selector de campaña en reporte de clientes mas activos
$(document).ready(function(){
$('.selector-camp').change(function(){
var campaing = $('.selector-camp').val();
$.post( "../campanas/test", { 'camp': campaing },
function( data ) {
alert( data.result );
}, "json");
});
});
As I use JavaScript more than jquery, I'll write it in JavaScript and I am sure you can do that in Jquery too, but in JavaScript it's also easy to do
function( data )
{
createTable(data.result); //pass your json array to JS function
}, "json");
//here i create js function
function createTable(array)
{
var array = JSON.parse(array); //decoding from json format
//So if i have numbers in array like [1, 2, 3, 4] and want
//to create row with them something like this should be done
var table = document.createElement("table"); //create table
var tr = document.createElement("tr"); //create row
for(var i=0; i<array.length; i++)
{
var td = document.createElement("td");
td.innerHTML = array[i];
tr.appendChild(td);
//for each array element creates cell and appends to row
}
table.appendChild(tr);
//Then you can have some empty div and append table to it
var div = //your empty div
div.appendChild(table);
}
Please check below php prototype code as per your requirement.
From ajax please make a call to this file it will return you a json response since I have used json_encode() function, you can directly return array as well but I would not suggest that, also you can edit this code for further mysql query.
<?php
test();
function test(){
$camp = htmlspecialchars($_POST['camp']);
isset($camp)&&!empty($camp)?
$data = array('test_key'=>'test_value');
echo json_encode($data);
}
?>
I have a jquery function that calls a controller which in turn calls a function that I extracted the data from the users table. I return an array cin all the data in the table. ID, username etc etc.. So mold date in jQuery and indeed the array is full. Ex. [{"Id_user": "21", "username": "cassy1994"}].
From this array I have to extract only the username. How can I do?
This is the Ajax function:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
var txt = "";
$.get("http://localhost/laravel/public/index.php/apprezzamenti/"+id,
function(data)
{
$(".modal-body-apprezzamenti>p").html(data);
});
});
If the json is parsed, your object is stored in an array, so:
data[0].username
If not (if it is a string), you need to parse it first:
data_parsed = JSON.parse(data);
// data_parsed[0].username
assuming data is where your response is stored, data[0].username should work. Example:
$(".modal-body-apprezzamenti>p").html(data[0].username);
To print all usernames:
var count = 0;
$.each($(".modal-body-apprezzamenti>p"), function() {
this.html(data[count].username);
count++;
]);
Hope this helps!
So, this is the problem. It's okay though, I realized that with this code I'm using can not seem to generate as many sections as there are users want to print and it shows me only the last username because it can generate only a paragraph in html. A possible solution which would it be?
This is the code:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
var txt = "";
$.get("http://localhost/laravel/public/index.php/apprezzamenti/"+id,
function(data)
{
data_parsed = JSON.parse(data);
for(var i=0; i<data_parsed.length; i++)
{
$(".modal-body-apprezzamenti>p").html((data_parsed[i].username));
}
});
});
To begin with I am building a complete CRM running Ajax and there is a lot to this, so please be patient and read the whole thing.
I have an ajax script returning several json arrays. When I display the return value from my php script I get this:
[{"packages":{"id":"1","name":"Land Line"}},{"packages":{"id":"2","name":"Cellular w\/Alarm.com"}},{"packages":{"id":"3","name":"Home Automation"}}]
What I am trying to do is separate the arrays so I can make a select drop down from it. Before anyone says anything, yes I know how to do that my itself, but I am needing the form this script is populating to be a select dropdown or a complete filled in form based off of the id going into another script. It is a bit confusing, so don't ding me for it please.
Here is the PHP script alliance_form.php:
$equip = "SELECT * FROM packages WHERE brand='$brand'";
if($db->query($equip) === false) {
trigger_error('Wrong SQL: ' . $query . ' Error: ' . $db->error, E_USER_ERROR);
} else {
$result = $db->query($equip);
$array = array();
foreach($result as $r) {
$array[] = array(
"packages" => array(
"id" => $r['id'],
"name" => $r['name']
)
);
}
echo json_encode($array);
}
Here is the jquery going to the PHP form and coming back to input the information:
$.ajax({
type: "POST",
url: "/crm/alliance_form.php",
data: dataString,
success: function(msg)
{
$("#package-form").html(msg);
$.each(msg.packages, function(i, object) {
$.each(object, function(index, value) {
alert(value);
});
});
},
error: function(error)
{
$(".error").html(error);
}
});
This is part of an ordering system of a CRM, so this script is checking the database for existing orders under the id. If the id is there then it is supposed to come back with the order information and I populate the form. If not it will give a select dropdown to select a package which then populates an empty form. That is the gist of what I am on right now.
Here is the question: Why can't I get a response from JQuery on the each() loop on this. One return comes back with a regular array, and this one is a nested array.
I'm not quite clear on what you're asking, but here are my thoughts on this:
You've got .packages in the wrong place. Instead of this:
$.each(msg.packages, function(i, object) {
$.each(object, function(index, value) {
...
You should have written this:
$.each(msg, function(i, object) {
$.each(object.packages, function(index, value) {
...
Better yet, you could just get rid of packages altogether. It's an unnecessary level in the JSON structure.
Also, I don't think jQuery knows that the response is JSON. For this to work, you need either dataType: 'json' in the list of arguments to $.ajax, or something on the server to set the MIME type appropriately.
I'm also concerned about $("#package-form").html(msg);, because msg is not an HTML string.
You should try something like this (Example)
msg = $.parseJSON(msg); // parse JS to object
$.each(msg, function(i, object) {
$.each(object.packages, function(index, value) {
console.log(value);
});
});
Instead of $.each(msg.packages, function(i, object){...}) because msg is an array of objects and in your given example there are three objects right now and each object has a packages item (nested object) which contains id and name.
Update : You can also use, just one loop (Example)
msg = $.parseJSON(msg); // parse JS to object
$.each(msg, function(i, object) {
console.log(object.packages.id);
console.log(object.packages.name);
});
Sorry guys, I threw out my back and couldn't get to my code from home.
Anyways I tried both solutions you provided, and I have been looking at this for a while but neither worked. I have this updated to:
$("#brand").click(function () {
var brand = $(this).attr('rel');
$("#order-form").empty();
var contact_id = $("#contact_id").val();
var dataString = "contact_id=" + contact_id +"&brand=" + brand + "";
//alert("test");
$.ajax({
type: "POST",
url: "/crm/alliance_form.php",
data: dataString,
//dataType: "json",
success: function(msg)
{
//$("#package-form").html(msg);
$.each(msg, function(i, object) {
if(msg.packages) {
$("#package-form").append("<select>");
$.each(object.packages, function(index, value) {
$("#package-form").append('<option value="'+value+'">'+index+'</option>');
});
$("#package-form").append('</select>');
}
});
},
error: function(error)
{
$(".error").html(error);
}
});
});
This just returns nothing not even a blank select box. The $("#package-form").html(msg); is just so I can see the output how the php script is sending it back. The if statement is just to run a verification to see if the array has a nested array with packages in it. I need the return function to do a certain action if it does. Very Important!
As for the dataType: 'json', line in the ajax, it doesn't give me a return value if I have that placed in it. But when I remove it, it will display the array.
Nothing has been changed in the PHP file besides moving the query like suggested.
Ok guys. I got the answer! I have it like this:
$("#brand").click(function () {
$("#order-form").empty();
$("#package-form").empty();
var msg = '[{"packages":{"1":"Land Line"}},{"packages":{"2":"Cellular w\/Alarm.com"}},{"packages":{"3":"Home Automation"}}]';
var newData = JSON.parse(msg);
var newSelect = "<select>";
$.each(newData, function(i, ob) {
$.each(ob.packages, function(index, value) {
newSelect += '<option value="'+index+'">'+value+'</option>';
});
});
newSelect += "</select>";
$("#package-form").append(""+newSelect+"");
});
Here is the fiddle: http://jsfiddle.net/M78vE/
I have a php page which includes the following javascript:
<script>
$(document).ready(function(){
$('#search').hide();
});
$('#L1Locations').live('change',function(){
var htmlstring;
$selectedvalue = $('#L1Locations').val();
$.ajax({
url:"<?php echo site_url('switches/getbuildings/');?>" + "/" + $selectedvalue,
type:'GET',
dataType:'json',
success: function(returnDataFromController) {
alert('success');
var htmlstring;
htmlstring="<select name='L2Locations' id='L2Locations'>";
htmlstring = htmlstring + "<option value='all'>All</option>";
console.log(returnDataFromController);
var JSONdata=[returnDataFromController];
alert('string length is' + JSONdata.length);
if(JSONdata.length > 0)
{
for(var i=0;i<JSONdata.length;i++){
var obj = JSONdata[i];
for(var key in obj){
var locationkey = key;
var locationname = obj[key];
htmlstring = htmlstring + "<option value='" + locationkey + "'>" + locationname + "</option>";
}
}
$('#l2locations').html(htmlstring);
}
else
{
alert('i think undefined');
$('#l2locations').html('');
}
}
});
$('#search').show();
});
</script>
what i'm trying to accomplish is dynamically show a combo box if the variable "returnDataFromController" has any items.
But I think I have a bug with the line that checks JSONdata.length.
Regardless of whether or not the ajax call returns a populated array or an empty one, the length always shows a being 1. I think I'm confused as to what is counted when you ask for the length. Or maybe my dataType property is incorrect? I'm not sure.
In case it helps you, the "console.log(returnDataFromController)" line gives the following results when i do get data back from the ajax call (and hence when the combo should be created)
[16:28:09.904] ({'2.5':"Admin1", '2.10':"Admin2"}) # http://myserver/myapp/index.php/mycontroller/getbranches:98
In this scenario the combo box is displayed with the correct contents.
But in scenario where I'm returning an empty array, the combo box is also created. Here's what the console.log call dumps out:
[16:26:23.422] [] # http://myserver/myapp/index.php/mycontroller/getbranches:98
Can you tell me where I'm going wrong?
EDIT:
I realize that I'm treating my return data as an object - I think that's what I want because i'm getting back an array.
I guess I need to know how to properly check the length of an array in javascript. I thought it was just .length.
Thanks.
EDIT 2 :
Maybe I should just chagne the results my controller sends? Instead of returning an empty array, should I return false or NULL?
if (isset($buildingforbranch))
{
echo json_encode($buildingforbranch);
}
else
{
echo json_encode(false);
}
EDIT 3:
Based on the post found at Parse JSON in JavaScript?, I've changed the code in the "success" section of the ajax call to look like:
success: function(returnDataFromController) {
var htmlstring;
htmlstring="<select name='L2Locations' id='L2Locations'>";
htmlstring = htmlstring + "<option value='all'>All</option>";
console.log(returnDataFromController);
var JSONdata=returnDataFromController,
obj = JSON && JSON.parse(JSONdata) || $.parseJSON(JSONdata);
alert(obj);
}
But i'm getting an error message on
[18:34:52.826] SyntaxError: JSON.parse: unexpected character # http://myserver/myapp/index.php/controller/getbranches:102
Line 102 is:
obj = JSON && JSON.parse(JSONdata) || $.parseJSON(JSONdata);
The problem was that the data from the controller is malformed JSON.
Note the part of my post where I show the return data:
({'2.5':"Admin1", '2.10':"Admin2"})
The 2.5 should be in double quotes not single quotes.
I don't understand how / why this is happening but I will create another post to deal with that question. Thanks everyone.