I'm coding a form right now using jQuery .post and the file responsible for processing has the code:
print_r($_POST);
Which returns the following dynamic output:
Array ( [data] => capacity=50-1000+people&bookingdate=17%2F04%2F2012&grade=1+star )
I am trying to split up this array into three variables namely capacity, booking date and grade but don't really know how to. Any idea how? I've tried using echo $_POST["capacity"]; but it doesn't work.
Thanks in advance!
Edit
This is the jQuery I'm using:
<script type="text/javascript">
$(document).ready(function() {
$("#postData").click(function() {
$("#last-step").hide(600);
$.post('resources/process2.php', { data: $("#task5_booking").serialize() }, function(data) {
$("#result").html(data);
});
return false;
});
});
</script>
which is working with the following form:
http://jsfiddle.net/xSkgH/93/
I think you should change this line:
$.post('resources/process2.php', { data: $("#task5_booking").serialize() }, function(data) {
To
$.post('resources/process2.php', $("#task5_booking").serialize(), function(data) {
Notice that I changed the second parameter from an object literal to a (url-encoded) string. This posts each variable in your form as a separate variable (as if it were posted directly). On the server side, each variable should be available separately inside $_POST array.
Have a go with parse_str()
Something like:
parse_str($_POST['data'] , $output);
$capacity = $output['capacity'];
$bookingdate = $output['bookingdate'];
$grade = $output['grade'];
You have to use explode for this.
$data = array(); // A array to store the extracted value
$temp = explode("&", $data); // First of all explode by "&" to get the each piece
foreach($temp as $tval) {
$t = explode('=', $tval); // Next explode by "=" to get the index and value
$data[$t[0]] = $t[1]; //Add them to the array
}
Another alternative is to use parse_str():
$data = array();
parse_str($_POST['data'], $data);
After this all the values will be mapped to the $data
Related
Allow me to preface this by saying that I looked at multiple SO posts on this and I am still lost.
So in my php code I am fetching data from my database and then I am trying to insert it into an array as follows:
$arrayResult = array();
foreach ($result as $item) {
array_push($arrayResult, array("type" => $item['type'],
"count" => $item['count'])
);
}
echo json_encode($arrayResult);
My problem is as follows, the only time my JS shows any data is when I just print out the data on a successful AJAX call, any attempts at manipulating it fail totally. As in, no data shown at all.
var arrayResult = null;
$.get("../php/displayGraph.php",
function (data) {
arrayResult = (data);
var result = JSON.parse(arrayResult);
$("#results").html(arrayResult);
//$("#results").html(JSON.parse(arrayResult));
}
);
The result of this is:
[{"type":"Entertainment","count":"4"},{"type":"Other","count":"31"},{"type":"Politics","count":"50"},{"type":"Sports","count":"3"},{"type":"Technology","count":"9"}]
I am honestly at a loss in terms of what I even need to do to make it work. And here I thought java was bad with json.
Try like this,
$.get("../php/displayGraph.php",
function (data) {
$.each(data, function (i,item){
console.log(item.type + " === " +item.count);
}
/*arrayResult = (data);
var result = JSON.parse(arrayResult);*/
//$("#results").html(arrayResult);
//$("#results").html(JSON.parse(arrayResult));
}
);
Not sure why, but the following works
$.get("../php/displayGraph.php",
function (data) {
var result = JSON.parse(data);
$("#results").html(data);
console.log(result[1][0].count);
}
);
Certainly is a 2D array the way my php makes it, but i did not think this would be how to do as all the other tutorials i saw never had it like this.
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);
}
}
});
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'm working on a jQuery .get that will send a value to the server to compare against an array which will then get encoded into a json format as the responses. Below is the code (jQuery and PHP zend). I'm not sure if my problem is with identifying the keys and values or if it is the syntax. Is there away to view the raw json data echoed by my php controller?
$.get(
"/ed/macro",
{value: singleValues},
function(data) {
$.each(data, function(key,value1){
$.each(data.value1[0], function(key,value2){
$('#stage').html("data");;
});
});
},"json");
$select = $this->getDbTable()->select();
$select->from('sub');
$resultSet = $this->getDbTable()->fetchall($select);
$data = array();
foreach ($resultSet as $row) {
$entry = new Application_Model_Subdiscipline();
$entry->setIdSub($row->idsubdiscipline)
->setSub($row->subdiscipline)
->setDescription($row->description);
$data[] = $entry;
}
return $data;
}
public function macAction()
{
$request = $this->getRequest()->getParam('value');
// acti
$sub = new Application_Model_Sub();
$fetch = $sub->fetchAll($request);
$jsonObject = Zend_Json::encode($fetch);
echo $jsonObject;
// action body
}
To view the object print_rin PHP and console.log in Javascript. Or as Sam said, after the JS has called it, look in Net to see what was sent.
Assuming that you are echoing a json string after telling your server to tell the browser it is json with header("Content-type: application/json"); your problem is probably here
$.each(data, function(key,value1){
$.each(data.value1[0], function(key,value2){
data.value1 isn't what you're dealing with there, it's value1. I'm assuming value1 IS an array, and you're picking the first element in it value1[0] to then iterate?
$.each(data, function(key,value1){
$.each(value1[0], function(key,value2){
Or maybe you're after
$.each(data, function(key,value1){
$.each(value1, function(key,value2){
Please echo the object and show it to us.
I am trying to transfer a list of data from a javascript array to a php array and I can't seem to get ajax to do the trick. Can someone show me the code on how to do this? So far here is what I have, which is just the array:
JAVASCRIPT
var dates;
// the dates array is then filled up here
// it contains information in the form {'2012-01-01', '2012-03-12', ...}
$.ajax({
type: "REQUEST",
url: "NAMEOFPHPFILE.php",
data: { sendData1 : dates },
success: function() {
alert("Attempting to transfer array -> AJAX");
}
});
var submissions;
// the submissions array is then filled up here
// it contains information in the form {int, int, ...}
// ect ......... with 3 more arrays using { sendData2 : submissions },
PHP
<?php
$bDates = $_REQUEST['sendData1'];
// need to set this array = to the JavaScript dates array
$bSubmissions = $_REQUEST['sendData2'];
// need to set this array = to the JavaScript submissions array
?>
I would prefer to use the REQUEST method to prevent information logging into the URL. This code also doesn't work when trying POST instead of REQUEST
At the very end of the .php page, I am outputting a bunch of arrays onto a CSV page where I iterate through the arrays and place their elements in the file. This already works, but I need to transfer some of these arrays from javascript to PHP so that I can spit out the data. That looks like this:
<?php
$stringData = "Dates, Number of Lines Changed, , Bug Dates, Arrivals, Fixed, Closed, Hold_";
for($i = 0; $i < sizeof($dataXAxis); $i++){
$date = substr($_REQUEST['Dates'][$i+1], 0, 24);
$stringData .= "$date, $dataYAxis[$i], , $bDates[$i], $bSubmissions[$i], $bCompletions[$i], $bDones[$i], $bRejections[$i]_";
}
echo '<BR><BR>Download Your CSV File';
?>
Why doesn't the AJAX work? The arrays appear empty...
One method would be to try sending the data in the form of JSON. Then using json_decode, you can convert it to an array. Example:
var Json = {"User1":"John", "User2":"Joe", "User3","Jerry"};
var data = "data="+Json;
hr = new XMLHttpRequest();
hr.onreadystatechange = function(){
if(hr.readyState == 4 && hr.status == 200){
console.log(hr.responseText);
}
}
hr.open("POST", "parsefile.php", true);
hr.send(data);
Then when you get the data in your PHP file it's something like:
$data = $_POST['data'];
$array = json_decode($data, true);
This all will tell php to turn our data into an assosciative array. It can then be manipulated as an assosciative array.
I was literally just working on this.
jQuery
var group_ids = $('.form-elements li').map(function(){
return $(this).data('group-id')
}).get()
$.get('{{ url('group/update_order_by') }}', {group_ids: group_ids});
PHP from the restful Laravel framework
public function get_update_order_by()
{
$group_ids = Input::get("group_ids");
$group_count = count($group_ids);
for ($i = 0; $i < $group_count; ++$i) {
$group = Group::find($group_ids[$i] );
$group->order_by = $i;
$group->save();
}
return true;
}
Raw PHP (ugh...)
$group_ids = $_GET("group_ids");
$group_count = count($group_ids);
for ($i = 0; $i < $group_count; ++$i) {
echo $group_ids[$i];
}
return true;
The simply convert an array to string
var data = [1,2,"hello"];
var data_str = data.join(",");
and afterwards convert the string to array in php:
$array = explode(",", $_REQUEST["data"]);
In PHP, the REQUEST expects arrays to be passed in the following format:
sendData1[]=first&sendData1[]=second&sendData1[]=third
This is automatically converted into an array:
$sendData = $_REQUEST['sendData`];
echo $sendData[0];
echo $sendData[1];
First, for the sake of simplicity, create an array holding both arrays you want to send and parse:
var request = Array(dates, submissions);
Second, make sure you're sending your request as properly formatted JSON. In addition, when testing I recommend returning the output from the remote file in your callback to see how your data was parsed. I recommend the following implementation, as well as sending via POST:
$.ajax({
type: "POST",
url: "NAMEOFPHPFILE.php",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(request),
success: function(data) {
alert(data);
}
});
In your PHP file, get you can parse the contents of the aforementioned request into an array using the following:
<?php
// convert json data read from the input stream to an array
// *note* you MUST set the true flag in the json_decode() function, otherwise it will convert the data into an object
$request = json_decode(file_get_contents('php://input'), true);
var_dump($request);
You should now get an alert containing the var_dump of the array(looks messy, I know!).
This should be enough to get you started, hope it helps!