codeigniter ajax getting the value of json from model - php

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');
}
});
}

Related

CodeIgniter unable to get Ajax data into variable

I have an Ajax post from a js file. This all works, but I am not able to set data to a variable and echo this to the screen.
I guess I do not know how to set class variables?
get Ajax code:
public function get_info()
{
// $test = $this->input->post();
var_dump($this->input->post());
$original_property_text = $this->input->post('original_property_text');
// set_ajax($original_property_text);
//$new_property_text = $this->input->post('new_property_text');
//return $test;
}
class variables and constructor:
class Users extends CI_Controller{
// gobal vars
var $new_property_text = '';
var $original_property_text = '';
var $changes = array();
function __construct() {
parent::__construct();
//$changes[] = $this->get_info();
}
*** edit *****
ajax code:
$.ajax({
url: base_url + 'users/get_info',
type: 'POST',
data: {
'original_property_text': $original_property_text,
'new_property_text': $new_property_text
},
success: function(data){
alert(data); // for testing
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
Quick answer, use this in your PHP :
public function get_info()
{
// better to use json when you need to return array
header('Content-Type: application/json');
echo json_encode( $this->input->post() );
exit();
}
In your ajax code (using jQuery framework) :
// call your controller in ajax
$.post('yourUrlHere', $('#yourForm').serialize(),
function(data) {
console.log(data);
// you manipulate json, so you can use : alert(data.property);'
}, 'json');
'$' defines variable so convert your php value to javascript object.
data: {original_property_text: '<?=$original_property_text?>', new_property_text: '<?=$new_property_text?>'},
Or,
var original_property_text = '<?=$original_property_text?>';
var new_property_text = '<?=$new_property_text?>';
var base_url = '<?=base_url();?>';
$.ajax({
url: base_url + 'users/get_info',
type: 'POST',
data: {original_property_text: original_property_text, new_property_text: new_property_text},
success: function(data){
alert(data); // for testing
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus, errorThrown);
}
});
And Get Using Your get function
print_r($_POST);exit

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

jquery ajax sending json to php error

Okay so here is my ajax request:
$("#scoreForm").submit(function(e){
e.preventDefault();
var nickName = $('#nickName').val();
var gameScore = parseInt($('#gameScore').text());
var result = { 'result' : '{ "nick":"'+nickName+'", "score":'+gameScore+' }' };
//var result = { "nick":nickName, "score":gameScore };
$.ajax({
url: "http://localhost:8888/snake/addScore.php",
type: "POST",
data: result,
//dataType: "jsonp",
success: function(data){
alert("siker");
},
error: function(jqXHR, textStatus, errorThrown) {
alert("bukta " + textStatus);
//console.log(data);
}
});
return false;
});
and my php process code:
$json_decoded = json_decode($_POST['result'],true);
//$nick = $_GET['nick'];
//$score = $_GET['score'];
$mysqli = new mysqli("localhost", "root", "root", "snake",8889);
//$mysqli->query("INSERT INTO scores(nickName,score) VALUES('".$nick."', ".$score.")");
$mysqli->query("INSERT INTO scores(nickName,score) VALUES('".$json_decoded['nick']."', ".$json_decoded['score'].")");
echo "true";
Now i got the data inserted into the database, but ajax still firing error event. i read that if i set the dataType to jsonp it will go trough , but then i get parse error, how do i get past that?
Wehn you access the $_POST variables in your php script, you need to refer to them the way they are packaged with the JSON object:
$_POST['nick']
$_POST['score']
If you want to refer to the items as $_POST['result'] and use your json decoding approach, youll need to package it this way:
var result = { result : { "nick":nickName, "score":gameScore } };

Save an array of arrays to database

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.

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