Save an array of arrays to database - php

After lots of searching and failing after trying.. i am posting this question here..
After half part of my actual query [here][1] i am not able to save the resulting array of arrays to the database..
Initially i had an array of inputs which i turned into array of arrays of inputs now my save function looks something like this
function store()
{
foreach($post['cats'] as $cat) {
$query = 'insert into #__joomd_item_cat values('.$cat.', '.$row->id.')';
$this->_db->setQuery( $query );
if(!$this->_db->query()) {
$obj->error = $this->_db->getErrorMsg();
return $obj;
}
}
}
now, how do i modify it to get my array of arrays into database..
This function is triggered by a serialized method.. so please recheck your answers and comments
function save(task) {
var data = $jd("form[name='<?php echo $array['editform']; ?>']").serializeArray();
$jd.ajax({
url: "<?php echo $url; ?>",
type: "POST",
dataType:"json",
data: data,
beforeSend: function() {
$jd(".poploadingbox").show();
},
complete: function() {
$jd(".poploadingbox").hide();
},
success: function(res) {
savesuccess(res);
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
}
[1]: http://stackoverflow.com/questions/11583375/add-input-fields-dynamically-but-fields-are-generated-by-external-php-functions/11583597#11583597

You can serialize() it and then unserialize() it upon retrieval.

Related

How to post value from one php page to another using ajax

I am trying to post one value which I got using Jquery, so I have to pass that value to php page using ajax. but when I did this I got Undefined index data error.
Here is my code:
$("#requirementtable tbody tr").on("click", function(){
desc = $(this).closest("tr").find("td:nth-child(4)").text().trim();
$.ajax({
type:"POST",
url:"get_diagnosis.php",
data: desc,
success: function (data, textStatus, jqXHR)
{
alert(data);
},
error: function (jqXHR, textStatus, errorThrown)
{
alert("some error occured->" + jqXHR.responseJSON);
}
})
})
this is my php code:
<?php
$data = $_POST['data'];
echo $data;
?>
Check the desc variable has some value in it and you have to post data like,
data: {data:desc},
AJAX Code,
$.ajax({
type:"POST",
url:"get_diagnosis.php",
data: {data:desc},
success: function (data, textStatus, jqXHR) {
alert(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("some error occured->" + jqXHR.responseJSON);
}
});
And in PHP use isset() to prevent undefined errors like,
<?php
$data = isset($_POST['data']) ? $_POST['data'] : 'Not defined';
echo $data;
?>
If you want JSON response format then use dataType:'json' in $.ajax, and use json_encode() in PHP to respond it.
here is a simple example that contains your code and solution
//Data Object
var obj={
name:"uneeb",
city:"gujranwala",
state: "punjab"
};
//Data Object
//Ajax Request to Server
$.ajax({
type: 'post',
url: 'someFile.php',
data:object,
success: function (data) {
//do something here
}
});
//Ajax Request to Server
//PHP
echo $_POST['name']; //prints uneeb
echo $_POST['city']; //prints gujranwala
echo $_POST['state']; //prints punjab
//PHP
Replace the followings:
desc = $(this).closest("tr").find("td:nth-child(4)").text().trim();
// remove ^^^^^^^^^^ since you're currently in tr click
desc = $(this).find("td:nth-child(4)").text().trim();
And replace to:
data: desc,
With:
data: {data:desc}, //to pass data as object as you don't have serialized data
And inside your php code, you can get data using $_POST['data'].
replace this data: desc, field in your ajax to data:{data: desc},, this is the cause you are not getting data in your php code

codeigniter ajax getting the value of json from model

I am having trouble how to get the returned json from my controller to my view. The passing of the data is already okay, but i dont know how to decode or get the specific values of the json encoded.
All i want is to store my specific values of json to a variable for further use. Something like this :
$project_name = val.($json['project_name');
Here is my code from my view :
function showprojectdetails(projectSelected) {
var studentId = null;
$.ajax({
url : "<?php echo site_url('manager/projects/ProjDetails/')?>/" + projectSelected,
type: "GET",
dataType: "JSON",
success: function(data) {
$json = json_decode(data, true);
alert($json['project_code'];);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
}
my Controller :
function ProjDetails($project_title) {
$data = $this->project->getProjDetails($project_title);
echo json_encode($data);
}
My model :
function getProjDetails($project_title) {
$this->db->from('project');
$query = $this->db->query('SELECT * from project where project_code = "'.$project_title.'" ');
return $query->row();
}
You dont need to decode the value in js. json_encode would convert array into json string. So what you get in view is already json. You simply needs to use it.
This will show you the json string in console.
console.log(data)
use
data['project_code']
You should combine PHP function
json_encode($your_json_string);
with JS
JSON.parse(response);
As in:
function showprojectdetails(projectSelected) {
var studentId = null;
$.ajax({
url : "<?php echo site_url('manager/projects/ProjDetails/')?>/" + projectSelected,
type: "GET",
dataType: "JSON",
success: function(data) {
var json = JSON.parse(data);
//do the magic you wanted to do like alert(json);
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
}

Success function does not return data using ajax

The success function does not give results. How do I solve this?
I have the following code
function fun()
{
var list_target_id = 'year';
$.ajax({
url: '://localhost/htdocs/cscart_mutli_car/index.php?dispatch=drill.drill',
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
}
if ($mode == 'drill')
{
$id = 166;
$arr = array('category_id' = > 167, 'category' = > 'computers');
echojson_encode($arr);
exit;
}
Here in this Ajax I get the success alert. But it does not provide any results. How do I solve this?
The data which is returned in the success handler is an Object.The alert will alert the string representation of the Object i.e. data.toString() which is [Object object]
You can get required things from data by calling properties from data object like this.
alert(data.category_id);
and
alert(data.category);

How to request an array of PHP objects from jQuery Ajax?

I want to pass through an array of "Blocks" with Ajax. I created "Blocks" with a PHP class: I know how to pass an array with numbers, with JSON, but I dont know how to pass an array with objects.
Will I have to recreate a class in Javascript that mimiks the "Blocks" class and then pass every value through?
class RequirementsEntity {
public $num;
public $name;
function __construct($num, $field, $name, $desc, $bool) {
$this->num = $num;
$this->name = $name;
My code for PHP:
$result = [];
while ($row = mysql_fetch_array($query)) {
$num = $row[0];
$name = $row[1];
$ablock = new BlockEntity($num, $name);
array_push($result, $arequirement);
}
echo json_encode($result);
My code for jQuery:
$('#selProgram').on('change', function() {
var id = this.value;
if (id != "None") {
$.ajax({
type: "POST",
url: "assets/php/fetch_req.php",
data: "id="+id,
datatype: "json"
success: function(data) {
alert(data);
GenerateRequirements(data, 1);
}
});
}
});
From the php.net docs
The JSON standard only supports these values when they are nested inside an array or an object.
json_encode turns the variables from an object into JSON variables, so if you save the name and number in the BlockEntity object they would show up.
With the help of the responses, if anyone in the future has the same issue, you should:
Call Ajax with a parameter data-type: "json", and making sure to parse the data after you receive it:
$('#selProgram').on('change', function() {
var id = this.value;
if (id != "None") {
$.ajax({
type: "POST",
url: "assets/php/fetch_req.php",
data: "id="+id,
datatype: "json",
success: function(data) {
JSON.parse(data)
}
});
}
});
Also, encode into JSON when sending with php:
echo json_encode($result);
Thanks!
This helped a lot How to return an array from an AJAX call?

Multi Delete using checkbox

I am learning Cakephp and I've been trying to delete multiple (checked) record using checkbox, but still not success. here's my jQuery :
var ids = [];
$(':checkbox:checked').each(function(index){
ids[index] = $(this).val();;
alert(ids[index]);
});
//alert(ids);
var formData = $(this).parents('form').serialize();
$.ajax({
type: "POST",
url: "tickets/multi_delete",
data:"id="+ids,
success: function() {
alert('Record has been delete');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown);
}
});
and here is code in controller :
function multi_delete() {
$delrec=$_GET['id'];
//debuger::dump($del_rec);
foreach ($delrec as $id) {
$sql="DELETE FROM tickets where id=".$id;
$this->Ticket->query($sql);
};
}
anybody will help me please. thank
you could try a .join(',') on the array of IDs and then an explode() on the server side to get the array of IDs passed to the script.
e.g.
var idStr = ids.join(',');
pass it (idStr) to the ajax call
$.ajax({
type: "POST",
url: "tickets/multi_delete",
data: {id:idStr},
//more code cont.
on the server side:
$ids = explode(',',$_POST['ids']);
OR
check the jquery.param() function in the jquery docs. Apply and to the IDS array and then pass it to $.ajax({});
Note: You are using POST and not GET HTTP METHOD in the code you provided
use json encode and decode for serialized data transfer
Since JSON encoding is not supported in jQuery by default, download the JSON Plugin for jQuery.
Your javascript then becomes:
$.ajax({
type: "POST",
url: "tickets/multi_delete",
data: { records: $.toJSON(ids) },
success: function() {
alert('Records have been deleted.');
},
});
In the controller:
var $components = array('RequestHandler');
function multi_delete() {
if (!$this->RequestHandler->isAjax()) {
die();
}
$records = $_POST['records'];
if (version_compare(PHP_VERSION,"5.2","<")) {
require_once("./JSON.php"); //if php<5.2 need JSON class
$json = new Services_JSON();//instantiate new json object
$selectedRows = $json->decode(stripslashes($records));//decode the data from json format
} else {
$selectedRows = json_decode(stripslashes($records));//decode the data from json format
}
$this->Ticket->deleteAll(array('Ticket.id' => $selectedRows));
$total = $this->Ticket->getAffectedRows();
$success = ($total > 0) ? 'true' : 'false';
$this->set(compact('success', 'total'));
}
The RequestHandler component ensures that this is an AJAX request. This is optional.
The corresponding view:
<?php echo '({ "success": ' . $success . ', "total": ' . $total . '})'; ?>
Wish you luck!

Categories