A PHP function should return a specific number and stored it to the variable data[i]. How to access a PHP function within a $.getJSON function? I used a PHP CodeIgniter framework. Thank you!
`$.getJSON("<?php echo site_url('some_contoller/some_funcion');?>", function (data) {
for (var i = 0; i < data.length; i++) {
var data[i] = "<?php echo $this->some_PHP_function($with_parameter)?>";
}
}`
This is my PHP function:
public function get_report_pictures($report_id) {
$this->db->select('*');
$this->db->where('report_id', $report_id);
$query = $this->db->get('report');
$data = $query->result();
return $data;
}
in javascript file (*.js) you can't use php code.
you can use $.ajax() to call function in controller .
$.ajax({
type: "post",
url: "some_contoller/some_funcion",
dataType :'json',
success: function(response){
if(response.status=='success'){
response.data.forEach( function (item)
{
var x = item.number;
console.log(x);
});
}
},error:function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
});
in function you mentioned 'some_funcion'
echo json_encode(array(
'status'=>'failed',
'data' => 'number you say ')
);
exit();
it's my solution.i hope so that's worked.
Related
I'm using CodeIgniter to access the database, but everytime I run the code it gets an internal error. This is my jQuery code:
function showCadeiras() {
$.ajax({
type: "POST",
url: base_url + "api/teacher/getCadeiras",
data: {id: localStorage.user_id},
success: function(data) {
for(var i = 0; i < data.cadeiras_id.length; i++) {
var cadeira_id = data.cadeiras_id[i].cadeira_id;
$.ajax({
type: "POST",
url: base_url + "api/teacher/getCadeiraInfo",
data: {id: cadeira_id},
success: function(data) {
console.log(data);
},
error: function(data) {
console.log("error");
}
})
}
},
error: function(data) {
console.log(data);
}
});
}
Here is the code inside the Controller:
public function getCadeiras() {
$user_id = $this->post('id');
$this->load->model('UserModel');
$data["cadeiras_id"] = $this->UserModel->getCadeiras($user_id);
$this->response($data, parent::HTTP_OK);
}
public function getCadeiraInfo(){
$cadeira_id = $this->post('cadeira_id');
$this->load->model('UserModel');
$data["info"] = $this->UserModel->getCadeiraInfo($cadeira_id);
$this->response($data, parent::HTTP_OK)
}
Lastly, the Model code:
public function getCadeiras($id) {
$this->db->select("cadeira_id");
$this->db->where(array('user_id =' => $id));
$query = $this->db->get('professor_cadeira');
return $query->result_array();
}
public function getCadeiraInfo($id) {
$query = $this->db->get_where('cadeira', array('id =' => $id));
return $query->result_array();
}
Everytime I comment the second function (getCadeiraInfo) the code works without a problem, however it doesn't work with the second function. They are written in a similar way, I don't understand the error.
i have to get the html reply of two php function with AJAX
Here my code
Home.php
<script>
$( document ).ready(function(){
var parameter = {
"mynumber" : $('#mynumber').val()
};
$.ajax({
data: parameter ,
url: 'script.php',
type: 'post',
dataType: 'json',
beforeSend: function () {
$("#loading").show();
},
success: function (response) {
$("#loading").hide();
$("#div1").html(response.reply1);
$("#div2").html(response.reply2);
},
}); });
</script>
And script.php
function loopone(){
for($a=0;$a<10;$a++){
?><div id="mydiv"><?php echo $a;?></div>
}
}
function casetwo(){
if($a<>$g){
?><div id="mydiv2"><?php echo $a;?></div>
}
}
$prew1=file_get_contents(loopone());
$prew2=file_get_contents(casetwo());
$reply1=prew1;
$reply2=prew2;
echo json_encode(array("reply1"=>$reply1, "reply2"=>$reply2));
what's wrong here ? I can not see the results.
file_get_contents() is for reading a file or URL into a string. You don't need to use these if you're creating the content in your script. Just have your functions return strings.
function loopone() {
$result = "";
for (a = 0; $a < 10; $a++) {
$result .= "<div class='mydiv'>$a</div>";
}
return $result;
}
function casetwo() {
global $a, $g;
if ($a != $g) {
return "<div id='mydiv2'>$a</div>";
} else {
return "";
}
}
$prew1 = loopone();
$prew2 = casetwo();
echo json_encode(array("reply1"=>$prew1, "reply2"=>$prew2));
I changed id="mydiv" to class="mydiv" because IDs are supposed to be unique, you shouldn't return the same ID in a loop.
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
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!
updated:
i use this:
$.getimagesarr = function(operation) {
return $.ajax({
type: 'POST',
url: 'operations.php',
data: {'operation':operation},
async: false
}).responseText
}
var jsonstring = $.getimagesarr('getimg');
var data = (new Function("return " + jsonstring))()
if (data){
....
}
old:
i want to pass a php aray to jQuery:
$.getimagesarr = function() {
$.getJSON('operations.php', {'operation':'getimglist'}, function(data){
var arr = new Array();
arr = data;
return arr;
});
}
var data = $.getimagesarr();
if (data){
jQuery.each(data, function(i, val) {
....
});
}
it return undefined
in php i have this:
function getimglist(){
$results = $_SESSION['files'];
echo json_encode($results);
}
it is possible?
The return arr; line isn't going to return a value for the $.getimagesarr function. It's going to execute asynchronously, after the $.getJSON() call has finished. You should move the bottom area of code to within the success event handler for the $.getJSON() call:
$.getimagesarr = function() {
$.getJSON('operations.php', {'operation':'getimglist'}, function(data){
if (data){
jQuery.each(data, function(i, val) {
....
});
}
});
};