Catching data on the php side from ajax - php

I'm confused. How do I catch the value on the php side after passing the data from ajax. Originally, I had data put into an object Array. When passing data through Ajax, do I pass it as a stringArray or as an ObjectArray? Does that mean I need to stringify() it?
I'm doing this in MVC so that's why it's /test in the url
<script>
var objectArray = [{"name":"Robert", "type": "male"}, {"name":"Jane", "type": "female"}]
var stringArray = JSON.stringify(objectArray);
$.ajax({
type: 'POST',
url: '/test',
data: stringArray, //do I pass in objectArray or stringArray here?
success: function(response)
{
alert(response);
}
});
</script>
test.php
<?php
public function test()
{
$var = '';
foreach($_POST['name'] as $value)
{
$var .= ' ' . $value;
}
return $var; // It says I'm getting unidentified index $_POST['name']
}
?>

PHP expects key=value pairs in GET/POST. You're passing in a monolithic string with no name, so PHP no key available to put that string into $_POST
Try
data: {foo: stringArray}
and
$_POST['foo']
instead.

You should give a key for the value that you are trying to send to the backend and you don't really need to send it as a string. Like that:
$.ajax({
type: 'POST',
url: '/test',
data: {users: objectArray },
success: function(response)
{
alert(response);
}
});
Then, in your backend you should access the key you've sent. Like that:
public function test()
{
$var = '';
foreach($_POST['users'] as $value) // use the right key
{
$var .= ' ' . $value['name'];
}
return $var;
}

Related

Codeigniter, Ajax: Pass html string from view to controller

I'm trying to pass a long Html string from a view to a controller using an ajax call, so I can pass it further to another view.
Markup:
<a id="openPDF">Save as PDF</a>
JS:
$('#openPDF').click(function(){
var htmlText = $( "div.modal" ).html(); //grab the html
var dataToSend = JSON.stringify("{strData : '" + htmlText + "' }");
console.log(dataToSend ); // contains the json
$.ajax({
url: "/dashboard/pdf",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: dataToSend
success: function (msg) { alert(msg.d); },
error: function (type) { alert("ERROR!" + type.responseText); }
});
});
Controller:
public function pdf(){
$data['htmlString'] = json_decode($this->input->post('strData'));
$this->load->view('pdf', $data);
}
My ajax call doesn't work because when a click the #openPDF button i get the alert error:
ERROR! NULL
What am I doing wrong?
Are you setting your headers properly before writing the output?
Controller:
public function pdf() {
$data['htmlString'] = json_decode($this->input->post('strData'));
$viewString = $this->load->view('pdf', $data, true); // this returns view as string rather than outputting it
header('Content-Type: application/json');
echo json_encode(['viewString' => $viewString]);
}
In client-side js, you can pass this success function to $.ajax()
success: function (response) {
if ('undefined' !== typeof response.viewString) {
// append view to concerned element
$('#viewTarget').append(response.viewString);
} else {
console.log('response did not contain viewString');
}
},
I hope this helps.
Also:
Navigate directly to the url (the one you are sending an ajax request for) in your browser and see if you get a valid json output.

Pass angularjs value to PHP variable

I am starting with angularjs with ngStorage. I can save and display data successfully.
I display value as before
{{myobj.session}}
I would like to pass whatever stored value into php variable. Shown below is my imaginary logic and I know thats not gonna work. My question is how to assign such value into PHP variable in a correct manner?
<?php
$name = {{myobj.session}}
?>
You can use this angular variable: students.tiffen_type
PHP variable : $value
<?php
$value = "{{ students.tiffen_type }}";
?>
You can do a ajax request like this:
$http({
url: "urltopost.php",
method: "POST",
data: {
data: variable
}
}).success(function(response) {
console.log(response);
});
And on the backend you can get the variable like this
<?php
$request = json_decode( file_get_contents('php://input') );
$variable = $request->data
From there you can do everything you want with that variable, still I'm not sure what are you trying to achieve.
You can't assign directly angularjs value to php variable, use the following method it will help you
$http({
method: "POST",
url: "test.php",
data: {
data: postvariable
}
}).success(function(response) {
console.log(response); //get the echo value from php page
}).error(function(response) {
console.log(response);
});
test.php
<?php
$data = json_decode(file_get_contents("php://input"));
echo $data->data;
?>
send.js
$http({
method: "post",
url: "ajax/request.php",
data: {
angular_var: $scope.angular_var // $scope.angular_var is angular variable e.g. ng-model="angular_var"
}, headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function (data) {
console.log(data)
});
ajax/request.php
$request_arr = json_decode( file_get_contents('php://input') );
$angular_var = $request_arr->angular_var;

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?

Access php function data via ajax

I have this php function inside a class the returns json data
function getPhotoDetails( $photoId ) {
$url = $this::APP_URL . 'media/' . $photoId . $this::APP_ID;
return $this->connectToApi($url);
}
and this ajax request
function getPhotoDetails( photoId ) {
$.ajax({
type: "GET",
cache: false,
url: 'index.php',
success: function (data) {
console.log(data);
}
});
}
The question is how I can call the php function to get the json data.
Solution:
A big thanks to all of you guys and thanks to Poonam
The right code
PHP:
I created a new object instance in php file
$photoDetail = new MyClass;
if(isset($_REQUEST['image_id'])){
$id = $_REQUEST['image_id'];
echo (($photoDetail->getPhotoDetails($id)));
}
JavaScript
function getPhotoDetails( photoId ) {
$.ajax({
type: "GET",
cache: false,
url: './instagram.php?image_id=' + photoId,
success: function (data) {
var data = $.parseJSON(data);
console.log(data);
}
});
}
Try with setting some parameter to identify that details needs to send for e.g assuming photoid params needed for function
function getPhotoDetails( photoId ) {
$.ajax({
type: "GET",
cache: false,
url: 'index.php?sendPhoto=1&photoid=23',
success: function (data) {
console.log(data);
}
});
}
and then on index.php check (You can make check for photoid whatever you need as per requirement)
if(isset($_REQUEST['sendPhoto'])){
$id = $_REQUEST['photoid'];
return getPhotoDetails($id);
}
setup a switch-case. Pass the function name as GET or POST variable such that it calls the php function
You need a file which calls the PHP function. You can't just call PHP functions from Ajax. And as pointed out by Tim G, it needs to use the proper header, format the code as JSON, and echo the return value (if the function is not already doing these things).

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