jQuery JSON not passing data to Ci properly - php

The script below works as far as i can tell:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#add').bind('keypress', function(e) {
if(e.keyCode == 13){
var add = $("#add").val();
$.ajax({
type: "POST",
dataType: "JSON",
url: "<?php echo site_url("home/jsonAddData"); ?>",
data: add,
json: {title_posted: true},
success: function(data){
if(data.title_posted == true) { // true means data was successfully posted.
$("#success").append("Success").fadeIn(400);
} else if(data.title_posted == false) { // false means data failed to post.
$("#success").append('Failure').fadeIn(400);
}
}
});
}
});
});
</script>
The problem I'm experiencing with the code below is that the mysql insetion query just wont work. It creates the row in the table and auto-increments but for some odd reason it wont pass the 'var add' in the Javascript above to the Ci script below and perform an insertion in the db. Any thoughts or ideas?
<?php
class home extends CI_Controller {
function __construct() {
parent::__construct();
}
function index() {
$data = array();
$data['lists'] = $this->displayList();
$this->load->view('home', $data);
}
function displayList() {
$str = '';
$query = $this->db->query("SELECT * FROM data");
foreach ($query->result() as $row) {
$b = '<input name="completed" type="checkbox" />';
$a = $row->title . "<br>";
$str .= $b.$a;
}
return $str;
}
function jsonAddData() {
if($this->input->is_ajax_request()) {
$title = $this->input->post('title');
$query = $this->db->query("INSERT INTO data (title) VALUES ('$title')");
header('Content-type:application/json');
if($query) echo json_encode(array('title_posted' => true));
else echo json_encode(array('title_posted' => false));
}
}
}
?>

In
$.ajax({
...
data: {title: add}
Not just a string

Related

How to get the values from multiple form in one post request using laravel?

Ajax:
<script type="text/javascript">
$(document).ready(function () {
$('#finalSubmit').click(function() {
var form1 = $('#priceform').serialize();
var form2 = $('#formdescription').serialize();
var form3 = $('#additionaldescription').serialize();
//var form4 = new FormData($("#imagesform").get(0));
//alert(form4);
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN':
$('meta[name="_token"]').attr('content') }
});
$.ajax({
url :"{{url('/dbvalue')}}",
type: 'POST',
data: {form1: form1, form2: form2,form3: form3},
dataType:'json',
success:function(data){
alert(data);
}
});
});
});
</script>
This is my ajax code.Here I'm passing the values of four forms
Controller:
public function finalSubmit(Request $request)
{
var_dump($_POST);
$var1 = $this->addPriceDetails1($request->form1);
$var2 = $this->addProductDetails1($request->form2);
$var3 = $this->addAdditionalInformation1($request->form3);
//$var4 = $this->addImages($imagesform);//you dont't have
$imagesform
return response()->json(["response"=>"success"]);
}
Eg. for function:
public function addPriceDetails1($request)
{
$priceInfo = new priceInfo ;
$priceInfo->id=$this->getpriceDetailsId();
$priceInfo->SKUID=$request->input('skuid');
echo($priceInfo->id);
//return $request->all();
}
Also here when I'm trying to echo the values of $priceInfo->Id it echoes '0'.I don't know why
With this I'm getting FatalErrorException..call to member function input() on string
var_dump($_POST) gives me an array of forms values.
UPdate:
public function getpriceDetailsId()
{
$id = mt_rand(1000000, 9999999);
$id="PD".$id;
$count=priceInfo::select('id')->where('id',$id)->count();
if($count==0)
{
return $id;
}
else
{
$this->getpriceDetailsId();
}
}
here is my function for getpriceDetailsId().
You get that error because your input query when you access as object when it is string, you can convert your query string to an array to access like so.
public function addPriceDetails1($request)
{
parse_str($request, $input);
$priceInfo = new priceInfo ;
$priceInfo->id = $this->getpriceDetailsId();
$priceInfo->SKUID = $input['skuid'];
echo($priceInfo->id);
}
Hope this help

Codeigniter: Ajax data is printing in log but not working in function

