Using JSON to pass Javascript array to PHP - php

I have 2 selects on my HTML, the options are loaded via my database and the user can switch the options between the boxes, like so:
<select id="column1" multiple size="10" name="FromLB" style="width:150px">
<?php foreach ($result->result() as $row) { ?>
<option value="<?php echo $row->id ?>"><?php echo $row->title ?></option>
<?php } ?>
</select>
So far so good, the final plan is for the the user to click Submit and to have access to the data on these two selects in PHP (via an array).
After digging around for a bit, it seems like JSON is the way to go.
I import json.js to my project and get to work:
function sort_cols(){
var i=0;
var p=0;
var column1 = new Array();
var column2 = new Array();
$("#column1 option").each(function()
{
column1[i]=$(this).val();
i=i+1;
});
$("#column2 option").each(function()
{
column2[p]=$(this).val();
p=p+1;
});
JSON = JSON.stringify(column1);
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
data: JSON,
success: function(){
alert("Success!")
}
});
}
So far I'm only passing one array (for the first select column), but I'm getting an error:
Uncaught TypeError: Object ["15","14","1"] has no method 'stringify'
I've been following this answer:
How exactly do you use json_decode to pass a javascript array to php?
I'm wondering what am I doing wrong here, and how can I pass my second array (column2) as well?

In this line
JSON = JSON.stringify(column1);
you redefine the native JSON object. Use another name for your variable and you should be fine.
And as for submitting both arrays, just use an encapsulating object:
data2send = JSON.stringify( { 'column1': column1, 'column2': column2 } );
Besides instead of using an incrementing index to insert your data into the arrays, just use the native push() method.

There's some strange behaviour happening here, most likely caused by the fact your JSON variable is overwriting the browser's native JSON object (or the one provided by json.js in older browsers).
You can actually pass an object directly to $.ajax, so the following will work:
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
data: column1,
success: function(){
alert("Success!")
}
});
If you want to pass both columns as separate parameters, change it to:
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
data: {
first_column: column1,
second_column: column2
},
success: function(){
alert("Success!")
}
});
They will now be available in your PHP script as $_POST['first_column'] and $_POST['second_column'].
This way, you leave the heavy lifting of converting your objects to JSON to jQuery, so you don't need to include the json.js library at all.
Your full code, rewritten:
function sort_cols(){
var column1 = [],
column2 = [];
$("#column1 option").each(function() {
column1.push($(this).val());
});
$("#column2 option").each(function() {
column2.push($(this).val());
});
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
data: {
first_column: column1,
second_column: column2
},
success: function(){
alert("Success!")
}
});
}

Make jQuery do the heavy lifting:
function sort_cols(){
var col1 = [], col2 = [];
$("#column1 option").each(function() {
col1.push($(this).val());
});
$("#column2 option").each(function() {
col2.push($(this).val());
});
$.ajax({
url: '<?php echo base_url() . 'js_tests/update_news'; ?>',
type: 'POST',
contentType: "application/json",
data: JSON.stringify({
column1: col1,
column2: col2
}),
success: function(){
alert("Success!")
}
});
}

Related

How to output json array value in ajax success?

