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

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?

Related

ReferenceError while passing multiple parameters Ajax Codeigniter

I'm getting
ReferenceError: Y1ohe1oTVVG6916 is not defined
response when viewing my console. This happens while trying to pass two parameters via Ajax. Y1ohe1oTVVG6916 is the unique identifier for this input.
AJAX:
function checktickets(val)
{
var myserial = <?= $row['eventserial']?>; //this outputs the unique identifier Y1ohe1oTVVG6916
$.ajax({
type: "POST",
url: "<?php echo base_url();?>welcome/gettickets",
data:{
id:val,
evtsr:myserial
},
beforeSend :function(){
$(".numberoftickets option:gt(0)").remove();
$('.numberoftickets').find("option:eq(0)").html("Please wait..");
},
success: function (data) {
/*get response as json */
$('.numberoftickets').find("option:eq(0)").html("Select Number of Tickets");
var obj=jQuery.parseJSON(data);
$(obj).each(function()
{
console.log(data);
alert(data);
var option = $('<option />');
option.attr('value', this.value).text(this.label);
$('.numberoftickets').append(option);
});
/*ends */
}
});
}
CONTROLLER:
public function gettickets() {
$evt =$_POST['evtsr'];
$tkt =$_POST['id'];
$query = $this->db->query("SELECT * FROM events_tickets where event_serial ='$evt' AND tickets_id='$tkt'");
$data=array();
foreach($query->result_array() as $key=> $r)
{
for($i=1; $i<=$r['ticket_max_allowed_buyer']; $i++)
{
$data['value']=$i;
$data['label']=$i;
$json[]=$data;
}
}
echo json_encode($json);
}
If I remove the second parameter evtsr:myserial from ajax function and readjust my query from the controller, everything works, but I need this second parameter to be included so as to sort the selection more.
There is only one possible explanation I guess.
Try using the declaration like this :
var myserial = '<?= $row['eventserial']?>';
Please reply if it works. I'm curious whether that is the problem

Catching data on the php side from ajax

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

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).

Passing Looped Array Values From PHP to JavaScript & JQuery

I am trying to make a search box in my web application, and I used ajax post to make a request to my server. My question is:
Is it possible to send looped array values from PHP to my JavaScript?
I want to get all of the results from my server.
CLIENT SIDE: Ajax POST request
<script type="text/javascript">
$(document).ready( function() {
$.ajax({
type: "POST",
url: "searchPlaces.php",
data: { searchInput: form.searchTxtId.value },
success: function (result)
{
// Get the search result
}
});
});
</script>
SERVER SIDE (after retrieving the post from ajax, and making queries):
while ($result = mysql_fetch_assoc ($query))
{
$resultName = $result['name'];
$resultAddress = $result['address'];
}
$results = array();
while ($result = mysql_fetch_assoc ($query)) {
$results[] = $result;
}
echo json_encode(array('results' => $results));
In your success callback you can then iterate over result.results which contains an object with the column names from your query as attributes.
success: function(result) {
$.each(results, function(i, row) {
console.log(row.name, row.address);
})
}
It is also advisable to use dataType: 'json' in your $.ajax({...}); arguments to avoid unnecessary guessing of the response type.
In case you have more columns in the SQL resultset than you want to forward to the client, you could add a custom array in the loop:
$results[] = array('name' => $row['name'], 'address' => $row['address']);
yes you can you can return a json string :
$.ajax({
type: "POST",
dataType: 'json', // return type is json ;
url: "searchPlaces.php",
data: { searchInput: form.searchTxtId.value },
success: function (result)
{
$.each($result,function(index, value){
// use params
}
}
});
and on your php side you use json_encode()

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