I am using jQuery to input data to a php file and return the results via json. However, the json is appearing in firebug, but the variable 'messageOutput' is not displaying results on the form. If I replace 'messageOutput' with 'msg.box' then it prints fine.
If I enter more than 1 item on my form, then it errors with: 'object object'.
Can someone point out where my error is as I have been struggling with this for ages. If you need to see any further code, please ask. many thanks.
jQuery code:
submitHandler: function() {
if ($("#BA_boxform").valid() === true) {
var data = $("#BA_boxform").serialize();
$.post('/domain/admin/requests/boxes/boxesadd.php', data, function(msg) {
var messageOutput = '';
for (var i = 0; i<msg.length; i++){
messageOutput += msg[i].box+' ';
}
$("#BA_addbox").html("You have entered box: " + "<b>" + messageOutput + "</b><br /> You may now close this window.");
$("#BA_boxform").get(0).reset();
}, 'json');
} else
{
return;
}
},
success: function(msg) {
//$("#BA_addbox").html("You have entered a box");
//$("#BA_boxform").get(0).reset();
}
boxesadd.php
<?php
$dept = mysql_real_escape_string($_POST['customerdept']);
$company = mysql_real_escape_string($_POST['BA_customer']);
$address = mysql_real_escape_string($_POST['customeraddress']);
$service = mysql_real_escape_string($_POST['BA_service']);
$box = mysql_real_escape_string($_POST['BA_box']);
$destroydate = mysql_real_escape_string($_POST['BA_destdate']);
$authorised = mysql_real_escape_string($_POST['BA_authorised']);
$submit = mysql_real_escape_string($_POST['submit']);
$boxerrortext = 'You must enter a box for intake';
$array = split('[,]', $_POST['BA_box']);
if (isset($_POST['submit'])) {
foreach ($array as $box) {
if (empty($box)) {
$error = array('boxerrortext'=>$boxerrortext);
$output = json_encode($error);
echo $output;
}
else
{
$form=array('dept'=>$dept,
'company'=>$company,
'address'=>$address,
'service'=>$service,
'box'=>$box,
'destroydate'=>$destroydate,
'authorised'=>$authorised,
'submit'=>$submit);
$result=json_encode($form);
echo $result;
?>
its hard to debug it without knowing what the the request response looks like. Are you sure that the server returns an array? I'm not familiar with php, so i am not to helpful there, looking quickly it seems that the php 'array' is really more akin to a js object literal then a js array. I.e. it looks like it is a bunch of key/value pairs.
in which case, you should use the for/in loop instead of the for/each
for ( var key in msg )
messageOutput += msg[key] // => concats dept, company, address, etc
if you are really expecting an array of those objects (where you have a bunch of objects with the prop 'box') then you are doing it correctly in the javascript but you may not be sending the right object back from the server.
can you pop open the dev panel/firebug and show us what is being returned from the server?
try adding:
console.log($.isArray(msg))
and seeing if it returns true or not. One way of ensuring what is returned is an array is to use, what i call a splat utility:
function splat(obj){
return $.isArray(obj) ? obj : [ obj ];
}
this makes sure you are always dealing with an array, albeit sometimes an array of one time
Related
So I am trying to send the "id" of a selected row in datatable in javascript to a php page so I could delete it from database.
var ids = $.map(table.rows('.selected').data(), function (item) {
return item[0] });
the variable "ids" is sent by post method
$.post( "deleterow.php", { v1: ids });
but it didn't worked so i try to see the response from post method and it says
"notice array to string conversion in C on line ... "
the line is of php page where i am writing the delete query
$id = $_POST["v1"];
$query = "DELETE FROM `package` WHERE `id` = '$id'";
The whole php page works fine when trying with other values.
Because you send an array here:
$.post( "deleterow.php", { v1: ids });
so v1 contains an array of elements. But in your php code you treat it as a single element:
$id = $_POST["v1"];
Hence the notice array to string conversion.
If you send an array of elements, you have to get it as an array and treat is as an array. To create a correct SQL string you should append each ID, like this:
$ids = json_decode($_POST["v1"]);
$query = "DELETE FROM `package` WHERE";
$first = true;
foreach ($ids as $id) {
if ($first) {
$first = false;
} else {
$query += " OR";
}
$query += " `id` = '$id'"
}
This way you loop the array and append a id = ID for each array element.
Now, this is important, this code is prone to SQL injection, a really bad security problem. Read this to get more info about this: How can I prevent SQL injection in PHP?
A JSON encoded array is passed from PHP to an HTML document. It is not at all clear how to deconstruct that array into javascript-usable pieces. For example, consider the following HTML:
<div id="options">{"foo":[{"id":1},{"id":3}], "bar":[{"id":2},{"id":4}]}</div>
The only a priori known element of this array is that the key id exists. The indices, I know, can be found with
var data = JSON.parse($("#options").text());
$.each(data, function(index) {
// index will be foo & bar
});
The use case is to use the index and id to add an attribute to elements in a document. I have not yet stumbled upon the technique to return the ids associated with each index. How best can that be done?
Edit - a clarification of the use case - the long story
I want to re-enable some options on a form based on properties of an entity (in a Symfony application). Disabled options cannot be modified, but are also not not persisted - their values are set to null. I've built a service to determine the option elements that are disabled and send those elements to the form document as a JSON object. I'm assuming for now that the specific options are not known until the form is created. In the example above, foo & bar represent possible options, and the ids correspond to the option. For example, a Household entity might have Reason options selected but disabled of "Low wages" (id = 3). This would show up in as ...id="options">{"reasons":[{"id":3}]}<.... I would the use this information to remove the disabled="disabled" attribute from the set of checkboxes for the Reason, id=3 (i.e., id="household_reasons_3") field. I hope this makes sense.
Edit #2, by request - the PHP code creating the object.
The result of getMetatData() appears in the document at #options. From the above edit, the Household entity is $object.
public function getMetaData($object) {
$data = array();
$className = get_class($object);
$metaData = $this->em->getClassMetadata($className);
foreach ($metaData->associationMappings as $field => $mapping) {
if (8 === $mapping['type']) {
$data[$field] = $this->extractOptions($object, $field);
}
}
return json_encode($data);
}
private function extractOptions($object, $field) {
$data = [];
$method = 'get' . ucfirst($field);
$itemName = substr($field, 0, -1);
$getter = 'get' . ucfirst($itemName);
$entity = $object->$method();
foreach ($entity as $item) {
if (method_exists($item, 'getEnabled') && false === $item->getEnabled()) {
$data[] = ['id' => $item->getId()];
}
}
return $data;
}
Long before the infinite monkey limit was reached I stumbled on a method to create the results I was looking for. My thanks go out to all who pushed for clarifications. So, for the object
{"foo":[{"id":1},{"id":3}], "bar":[{"id":2},{"id":4}]}
the script
var data = JSON.parse($("#options").text());
var i = 0
var output = [];
$.each(data, function(index, item) {
$.each(item, function(k, v) {
output[i] = "household_" + index + "_" + v.id;
i++;
});
});
output;
produces this:
["household_foo_1", "household_foo_3", "household_bar_2", "household_bar_4"]
I get the strings I need; I can take it from here.
So Here is my php file code
GetUserArray.php
$Users = array('7'=>'samei', '4'=>"chaya", '10'=>'abetterchutia');
echo json_encode($Users);
and this is my ajax request
$.ajax({
url: './GetUserArray.php',
type: 'POST',
dataType: "json",
success: function(users) {
console.log(users);
$.each( users, function( key, value ) {
console.log(key, value);
});
}
});
now what it gives me is in the console is an object sorted by the keys of that array while i want the orignal order which was 7 4 10 in my php file
Object {4: "chaya", 7: "samei", 10: "abetterchutia"}
4 chutiya
7 sali
10 abetterchutia
The problem with using hashmaps is that they don't actually specify order. Though, in PHP, an array is actually an ordered hashmap, so it does. Once you translate that into an object in Javascript, the order is no longer preserved. The only way to guarantee order in Javascript is to use an array.
So in PHP this works as expected and preserves order.
$arr = [4 => "I'm first", 1 => "I'm second", 3 => "I'm third"];
foreach($arr as $value) {
echo $value, "\n";
}
Which gives us
I'm first
I'm second
I'm third
But encode that to Javascript Object Notation (i.e. JSON) and you get an object, because in Javascript arrays don't have keys, they have indexes.
echo json_encode($arr);
Gives us...
{"4":"I'm first","1":"I'm second","3":"I'm third"}
If you tried to do the same in Javascript with this object you might not get the same order
var obj = {"4":"I'm first","1":"I'm second","3":"I'm third"};
var s = "";
for(var x in obj) {
s += + obj[x] + "\n";
}
document.write("<pre>" + s + "</pre>");
This might give you something more like...
I'm second
I'm third
I'm first
So the only way to fix that is to use an array...
json_encode(array_values($arr));
Now this gives us...
["I'm first","I'm second","I'm third"]
And the order is maintained.
However, if you want to preserve the keys as well, you'll have to create an array of objects.
$json = [];
foreach($arr as $key => $value) {
$json[] = [$key => $value];
}
echo json_encode($json);
Now you get...
[{"4":"I'm first"},{"1":"I'm second"},{"3":"I'm third"}]
Which in javascript, works perfectly as expected...
for(var x in obj) {
for(var n in obj[x]) {
obj[x][n]; // now you can both maintain order and have access to the key
}
}
I am echoing two array values from PHP. How do I differentiate these values in ajax.
if(#mysql_select_db("trainer_registration"))
{
$select_query_num = #mysql_query("select program_id,facilitator_id,availability_status from program_facilitator");
$select_query_name = #mysql_query("select facilitator_id,firstname,lastname,email_id from facilitator_details");
$num_rows = #mysql_num_rows($select_query_num);
$trainerdetails = [];
$traineravaildetails = [];
$i = 0;
while($row = #mysql_fetch_assoc($select_query_num))
{
$trainerdetails[$i]['pgidi'] = $row['program_id'];
$trainerdetails[$i]['facilitatorid'] = $row['facilitator_id'];
$trainerdetails[$i]['avail_status'] = $row['availability_status'];
$trainerdetails[$i]['idi'] = $row['facilitator_id'];
$i++;
}
while($row1 =#mysql_fetch_assoc($select_query_name))
{
$traineravaildetails[$i]['facilitatorid'] = $row1['facilitator_id'];
$traineravaildetails[$i]['firstname'] = $row1['firstname'];
$traineravaildetails[$i]['lastname'] = $row1['lastname'];
$traineravaildetails[$i]['emailidvalue'] = $row1['email_id'];
$i++;
}
echo json_encode($trainerdetails);
echo json_encode($traineravaildetails);
}
?>
function loadavailabletrainers (m) {
$.ajax({
url: 'assignavailtrainers.php',
data: { action:'test' },
type: 'post',
success: function(output) {
console.log(output);
}
});
}
I've seen a examples of multiple return values from php and handling them in ajax, but I didn't understand them. Can someone please explain how to differentiate output values in my case?
OUTPUT:
[[{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"1","avail_status":"2","idi":"1"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"1","avail_status":"2","idi":"1"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"2","avail_status":"2","idi":"2"}],{"7":{"facilitatorid":"1","firstname":"Vignesh","lastname":"Anand","emailidvalue":"v*******#gmail.com"},"8":{"facilitatorid":"2","firstname":"Vignesh","lastname":"Anandakumar","emailidvalue":"vign*****#gmail.com"},"9":{"facilitatorid":"3","firstname":"Vignesh","lastname":"Anand","emailidvalue":"v*****#hotmail.com"},"10":{"facilitatorid":"4","firstname":"Vignesh","lastname":"Anand","emailidvalue":"****#live.com"}}]
It's a nice practice to send only one stream of values so you can process it all at once.
First, you could create a container array:
$data = array('trainerdetails' => $trainerdetails,
'traineravaildetails' => $traineravaildetails);
Then
echo json_enconde($data);
This will generate a merged output.
The encoded string returned by your PHP code needs to be decoded in the client side (more details: Parse JSON in JavaScript?). Because of that, you could use $.getJSON(), which is an alias for a specific call to $.ajax (doc: http://api.jquery.com/jquery.getjson/).
The 'success' function will pass a 'key'=>'value' array data. In this case you'd need to treat the value as they may contain extra levels of arrays. It helps if you can visualize your data structure as tree view, like this: http://jsonviewer.stack.hu/ (paste your output there).
I hope it helps!
Hey friends i am using javascript sdk to post on users friends wall with jQuery facebook multi friend selector however i am getting this error friendId.split is not a function. Here is my code
function recommendToFriend(pic, url, friendId, fromName)
{
alert(friendId);
var friendList ;
pFriend = new Array();
pFriend = friendId.split(',');
for( x in pFriend )
{
alert(pFriend[x]);
var publish = {
method:'feed',
picture:pic,
link:url,
name:'SHARP Product Recommend',
caption: fromName + 'has recommend a product to you via Sharp Expert lounge',
};
FB.api('/'+pFriend[x]+'/feed', 'post', publish, function(resp) {
if( !response || response.error )
alert('Unable to share');
else
alert('Successfully posted to firends wall');
});
}
}
In alert box i got comma seperated friend ids so i use split function post on each users wall seperately i dont know whats wrong here please help me
Most probably friendID is already an array. If you call alert the array is converted to a string and becomes a comma separated list of values.
Note that converting an array to a string is not the same as calling JSON.stringify (where you get also brackets and double quotes around elements when they're strings)
The JavaScript split() function is for the type string ie for eg.
var friendid='1,34,67';
As VisioN says, when you alert an array you get comma separated values.
You can traverse JS Objects like this
for (var key in friendid) {
var obj = friendid[key];
for (var prop in obj) {
alert(prop + " = " + obj[prop]);
}
}
Hope this helps
alternate
for( var x in friendId )
{
alert(friendId[x]); // this would be your desired value
}