ReferenceError while passing multiple parameters Ajax Codeigniter - php

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

Related

How to pass variables in url using codeigniter?

I am passing multiple variables like window.location.href="<?php echo base_url(); ?>search?result="+state1+"&c="+city1; instead of window.location.href="<?php echo base_url(); ?>search/"+state1+"/"+city1;
Now, the problem is when I define route i.e. $route['search?(:any)'] = "test/search?$1"; after a click on submit button then it shows an error on search page and print nothing. So, How can I resolve this issue? Please help me.
view:
<script>
$(".submit").click(function(){
state1 = $("#state1").val();
city1 = $(".city1").val();
window.location.href="<?php echo base_url(); ?>search?result="+state1+"&c="+city1;
});
</script>
controller:
public function search($raw)
{
echo $raw;
}
config/route.php
$route['search?(:any)'] = "test/search?$1";
Thank You
Your routing is wrong. No need to route the url for access the $_GET values.
Try below code.
Change $route['search?(:any)'] = "test/search?$1"; to $route['search'] = "test/search";
To get it values:
$this->input->get('result');
$this->input->get('c');
Try this,
POST:
$(".submit").click(function(){
var state1 = $("#state1").val();
var city1 = $(".city1").val();
$.ajax({
beforeSend: function () {
},
complete: function () {
},
type: "POST",
url: "<?php echo site_url('controller/cmethod'); ?>",
data: ({state: state1 ,city: city1}),
success: function (data) {
}
});
});
GET:
$(".submit").click(function(){
var state1 = $("#state1").val();
var city1 = $(".city1").val();
$.ajax({
beforeSend: function () {
},
complete: function () {
},
type: "GET",
url: "<?php echo site_url('controller/cmethod/'); ?>"+state1+"/"+city1 ,
success: function (data) {
}
});
});
PHP:
POST
function search(){
echo print_r($_POST);die;
}
GET
function search($state,$city){
echo $state;
echo $city;
die;
}
Currently what you are doing is sending $_GET Data to the controller, you will need to access the data by using
$this->input->get();
It is an array so you will automatically get all the variables you've sent.
Alternatively you can send the data via segments as CI3 is designed to work with. In your controller you can pass the parameters as arguments to the function. e.g
function search($param1,$param2,$param3){
}
Using this method this information can then be access by using your site URL plus the segment of data.
www.test.com/index.php/controller/param1/param2
You will also need to change your JS code to
window.location.href="<?php echo base_url(); ?>search/" + state1 + "/" + city1;
Your trying to use Get method values like Url parameter,
Please try this code
Jquery Code
$(".submit").click(function(){
state = $("#state").val();
city = $(".city").val();
window.location.href="<?php echo base_url(); ?>search?state="+encodeURIComponent(state)+"&city="+encodeURIComponent(city);
});
Route
$route['search'] = "test/search";
Controller
public function search()
{
$state = $this->input->get('state');
$city = $this->input->get('city');
}

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?