I have post the data and return the value with json_encode and get that in ajax success stage. but i can't out that data value in specific input. Here is my html input. The return value are show in console and alert box as below.
{"status":"0","data":[{"user_id":"1","start_time":"00:00:00","end_time":"01:00:00","date_select":"2017-03-23","admin_flag":"0","interview_plan_staff_id":"1","interview_plan_staff_name":"Administrator","user_name":"\u304a\u306a\u307e\u30481"},{"user_id":"31","start_time":"00:00:00","end_time":"01:00:00","date_select":"2017-03-23","admin_flag":"0","interview_plan_staff_id":"1","interview_plan_staff_name":"Administrator","user_name":"uchida"}]}
<input type="text" id="admin_id" class="form-control">
Here is my ajax
function cal_click(cal_date){
var calDate = cal_date
var date_format = calDate.replace(/-/g, "/");
var base_url = <?php base_url(); ?>
$.ajax({
type: "post",
url: "<?php echo base_url('Admin_top/getcal');?>",
data: {calDate:calDate},
cache: false,
async: false,
success: function(result){
console.log(result);
alert(result);
}
});
}
Use JSON.parse to get specific input from result
function cal_click(cal_date){
var calDate = cal_date
var date_format = calDate.replace(/-/g, "/");
var base_url = <?php base_url(); ?>
$.ajax({
type: "post",
url: "<?php echo base_url('Admin_top/getcal');?>",
data: {calDate:calDate},
cache: false,
async: false,
success: function(result){
console.log(result);
var obj = JSON.parse(result);
alert(obj.status);
//alert(result);
var user_id = [];
var start_time = [];
for (i = 0; i < obj.data.length; i++) {
user_id[i] = obj.data[i].user_id;
start_time[i] = obj.data[i].start_time;
}
alert(' First user '+user_id[0]+' Second User '+ user_id[1]+' First start_time '+start_time[0]+' Second start_time '+ start_time[1] );
}
});
}
Use a each loop to get the ids,result is a object that has a data array:
$.each(result.data,function(i,v){
console.log(v.user_id);
//$('.admin_id').val(v.user_id);//use val to append the value, note you have multiple ids so you need multiple inputs
});
if this doesn't work then you return a string not json so you need to convert it to json using:
var result = JSON.parse(result);
Read Following posts you will get idea about json parsing
Parse JSON from JQuery.ajax success data
how to parse json data with jquery / javascript?
and you can try looping like this
var parsedJson = $.parseJSON(json);
$(parsedJson).each(function(index, element) {
console.log(element.status);
$(element.data).each(function(k,v) {
console.log(v.user_id);
});
});
When in an AJAX callback, you can use result.data to access the array of objects being returned. You can work with these like you would any other Javascript object. You may need to deserialize the JSON first.
To accomplish what you're trying to do, the following code would do the trick, although it will only use the very first object in the array as you only have one text box.
var responseObj = JSON.parse(result);
document.getElementById('admin_id').value = responseObj.data[0].user_id;

Using jquery sortable with ajax and php

I am trying to use jQuery sortable and then save the changes to the database, however before I even get to updating the database I have something strange going on that I can't fathom. If I log the serialised data to the console, I get all items in the 'list' but if I echo out the json encoded array from the php script I only get one item - confused.com.
The jquery at the moment is:
$('#sortable-list').sortable({
//handle : '.handle',
update : function () {
var order = $(this).sortable('serialize');
var table = $(this).parent().attr('id');
console.log(order);
$.ajax ({
type: "POST",
url: templateDir + "/inc/changeSortOrder.php",
data: "order=" + order + "&sort=1&sort_table=" + table,
dataType: "json",
cache: false,
success: function(data)
{
console.log(data);
}
});
}
});
The PHP at the moment is:
if (isset($_POST['sort']) && $_POST['sort'] == 1) {
if ($_POST['sort_table'] == 'nationalities') {
$output = array();
$list = parse_str($_POST['order'], $output);
echo json_encode($output);
}
}
The console log gives me:
nationality[]=17&nationality[]=1&nationality[]=47&nationality[]=23&nationality[]=3&nationality[]=4&nationality[]=5&nationality[]=6&nationality[]=7&nationality[]=8&nationality[]=12&nationality[]=10&nationality[]=11&nationality[]=13&nationality[]=14&nationality[]=15&nationality[]=16&nationality[]=18&nationality[]=19&nationality[]=20&nationality[]=21&nationality[]=22&nationality[]=24&nationality[]=25&nationality[]=26&nationality[]=27 etc
And the echo json gives me:
Object {nationality: Array[1]}
nationality: Array[1]
0: "17"
length: 1
So for some reason the full array isn't being passed through to the PHP file and I can't work out why.
Your problem is that you are trying to assign a serialized array, to a single query string parameter, which will yield an incorrect query string. Try passing the serialized list as returned by the plugin serialize method like so:
$.ajax ({
type: "POST",
url: templateDir + "/inc/changeSortOrder.php",
data: order + "&sort=1&sort_table=" + table,
dataType: "json",
cache: false,
success: function(data)
{
console.log(data);
}
});
And then access the passed list in php with:
$list = $_POST['nationality'];

How to create dynamic table using the results

