I have a problem in jQuery, on how to get data from my codeigniter controller to jQuery function.
I am having a progress bar in jQuery and i need the value of the progress bar will be depend on the output of the controller; i use json_encode in controller.
Jquery
$(function() {
$( "#progressbar" ).progressbar({
value: //get value from the controller json_encode
});
});
Controller
public function countScoreCh(){
$id = $this->session->userdata('userID');
$data['getScore'] = $this->lawmodel->battleUserID($id);
foreach($data['getScore'] as $row){
$scoreCH = $row->challengerScore;
echo json_encode(
array(
'scoreCH' => $scoreCH,
)
);
}
}
the progress bar function will be something like this.
$(function() {
$( "#progressbar" ).progressbar({
value: //jsn.scoreCH value
});
});
Is there's a possible way of doing it? I don't know if using json_encode is the correct way. But any solution will do..:)
Thanks..
I think your controller doesnt produce the valid json. since it would produce a json string like this one :
{scoreCH:<SomeValue>}{ScoreCH:<SomeValue>}{ScoreCH:<Somevalue>}
It would be better if you put the set of ScoreCH value inside some "json wrapper" so you should modify you controller to create a temporary variable that contain all your values from the model like this one :
public function countScoreCh(){
$id = $this->session->userdata('userID');
$data['getScore'] = $this->lawmodel->battleUserID($id);
// Here is "my hack"
$output = array(); // it will wrap all of your value
foreach($data['getScore'] as $row){
unset($temp); // Release the contained value of the variable from the last loop
$temp = array();
// It guess your client side will need the id to extract, and distinguish the ScoreCH data
$temp['id_of_ScoreCH'] = $row->id;
$temp['ScoreCH'] = $row->ScoreCH;
array_push($output,$temp);
}
// Now the $output supposed to be a two dimensional array looks like this one
// array(
// [0]=>array("id_of_ScoreCH"=>SomeID,"ScoreCH"=>SomeValue),
// [1]=>array("id_of_ScoreCH"=>SomeID,"ScoreCH"=>SomeValue),
// [2]=>array("id_of_ScoreCH"=>SomeID,"ScoreCH"=>SomeValue)
// );
// Then emit the wrapped value It would produce array of object JSON
// Dont forget to put the header format
header('Access-Control-Allow-Origin: *');
header("Content-Type: application/json");
echo json_encode($output);
}
Next on your client side (HTML) use the JSON.parse(<string_retrieved_from_controller>) like this one :
$.ajax({
url:<your_controller_name/you_method_name>,
data: <your_specific_data_you_want_to_pass_to_the_server>,
method:<post/get>
success:function(retrieved_data){
// Your code here.. use something like this
var Obj = JSON.parse(retrieved_data)
// Since your controller produce array of object you can access the value by using this one :
for(var a=0; a< Obj.length; a++){
alert("the value with id : " + Obj.id_of_scoreCH + "is " + Obj.ScoreCH);
}
}
});
Related
I'm trying to build an array of data that will then be ajax using post to php - below is my code:
$('#mainBodySaveSubmitButtonProfilePhotoIMG').click(function() {
var profilePhotoArray = [];
$('.mainUnapprovedProfilePhotoWrapperDIV').each(function() {
var action = '';
alert( this.id );
if($('.mainUnapprovedProfilePhotoAttractiveIMG', this).is(':visible')) {
alert('attractive...');
action = 'attractive';
}
else if($('.mainUnapprovedProfilePhotoDeleteIMG', this).is(':visible')) {
alert('delete...');
action = 'delete';
}else{
alert('normal...');
action = 'normal';
}
profilePhotoArray[this.id+'_'+this.id] = action;
});
alert(profilePhotoArray.length);
for (i=0;i<profilePhotoArray.length;i++) {
console.log("Key is "+i+" and Value is "+array[i]);
}
$.post('scripts/ajax/ajax_approval_functions.php', {
'approvalProfilePhotos': '1',
'approvalProfilePhotosData': profilePhotoArray},
function(data) {
alert(data);
});
});
The if, else if, else section works fine as I can see the alerts.
When I try to alert the array length 'profilePhotoArray' it says 0 so I'm not populating the array correctly. Do I need to use .push()? I thought this format was ok?
Also do I need to do anything to the array before sending to php via ajax?
thankyou
** edit - I'm adding "profilePhotoArray[this.id+'_'+this.id] = action;" this.id twice just to prove this words as I will pass a second variable like this... am I better to use JSON for this?
Javascript arrays use numerical index, therefore your storage is failing. Use a javascript Object to store string based keys.
var lang=new Object();
lang["foo"]="Foo";
lang["bar"]="Bar";
I have actually read all related answers to my question but I need a clear and simple example on how to properly implement my code below.
myHome.php
jquery
var url = "computeArea.php";
var data = $('thisForm').serialize();
$.post(url,data,function(response)); // how do i get the area being returned from
computeArea function? i need to save the
return value to a javascript variable
computeArea.php
function computeArea ($data){ // do i need to parse $data to make it an array?
return $area;
}
im new to jquery and your help is very helpful. thank you!
You can do:
$.post(url,data,function(response){
alert(response)
});
ps: you are missing the . between $ and post.
In your php code you could do that:
echo json_encode($area);
Do a simple teste.
jQuery:
$.post("url/to/file.php",{variable_name: "hello"/*(we'll give this value to variable_name*/)},
function(response){
if(response>0)
alert('Something went wrong');
else
alert(response);
});
Now, on server side:
<?php
if(isset($_POST['variable_name']) && $_POST['variable_name']!=="")
echo $_POST['variable_name'];
else
echo 1;
?>
You are misunderstanding the use of post requests. This will not call the computeArea function in computeArea.php and pass data as its parameter:
var data = $('thisForm').serialize();
$.post(url,data,function(response));
You can do this instead for computeArea.php:
$data = $_POST['watever_you_are_serializing'];
// Do computations, etc.
$area = 123; // Contains computed area
echo $area; // Or json_encode($area);
If you need to call that function from computeArea.php, then you can create a new file for $.post request (eg. computeArea2.php) and include computeArea.php from there. It would be something like this:
include 'computeArea.php';
$data = $_POST['watever_you_are_serializing'];
echo computeArea($data);
Something along the lines of:
var url = "computeArea.php",
data = $('thisForm').serialize(),
new_variable;
$.post(url, data, function(response) {
new_variable = response;
});
Though I presume there's a bit more to your PHP script, as otherwise $area isn't defined anywhere.
I have a table that has sortable rows. The table is generated from a mysql database that has a field called "displayorder" that oders the table. When the user drags and drops rows, I want to use AJAX to submit those changes to the database whenever a user drops a row.
Currently, I can see the console.log() output from the success part of the AJAX call, and when i output the data there (order) it looks great, like this:
["order_1=1", "order_2=2", "order_4=3", "order_3=4"]
But according to Firebug, all that's getting passed in the $_POST is "undeclared".
How do I access that order variable from my indexpage_order.php file?
I have this jquery code:
<script>
$(document).ready(function() {
var fixHelper = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index)
{
$(this).width($originals.eq(index).width())
});
return $helper;
};
var sortable = $("#sort tbody").sortable({
helper: fixHelper,
stop: function(event, ui) {
//create an array with the new order
order = $(this).find('input').map(function(index, obj) {
var input = $(obj);
input.val(index + 1);
return input.attr('id') + '=' + (index + 1);
});
$.ajax({
type: 'POST',
url: 'indexpage_order.php',
data: order,
error: function() {
console.log("Theres an error with AJAX");
},
success: function(order) {
console.log("Saved.");
console.log(order);
}
});
return false;
}
});
});
</script>
indexpage_order.php contains:
if(isset($_POST) ) {
while ( list($key, $value) = each($_POST) ) {
$id = trim($key,'order_'); //trim off order_
$sqlCommand =
"UPDATE indexpage
SET displayorder = '".$value."'
WHERE id = '".$id."'";
$query = mysqli_query($myConnection,$sqlCommand) or die (mysqli_error($myConnection));
$row = mysqli_fetch_array($query);
}
}
You can simply rewrite the js code that are generating the data for POST.
order = {}
$(this).find('input').map(function(index, obj)
{
return order[this.id] = index;
}
)
Rest should work in PHP.
Try $_REQUEST instead of $_POST on the PHP file for POST method with ajax.
convert the js array order to json object as ajax data needs to be in json using JSON.stringify. hence, it needs to be data:JSON.stringify(order), in the ajax function.
Or, use json_encode like this data: <?php echo json_encode(order); ?>, in the ajax function
order is an array. Convert the order to query string like this in your ajax script,
data: order.join('&'),
It looks like your sending your order in a JavaScript array
And when it arrives at your PHP, its unreadable.
If its an object look into the json_decode function.
If its an array, serialize the data before it goes, then unserialize on the php side.
PHP is unable to understand JavaScript array or objects unless they are encoded/serialized correctly.
Hmm... i'm trying to use a php variable in jquery, in my edit.php : i'd like to use jquery to show the php variable, using the "rel" attribute, but it gives me the "name" of the variable, not its content.
i'm using php to retrieve the text from the xml file : (edit : one click on submit does not update the text, but 2 clicks do)
/* READ */
$dom = new DomDocument();
$dom->load('edition.xml');
$_home = $dom->getElementsByTagName('home')->item(0);
$home = $_home->firstChild->nodeValue;
$_rhizo = $dom->getElementsByTagName('rhizo')->item(0);
$rhizo = $_rhizo->firstChild->nodeValue;
$_disco = $dom->getElementsByTagName('disco')->item(0);
$disco = $_disco->firstChild->nodeValue;
/* array */
$rels = array('home' => $home,
'rhizo' =>$rhizo,
'disco' =>$disco);
echo '<script>var rels = ' . json_encode($rels) . '</script>';
/* WRITE */
if ( isset($_POST['cache']) ){
if ( isset($_POST['home']) ){
$home = stripslashes($_POST['home']);
$_home->firstChild->nodeValue = $home;
}
if ( isset($_POST['rhizo']) ){
$rhizo = stripslashes($_POST['rhizo']);
$_rhizo->firstChild->nodeValue = $rhizo;
}
if ( isset($_POST['disco']) ){
$disco = stripslashes($_POST['disco']);
$_disco->firstChild->nodeValue = $disco;
}
$dom->save('edition.xml');
}
?>
(the text is simply shown in a textarea, where i just put the php variable)
then i use jquery to show the content from the php variable : (edit with the array object : )
$('#left a').bind('click', function(){
var text_from_link = $(this).text();
var rel = $(this).attr('rel');
$('#textarea1').attr('name', rel);
$('#textarea1').text(rels[''+rel+'']);//output is "$home" for example, which will retrieve the "home" part from the xml
return false;
})
And this works if i double click on submit, if i just click once, the text is not updated... i'm a bit confused with that
Thanks for your help
You need to do an ajax call to do that.
Or you can write a javascript object in your HTML:
$rels = array('rel23' => 'Hello world');
echo '<script>var rels = ' . json_encode($rels) . '</script>';
Then access them with javascript:
alert(rels.rel23);
like mentioned you will need to use ajax for this.. jQuery provides ajax and it appears you are already using it soooo....
if(isset($_POST["getHome"])) {
$dom = new DomDocument();
$dom->load('edition.xml');
$_home = $dom->getElementsByTagName('home')->item(0);
$home = $_home->firstChild->nodeValue;
echo $home; // anything returned by this page will become 'data'
}
and
$(function(){
$('a').bind('click', function(){
$.post("mypage.php",{getHome : 1}, function(data) {
alert(data);
});
})
});
ok assuming you have an array in your php
if(isset($_POST["varName"])) { // will check if the POST variable with the name 'varName' is set
$arr = array(1,2,3); // your array
echo json_encode($arr); // encode your output as a json string
}
then in your javascript
$(function(){
$('a').bind('click', function(){
$.post("mypage.php",{varName: 1}, function(data) { // the value of 1 is trivial. and is likely not needed, you can post to a page without passing any values. In which case the use if isset() in php is not required.
var json_obj = JSON.parse(data);
console.log(json_obj); // assuming you have a console at your disposal.
});
})
});
I am trying to post a group of arrays using the jQuery post method, but I am having trouble getting the value of the arrays. How can I get the values of the array that I have sent?
If somebody could help me i would be grateful....
Here is what i have done:
$(document).ready( function()
{
$("#submit_info").click (
function()
{
var batchArr= new Array();
batchArr=arrPush('batch');
var facultyArr= new Array();
facultyArr=arrPush('faculty');
var levelArr= new Array();
levelArr=arrPush('level');
var sectionArr= new Array();
sectionArr=arrPush('section');
var shiftArr= new Array();
shiftArr=arrPush('shift');
$.post("server_side/college_info_insert.php",{
batchArr:batchArr,
facultyArr:facultyArr,
levelArr:levelArr,
sectionArr:sectionArr,
shiftArr:shiftArr
}, function(data)
{
alert(data);
});
}
);
function arrPush(opt)
{
var Arr= new Array();
Arr.push($("#"+opt+"_1").val());
var count= $("#"+opt).val();
var i=0;
for(i;i<=count;i++)
{
if(i==0)
{
Arr.push($("#txt"+opt).val());
}
else
{
Arr.push($("#txt"+opt+i).val());
}
}
return Arr;
}
}
);
How can I get the array values in the next page "college_info_insert.php" ??
okay, so this is actually a really common issue. It's unclear that you can't just send an array as-is from javascript to PHP and have it recognized.
The problem is that PHP doesn't know how to read in multiple values from a POST request - typically things like that require the PHP author to use brackets like: varname[].
So, basically you must send variables as strings. Using JSON you can send even complicated objects as strings to PHP using a single variable name. Typically you'd use JSON.stringify or something along those lines - but if you have a simple array you might not even need it.
Here's a full example of the problem/solution, found using jquery and $.post:
Asume you have a file myurl.php:
<?php
print_r($_POST);
?>
And in a separate file (or the console), you try:
var myarray = Array('some','elements','etc');
var mydata = {postvar1: 'string', postvar2: myarray};
$.post('myurl.php', mydata, function(response) {
alert("response: " + response);
});
This doesn't work! The result is that postvar2 only contains "etc".
The solution is force the array into a JSON string that can be decoded from PHP.
var myarray = Array('some','elements','etc');
var json_array = $.map(myarray,function(n) {
return '"'+n+'"';
});
var mydata = {postvar1: 'string', postvar2: '['+json_array+']' };
$.post('myurl.php', mydata, function(response) {
alert("response: " + response);
});
ON the PHP side you now must use: json_decode($_POST['myarray']); to get your results in a proper array.
Note, this example assumes very simple strings or numbers in your array. If you have complex objects, you will need to use a JSON.stringify function which will take care of extra quotes, escaping special characters, etc.
Not sure if i understood the question but wouldn't something like this work
if (isset($_POST['batchArr'])) {
$batchArr = $_POST['batchArr'];
// Then populate your html here e.g
echo $batchArr[0];
}