Why is this returning me 'undefined' [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 10 years ago.
Trying to run a script, (test.al();) and inside test.al, its called getcrypt.php();, the php script is on a webserver, and it is working. Currently, these are my scripts
JS
var getcrypt = {
php: function () {
$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
return v;
}
});
}
}
var test = {
al: function () {
a = getcrypt.php();
alert(a);
}
}
PHP
<?php
$id = $_POST['id'];
if ('getit' == $id){
$value = 'VALUE';
echo $value;
}else{
echo 0;
}
?>
In this way, it will show an alert with 'unidefined', and if i add a alert(v); right before return v, it will show me 'VALUE', but not able to use it outside the variable...
var getcrypt = {
php: function () {
$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
alert(v);
return v;
}
});
}
}
This will give me an alert with the correct value (AFTER THE 'undefined')
This is because of the asynchronous call you're making. The return is only for the success function and not for the php function.
To get the value out you would need to write:
var value;
var getcrypt = {
php: function (callback) {
$.ajax({
url: "",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
alert(v);
callback(v);
}
});
}
}
getcrypt.php(function(v) {
alert(v);
// This happens later than the below
value = v;
});
// The below will still not work since execution has already passed this place
// alert will still return undefined
alert(value);
The problem is jQuery ajax works with callbacks and does not work with return value's so you need to add an callback to your getcrypt function so say
var getcrypt = {
php: function (callback) {
$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
callback(v);
}
});
}
}
so now if you call
getcrypt.php(function(returnVar){
alert(returnVar)
});
you will get an alert with VALUE
$.ajax returns immidiately (well, almost :)) upon calling, before the response is received. You should rewrite your code to accomodate to this fact, something like this;
var getcrypt = {
php: function(){
$.ajax({
//..other params ..//
success: function(msg){
var v = msg.match(/^.*$/m)[0];
alertResponse(v);
}
});
},
alertResponse: function(processedResponse) {
alert(v);
}
}
var test = {
al: function(){
getcrypt.php();
}
}
If you need your response in test object, you move alertResponse to that object and call it from success method. I think this tutorial might be useful for you to learn javascript event-driven programming model.
$.ajax calls are async. So what you get is the return value of $.ajax (when the request is sent, before a response is received). It is only when the browser receives a response to the ajax call that the success callback is run, as a seerate process from the $.ajax call. In other words the return value of $.ajax will always be null. I'm not sure it's possible to do anythging with the return value of the success callback, you need to put your logic (or a call to another function with the logic) in the success callback itself, in the same way you did with the alert in your final example

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!

Am i passing the value correctly to my controller from jquery?

I am doing a delete on a table using jquery,
$('table#chkbox td a.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().attr('id');
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "<?php echo base_url().'index.php/libraryController/librarydelete' ?>",
data: { 'id': id },
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
}
});
}
});
I am getting the id value correctly but my data parameter doesn't get passed to my controller,
function librarydelete($id)
{
$del = $id;
echo $del;
$this->librarymodel->deletebook_issue($id);
$this->session->set_flashdata('response','Deleted successfully');
redirect('libraryController/loadmagazinedetails');
}
Any suggestion...
I am getting the error,
Missing argument 1 for libraryController::librarydelete() and Undefined variable: id
Your are posting the data, so you can get the id like this:
function librarydelete()
{
$del = $_POST['id'];
echo $del;
$this->librarymodel->deletebook_issue($_POST['id']);
$this->session->set_flashdata('response','Deleted successfully');
redirect('libraryController/loadmagazinedetails');
}
Looks like you are using codeigniter, so this would be even better:
$del = $this->input->post('id');
Change id to $id in controller function parameter
means, your function should be
function librarydelete($id)
{
$del = $id;
echo $del;
$this->librarymodel->deletebook_issue($id);
$this->session->set_flashdata('response','Deleted successfully');
redirect('libraryController/loadmagazinedetails');
}
Perhaps it is because you are using the variable name 'data' twice. Try renaming var data to var mydata.
The way you are passing data is wrong. This is the way you should be setting data.
var data= {id: id };
in your case let me not use the variable in the post action and show you how its done.
$.ajax(
{
type: "POST",
url: "<?php echo base_url().'index.php/libraryController/librarydelete' ?>",
data: {id:id},
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
}
});
Edit: After you modified your code to pass data the right way.
Hey I have not followed MVC framwework in php. but since you are doing a post on the action you can always get the data the following way:
$id=$_POST['id']
and then you can use this id.
Also if you still want to use the function:
function librarydelete($id)
{
$del = $id;
echo $del;
$this->librarymodel->deletebook_issue($id);
$this->session->set_flashdata('response','Deleted successfully');
redirect('libraryController/loadmagazinedetails');
}
just modify the uri action to existingurl+/ i.e append the id to the end and in your route map (if there exists something like this in php in .nets implementation there is 1) just add that route.

Categories