$.ajax({
type: "post",
url: "<?php echo site_url(); ?>/controller_d/login/admin_search_user",
cache: false,
data: $('#docContainer1').serialize(),
dataType:"JSON", //<----here
success: function(json){
var str= "<table><tr>";
$.each(json.query,function(i,v){
alert(v.uID); //gives U0016
alert(v.name); //gives saman
str+="<td>"+v.uID+"</td>";
str+="<td>"+v.name+"</td>";
})
str+="</tr></table">;
$("body").append(str);
}
I want to create a dynamic table using json object values it must create a table but this is not working it will says v.ID not define
row += "$('<td>').append("+dataString[i]+")";
or
var row = $('<tr>');
for(var i = 0; i < n; i++) {
row.append($('<td>').html(dataString[i]));
}
$('#results').append(row);
create a table on the layout (on html code) then inside this create a <tbody> tag. assign an ID, then on the success function of your jquery, use $("#*tbody ID*").html to assign the value on the tbody.
i've got this code on one of my projects. maybe you can use this as a reference (tblApproved is the id of the tbody):
function updateApprovedTable(){
// retrieve Unit Record
$.ajax({
type:'post',
url:'php/requests.php',
data:{mode:"getApproved"},
success:function(data){
$('#tblApproved').html(data);
}//success
});//ajax
}
can you please used this :
$.ajax({
type: "post",
url: "<?php echo site_url(); ?>/controller_d/login/admin_search_user",
cache: false,
data: $('#docContainer1').serialize(),
success: function(data){
$("body").append(data);
});
Also write your code for table create into this url "/controller_d/login/admin_search_user"
PHP Code
echo "<table>";
echo "<tr><td>content</td></tr>";
echo "<tr><td>content</td></tr>";
echo "<tr><td>content</td></tr>";
echo "</table>";

jQuery external function needs some PHP values

In my external JavaScript file, I have the following jQuery code:
$(function(){
$('#follow').on('click',function(){
$.ajax({
type: 'POST',
url : 'functions/follow.php',
data: {follower : session_id,
user : p_id,
success: function(result) {
if(result == 'followed'){
$('#follow').attr('id','unfollow').text('-Unfollow');
}
}
});
});
});
On my normal page, I have this:
var session_id = '<?php echo $_SESSION['id']; ?>',
p_id = '<?php echo $p_id; ?>';
but this is not passing the variables into the jQuery function. I have these two variables being set before the JavaScript file is being called, also.
EDIT: I have tested this with the function on the same page as where the button is, and I passed in the PHP values with an echo, and it worked then.
You can create a namespace in the jquery object allowing access to it even inside events. Like so:
$.mynamespace = {
session_id: '<?php echo $_SESSION['id']; ?>',
p_id: '<?php echo $p_id; ?>'
};
Then reference those namespace vars in your code like so:
$(function(){
$('#follow').on('click',function(){
$.ajax({
type: 'POST',
url : 'functions/follow.php',
data: {follower : $.mynamespace.session_id,
user : $.mynamespace.p_id,
success: function(result) {
if(result == 'followed'){
$('#follow').attr('id','unfollow').text('-Unfollow');
}
}
});
});
});
This will also make them available for any other jQuery events/callbacks etc
(NB: Make sure your variables are being set before you try to use them, i.e. higher in the script)

multiple return values from PHP with jQuery AJAX

I'm using this jQuery code:
$.ajax
({
type: "POST",
url: "customerfilter.php",
data: dataString,
cache: false,
success: function(html)
{
$(".custName").html(html);
}
});
How can i do something like this: $(".projDesc").html(html1);
So i can split the returned results into two html elements?
echo "<p>" .$row['cust_name']. "</p>";
thats the PHP i'm using and i want to echo another statement which i can put into another HTML element
Does this make sense?
Use json_encode() to convert an associative array from PHP into JSON and use $.getJSON(), which will return a Javascript array.
Example:
<?php echo json_encode(array("a" => "valueA", "b" => "valueB")); ?>
In Javascript:
$.getJSON("myscript.php", function(data) {
alert("Value for 'a': " + data.a + "\nValue for 'b': " + data.b);
});
Make your response return JSON, you'll need to change your jQuery to this, so the expected dataType is json:
$.ajax
({
type: "POST",
url: "customerfilter.php",
dataType: 'json',
cache: false,
success: function(data)
{
$(".custName").html(data.message1);
$(".custName2").html(data.message2);
}
});
Then you need to encode your response as a JSON Array:
<?php echo json_encode(
array("message1" => "Hi",
"message2" => "Something else")
) ?>
Why don't you return a JSON object. This way you can easily put many different results inside the ajax response.
You can use a separator and join the values like this in your response
echo $value1.'|'.$value2;
Now you can use JavaScript method split("|") as below:
var myarray = response.split("|");
var value_1 = myarray[0];
var value_2 = myarray[1];

Categories