Multi Delete using checkbox - php

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!

Related

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

Laravel 5: Returning Eloquent Model Object as an Ajax Response

I am trying to return an Eloquent Model Object as an Ajax Response that i get from search process and i want to pass it to the view.
JS
$(document).ready( function() {
$(".client_search_option").change(function(){
var selectedClientTypeVal = "";
var selectedSmsDecisionVal = "";
var selectedClientType = $('input[type=radio][name=clientType]:checked');
var selectedSmsDecision = $('input[type=radio][name=sms_decision]:checked');
if (selectedClientType.length > 0) {
selectedClientTypeVal = selectedClientType.val();
}
if (selectedSmsDecision.length > 0) {
selectedSmsDecisionVal = selectedSmsDecision.val();
}
//alert(selectedClientTypeVal);
//alert(selectedSmsDecisionVal);
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: 'http://localhost/pages/clientSearchAjax',
type: 'POST',
data: {_token: CSRF_TOKEN, selectedClientTypeVal:selectedClientTypeVal,selectedSmsDecisionVal:selectedSmsDecisionVal},
dataType: 'JSON',
success: function (data) {
console.log(data);
},
error:function(){
alert("An error has occured !");
}
});
});
});
Contoller
public function clientSearch(){
$client_option = Input::get('selectedClientTypeVal');
$sms_option = Input::get('selectedSmsDecisionVal');
if($client_option == 'all' && $sms_option == 'all'){
$ajax_clients = Client::with('clientType')->paginate(5);
}else{
$ajax_clients = Client::with('clientType')->where('clienttype_id', $client_option)->where('send_sms', $sms_option)->paginate(5);
}
return $ajax_clients->toJson();
}
I am sure that $ajax_client object is not null, i test it and i am able to get data from database but when i want to pass it to the view(or console) it shows up like undefined. How can pass it to the view(or console) and get the values of model's columns. Any help would be appreciated.
Try replacing
return $ajax_clients->toJson();
with
return $ajax_clients;
Laravel automatically converts Eloquent objects to JSON, moreover it will set content type header to application/json, which is something you don't do in your code and what might cause the issues you describe.

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?

How to handle json response from php?

I'm sending a ajax request to update database records, it test it using html form, its working fine, but when i tried to send ajax request its working, but the response I received is always null. where as on html form its show correct response. I'm using xampp on Windows OS. Kindly guide me in right direction.
<?php
header('Content-type: application/json');
$prov= $_POST['prov'];
$dsn = 'mysql:dbname=db;host=localhost';
$myPDO = new PDO($dsn, 'admin', '1234');
$selectSql = "SELECT abcd FROM xyz WHERE prov='".mysql_real_escape_string($prov)."'";
$selectResult = $myPDO->query($selectSql);
$row = $selectResult->fetch();
$incr=intval($row['votecount'])+1;
$updateSql = "UPDATE vote SET lmno='".$incr."' WHERE prov='".mysql_real_escape_string($prov)."'";
$updateResult = $myPDO->query($updateSql);
if($updateResult !== False)
{
echo json_encode("Done!");
}
else
{
echo json_encode("Try Again!");
}
?>
function increase(id)
{
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
success: function (response) {
},
complete: function (response) {
var obj = jQuery.parseJSON(response);
alert(obj);
}
});
};
$.ajax({
type: 'POST',
url: 'test.php',
data: { prov: id },
dataType: 'json',
success: function (response) {
// you should recieve your responce data here
var obj = jQuery.parseJSON(response);
alert(obj);
},
complete: function (response) {
//complete() is called always when the request is complete, no matter the outcome so you should avoid to recieve data in this function
var obj = jQuery.parseJSON(response.responseText);
alert(obj);
}
});
complete and the success function get different data passed in. success gets only the data, complete the whole XMLHttpRequest
First off, in your ajax request, you'll want to set dataType to json to ensure jQuery understands it is receiving json.
Secondly, complete is not passed the data from the ajax request, only success is.
Here is a full working example I put together, which I know works:
test.php (call this page in your web browser)
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
// Define the javascript function
function increase(id) {
var post_data = {
'prov': id
}
$.ajax({
'type': 'POST',
'url': 'ajax.php',
'data': post_data,
'dataType': 'json',
'success': function (response, status, jQueryXmlHttpRequest) {
alert('success called for ID ' + id + ', here is the response:');
alert(response);
},
'complete': function(jQueryXmlHttpRequest, status) {
alert('complete called');
}
});
}
// Call the function
increase(1); // Simulate an id which exists
increase(2); // Simulate an id which doesn't exist
</script>
ajax.php
<?php
$id = $_REQUEST['prov'];
if($id == '1') {
$response = 'Done!';
} else {
$response = 'Try again!';
}
print json_encode($response);

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

Categories