I'm getting data through ajax who's function is:
<script type="text/javascript">
// Ajax post
$(document).ready(function()
{
$("#submit").click(function(event)
{
event.preventDefault();
var hiddenValue = $("#hiddenValue").val();
alert(hiddenValue);
var update_name = $("input#update_name").val();
// pop up Name Entered
alert(update_name);
jQuery.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" + "seasons/update_season",
data: {
hiddenValue : hiddenValue,
update_name: update_name
},
success: function(res)
{
console.log(res);
// window.alert("i got some data ");
if (res)
{
jQuery("div#result").show();
}
},
fail: function(res)
{
console.log(res);
}
});
});
});
The Controller function i have:
public function update_season()
{
$session_id = $this->session->userdata('id');
if (isset($session_id))
{
// print_r($_POST);
// die();
$update_id = $this->input->post('hiddenValue');
$update_name = $this->input->post('update_name');
$arr = array(
'id' => $update_id,
'name'=> $update_name);
//This prints empty data
// print_r($arr);
// die();
$result = $this->model_season->edit_season($arr);
// $result = $result->row();
if ($result)
{
print_r($arr);
}
else
{
return FALSE;
}
}
else
{
redirect('user_authentication');
}
}
And in Model through controller i have:
public function edit_season($data)
{
// I am getting right array of name and id
print_r($data);
die();
// but get empty variable if i try to assign value to it
$name = $data['name'];
$this->db->where('seasons', array('season_id ' => $data['id']));
$query = $this->db->update('seasons',array('names ' => $data['name'] ));
if ($query)
{
return $query;
}
else
{
return FALSE;
}
}
The ajax seem to work fine as its printing the values of id and name its getting i'm not even encoding it in json, but i'm unable to get its value in separate variable. I wonder if there is any different method to get values from ajax data ?
When i let it run the whole model function without making it die i have following error:
UPDATEseasonsSETnames= NULL WHEREseasons=Array``
Like array have nothing in it
There is error in your query, you are supplying array to where condition, where it should be string,
$this->db->where('season_id ', $data['id']);
Also, it is not good to have unnecessary spaces (though CI driver internally trims all spaces) in conditions like 'season_id ' should be 'season_id'
$this->db->where('season_id', $data['id']);
$query = $this->db->update('seasons', array('names' => $data['name']));
Check driver referance here: Queries in CI
$array1= array('season_id ' => $data['id']);
$array2= array('names' => $data['name']);
$this->db->where($array1);
$query = $this->db->update('seasons',$array2);

How to test returned json result?

I have an Ajax Request that is getting data from my database, specifically two columns from it, company_id and people_id,
I need to test the result that comes from the json result, I need to check if a specific people_id exists in the result,
Here is my Ajax Request
Ext.Ajax.request({
url: 'system/index.php',
method: 'POST',
params: {
class: 'CompanyPeople',
method: 'secget',
data: Ext.encode({
people_id: Ext.getCmp('peopleGrid').selectedRecord.data.people_id
})
},
success: function (response) {
},
failure: function () {
}
});
I thought I could do this following code in the success function but it didnt work
if (data == 0) {
Ext.MessageBox.alert('Status', 'Person is not attached to anything bud!.');
}
else {
Ext.MessageBox.alert('Status', 'Person already attached to another company.');
}
Also here is my php
class CompanyPeople extends Connect {
function __construct() {
parent::__construct();
}
public function secget($vars) {
$sql = "SELECT * FROM CompanyPeople where people_id={$vars->data->people_id}";
$data = array();
$total = 0;
if ($result = $vars->db->query($sql)) {
while ($row = $result->fetch_assoc()) {
$data[] = array("people_id" => intval($row["people_id"]));
$total++;
}
$result->free();
}
echo json_encode(array("success" => true, "total" => $total, "topics" => $data));
}
}
I think something like this should work:
success: function( response ){
if(response.success === true) {
var personExist = false;
for(var i = 0; i < response.topics.lenght; ++i) {
// Your specific people_id in myValue
if(response.topics[i]['people_id'] === myValue) {
personExist = true;
break;
}
}
}
},

Asynchronously query the database by using ajax and jquery and post the result back in codeigniter View

I've struggeled alot with this .
I wanna send an ID in the CI model and get the returned value via CI controller
My view is
<script type="text/javascript">
function showsome(){
var rs = $("#s_t_item option:selected").val();
var controller = 'items';
var base_url = '<?php echo site_url(); ?>';
$.ajax({
url : base_url+ '/' + controller+ '/get_unit_item',
type:'POST',
contentType: 'json',
data: {item_id: rs},
success: function(output_string){
//$('#result_area').val(output_string);
alert(output_string);
}
});
}
</script>
My Controller method is
public function get_unit_item()
{
$received = $this->input->post('item_id');
$query = $this->units_model->get_unit_item($received);
$output_string = '';
if(!is_null($query)) {
$output_string .= "{$query}";
} else {
$output_string = 'There are no unit found';
}
echo json_encode($output_string);
}
And my model function responsible
public function get_unit_item($where){
$this->db->where('item_id',$where);
$result = $this->db->get($this->tablename);
if($result->num_rows() >0 ){
$j = $result->row();
return $j->unit_item_info ;
}
}
Html codes
<?php $id = 'id="s_t_product" onChange="showsome();"';
echo form_dropdown('product_id[]', $products, $prod,$id); ?>
I tried to use the id only but failed to fire so passing a function onchange seems to pick the item and fire
Using firebug I can see that the post request sends item_id=2 but the response length is 0 and with php result code 302
POST
RESPONSE
How can I achive this?(The model is loaded on the contructor)
Do slighly change your controller and model:
// Model
public function get_unit_item($where){
$this->db->where('item_id',$where);
$result = $this->db->get($this->tablename);
if($result->num_rows() > 0 ) {
$j = $result->row();
return $j->unit_item_info ;
}
else return false;
}
// Controller
public function get_unit_item()
{
$received = $this->input->post('item_id');
$return = array('status'=>false);
if( $query = $this->units_model->get_unit_item($received) ) {
$return['status'] = true;
// Add more data to $return array if you want to send to ajax
}
$this->output->set_content_type("application/json")
->set_output(json_encode($return));
}
Check returned values in JavaScript:
$.ajax({
url : base_url+ '/' + controller+ '/get_unit_item',
type:'POST',
dataType: 'json',
data: {item_id: rs},
success: function( response ){
if( response.status === true ) {
alert('Everything Working Fine!');
console.log( response );
}
else alert('Something went wrong in query!');
}
});
After trying various approaches I have finally found what really is the problem and i think this might be the problem for all with the 302 found error. In this project (server) there're two systems within the same root and each has got its own codeigniter files. As seen above i was using
var controller = 'items';
var base_url = '<?php echo site_url(); ?>';
url : base_url+ '/' + controller+ '/get_unit_item',
as the value for url but i tried to put the full url from the base and it worked so now it is
url: '<?php echo base_url(); ?>index.php/en/items/get_unit_item',
. I think for any one with the redirect issue the first thing to check is this

AJAX request and PHP class functions

How to call a PHP class function from an ajax call
animal.php file
class animal
{
function getName()
{
return "lion";
}
}
Then in my ajax.php file I have an ajax request, need to get values from getName function
How to do that getName() function can I do like this?
<script type=text/javascript>
$.ajax({
type: "POST",
data: {
invoiceno:jobid
},
url: "animal/getName",
beforeSend: function() {
},
dataType: "html",
async: false,
success: function(data) {
result=data;
}
});
</script>
My answer is the same as Surreal Dreams answer, but with the code.
First. Class animal is OK. Leave it like that:
animal.php
<?php
class animal
{
function getName()
{
return "lion";
}
}
Next. Create a new animalHandler.php file.
<?php
require_once 'animal.php';
if(isset( $_POST['invoiceno'] )) {
$myAnimal = new animal();
$result = $myAnimal->getName();
echo $result;
}
Finally. Change your Javascript.
<script type=text/javascript>
$.ajax({
type: "POST",
data: {
invoiceno:jobid
},
url: "animalHandler.php",
dataType: "html",
async: false,
success: function(data) {
result=data;
}
});
</script>
That's is.
You need one additional script, because your animal class can't do anything on its own.
First, in another script file, include animal.php. Then make an object of the animal class - let's call it myAnimal. Then call myAnimal->getName() and echo the results. That will provide the response to your Ajax script.
Use this new script as the target of your Ajax request instead of targeting animal.php.
OOP Currently with php:
ajax.html program(client tier) -> program.php (middle tier) -> class.php (middle tier) -> SQL call or SP (db tier)
OOP Currently with DotNet:
ajax.html program(client tier) -> program.aspx.vb (middle tier) -> class.cls (middle tier) -> SQL call or SP (db tier)
My real-life solution:
Do OOA, do not OOP.
So, I have one file per table -as a class- with their proper ajax calls, and select the respective ajax call with a POST parameter (i.e. mode).
/* mytable.php */
<?
session_start();
header("Content-Type: text/html; charset=iso-8859-1");
$cn=mysql_connect ($_server, $_user, $_pass) or die (mysql_error());
mysql_select_db ($_bd);
mysql_set_charset('utf8');
//add
if($_POST["mode"]=="add") {
$cadena="insert into mytable values(NULL,'".$_POST['txtmytablename']."')";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
};
//modify
if($_POST["mode"]=="modify") {
$cadena="update mytable set name='".$_POST['txtmytablename']."' where code='".$_POST['txtmytablecode']."'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
};
//erase
if($_POST["mode"]=="erase") {
$cadena="delete from mytable where code='".$_POST['txtmytablecode']."'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
};
// comma delimited file
if($_POST["mode"]=="get") {
$rpta="";
$cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
while($row = mysql_fetch_array($rs)) {
$rowCount = mysql_num_fields($rs);
for ($columna = 0; $columna < $rowCount; $columna++) {
$rpta.=str_replace($row[$columna],",","").",";
}
$rpta.=$row[$columna]."\r\n";
}
echo $rpta;
};
//report
if($_POST["mode"]=="report_a") {
$cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
while ($row=mysql_fetch_array($rs)) {
echo $row['code']." ".$row['name']."<br/>"; // colud be a json, html
};
};
//json
if($_POST["mode"]=="json_a") {
$cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
$result = array();
while ($row=mysql_fetch_array($rs)) {
array_push($result, array("id"=>$row['code'],"value" => $row['name']));
};
echo json_encode($result);
};
?>
Can you please mention which are you using any Framework?
You method is correct but I want to mention two things over here. First try your URL from the browser and check if its working correctly. Secondly don't use return, in *success: function(data) * data will contain only the output. so use Echo rather then return
For what it is worth, I have used a PHP proxy file that accepts an object as a post -- I will post it here. It works by providing class name, method name, parameters (as an array) and the return type. This is limited as well to only execute classes specified and a limited set of content types to return.
<?php
// =======================================================================
$allowedClasses = array("lnk","objects"); // allowed classes here
// =======================================================================
$raw = file_get_contents("php://input"); // get the complete POST
if($raw) {
$data = json_decode($raw);
if(is_object($data)) {
$class = $data->class; // class: String - the name of the class (filename must = classname) and file must be in the include path
$method = $data->method; // method: String - the name of the function within the class (method)
#$params = $data->params; // params: Array - optional - an array of parameter values in the order the function expects them
#$type = $data->returntype; // returntype: String - optional - return data type, default: json || values can be: json, text, html
// set type to json if not specified
if(!$type) {
$type = "json";
}
// set params to empty array if not specified
if(!$params) {
$params = array();
}
// check that the specified class is in the allowed classes array
if(!in_array($class,$allowedClasses)) {
die("Class " . $class . " is unavailable.");
}
$classFile = $class . ".php";
// check that the classfile exists
if(stream_resolve_include_path($classFile)) {
include $class . ".php";
} else {
die("Class file " . $classFile . " not found.");
}
$v = new $class;
// check that the function exists within the class
if(!method_exists($v, $method)) {
die("Method " . $method . " not found on class " . $class . ".");
}
// execute the function with the provided parameters
$cl = call_user_func_array(array($v,$method), $params );
// return the results with the content type based on the $type parameter
if($type == "json") {
header("Content-Type:application/json");
echo json_encode($cl);
exit();
}
if($type == "html") {
header("Content-Type:text/html");
echo $cl;
exit();
}
if($type == "text") {
header("Content-Type:text/plain");
echo $cl;
exit();
}
}
else {
die("Invalid request.");
exit();
}
} else {
die("Nothing posted");
exit();
}
?>
To call this from jQuery you would then do:
var req = {};
var params = [];
params.push("param1");
params.push("param2");
req.class="MyClassName";
req.method = "MyMethodName";
req.params = params;
var request = $.ajax({
url: "proxy.php",
type: "POST",
data: JSON.stringify(req),
processData: false,
dataType: "json"
});
Try this:
Updated Ajax:
$("#submit").on('click', (function(e){
var postURL = "../Controller/Controller.php?action=create";
$.ajax({
type: "POST",
url: postURL,
data: $('form#data-form').serialize(),
success: function(data){
//
}
});
e.preventDefault();
});
Update Contoller:
<?php
require_once "../Model/Model.php";
require_once "../View/CRUD.php";
class Controller
{
function create(){
$nama = $_POST["nama"];
$msisdn = $_POST["msisdn"];
$sms = $_POST["sms"];
insertData($nama, $msisdn, $sms);
}
}
if(!empty($_POST) && isset($_GET['action']) && $_GET['action'] == ''create) {
$object = new Controller();
$object->create();
}
?>
For every ajax request add two data, one is class name and other is function name
create php page as follows
<?php
require_once 'siteController.php';
if(isset($_POST['class']))
{
$function = $_POST['function'];
$className = $_POST['class'];
// echo $function;
$class = new $className();
$result = $class->$function();
if(is_array($result))
{
print_r($result);
}
elseif(is_string($result ) && is_array(json_decode($result , true)))
{
print_r(json_decode($string, true));
}
else
{
echo $result;
}
}
?>
Ajax request is follows
$.ajax({
url: './controller/phpProcess.php',
type: 'POST',
data: {class: 'siteController',function:'clientLogin'},
success:function(data){
alert(data);
}
});
Class is follows
class siteController
{
function clientLogin()
{
return "lion";
}
}
I think that woud be a sleek workaround to call a static PHP method via AJAX which will also work in larger applications:
ajax_handler.php
<?php
// Include the class you want to call a method from
echo (new ReflectionMethod($_POST["className"], $_POST["methodName"]))->invoke(null, $_POST["parameters"] ? $_POST["parameters"] : null);
some.js
function callPhpMethod(className, methodName, successCallback, parameters = [ ]) {
$.ajax({
type: 'POST',
url: 'ajax_handler.php',
data: {
className: className,
methodName: methodName,
parameters: parameters
},
success: successCallback,
error: xhr => console.error(xhr.responseText)
});
}
Greetings ^^

Categories