Column can not be null in ajax laravel update function - ajax

Hi guys i am sending my updated values from ajax to my update function.i am getting error as "Column cannot be null"
Here is my input which i am sending json data:
<input type="text" id="jsonData" name="jsonData">
And here is my ajax form:
function saveEditQtypeFile(edit_qtype_id)
{
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
chk_EnumValuesValidation = chkEnumValuesValidation(isSoltion, stepCount);
if(!chk_EnumValuesValidation)
{
return false;
}
else
{
// Function to push "MainArray" in current Solution
pushVarMainArrayInThisSolution(isSoltion, var_main_arr.var_arr_values);
arr = ar;
var edit_qtype_id = $('#edit_qtype_id').val();
var qtype_name = $('#qtype_name').val();
var subject_list = $('#qtype_subject_id').val();
var ddl_topic_type = $('#qtype_topic_id').val();
var qtype_option = $('#qtype_option').val();
var jasondata = $('#jsonData').val();
var sort_order = $('#sort_order').val();
var sendInfo = {
'edit_qtype_id':edit_qtype_id,
'arr':arr,
'saveEditQtypeFile':1,
'qtype_name':qtype_name,
'qtype_subject_id':subject_list,
'qtype_topic_id':ddl_topic_type,
'qtype_option':qtype_option,
'qtype_json':jasondata,
'sort_order':sort_order
};
console.log('json',jasondata);
//return false;
//var loadQtypeInfo = JSON.stringify(sendInfo);
$.ajax({
url: "/eqtype-editor/update",
type: "POST",
data :sendInfo,
contentType: "application/x-www-form-urlencoded",
success: function(response)
{
alert('Your file is updated!');
window.location.href ="/eqtype-editor";
},
error: function (request, status, error)
{
alert('problem with updating record!!!');
},
complete: function()
{}
});
}
}
and here is my controller:
public function update(Request $request, Qtype_editor $qtype_editor)
{
$qtype_editor = Qtype_editor::findOrFail($request->edit_qtype_id);
$qtype_editor->qtype_name = $request->input('qtype_name');
$qtype_editor->qtype_subject_id = $request->input('qtype_subject_id');
$qtype_editor->qtype_topic_id = $request->input('qtype_topic_id');
$qtype_editor->qtype_option = $request->input('qtype_option');
$qtype_editor->qtype_json = json_decode($request->input('jsonData'));
$qtype_editor->sort_order = $request->input('sort_order');
$qtype_editor->save();
return redirect()->route('eqtype-editor.index');
}
From ajax when i console i am getting my json data..i am getting error as qtype_json cannot be null.
Can anyone help me where i am missing it.
Thanks in advance.

You use a wrong key for your data.
Change the line in your controller:
$qtype_editor->qtype_json = json_decode($request->input('jsonData'));
to
$qtype_editor->qtype_json = json_decode($request->input('qtype_json'));
and it will work.

Related

Laravel: update function creating new record instead of updating existing one

Hi guys i am trying to update my existing record in my edit page..so when i clicked on update button it is creating new record instead of updating existing one
Here is my controller:
public function update(Request $request, Qtype_editor $qtype_editor)
{
$qtype_editor = new Qtype_editor();
$qtype_editor->qtype_name = $request->input('qtype_name');
$qtype_editor->qtype_subject_id = $request->input('qtype_subject_id');
$qtype_editor->qtype_topic_id = $request->input('qtype_topic_id');
$qtype_editor->qtype_option = $request->input('qtype_option');
$qtype_editor->qtype_json = $request->input('qtype_json');
$qtype_editor->sort_order = $request->input('sort_order');
$qtype_editor->save();
return redirect()->route('eqtype-editor.index');
}
And i have ajax call where i am updating records from ajax
Here is my ajax code
function saveEditQtypeFile(edit_qtype_id)
{
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
chk_EnumValuesValidation = chkEnumValuesValidation(isSoltion, stepCount);
if(!chk_EnumValuesValidation)
{
return false;
}
else
{
// Function to push "MainArray" in current Solution
pushVarMainArrayInThisSolution(isSoltion, var_main_arr.var_arr_values);
arr = ar;
var edit_qtype_id = $('#edit_qtype_id').val();
var qtype_name = $('#qtype_name').val();
var subject_list = $('#qtype_subject_id').val();
var ddl_topic_type = $('#qtype_topic_id').val();
var qtype_option = $('#qtype_option').val();
var jasondata = $('#qtype_json').val();
var sort_order = $('#sort_order').val();
var jasondata = $('#jasonData').val();
var sendInfo = {
'edit_qtype_id':edit_qtype_id,
'arr':arr,
'saveEditQtypeFile':1,
'qtype_name':qtype_name,
'qtype_subject_id':subject_list,
'qtype_topic_id':ddl_topic_type,
'qtype_option':qtype_option,
'qtype_json':jasondata,
'sort_order':sort_order
};
console.log(sendInfo);
//var loadQtypeInfo = JSON.stringify(sendInfo);
$.ajax({
url: "/eqtype-editor/update",
type: "POST",
data :sendInfo,
contentType: "application/x-www-form-urlencoded",
success: function(response)
{
alert('Your file is updated!');
},
error: function (request, status, error)
{
alert('problem with updating record!!!');
},
complete: function()
{}
});
}
}
Here is my route file:
Route::post('eqtype-editor/update', 'QtypeEditorController#update');
Can anyone help me where i did mistake..thanks in advance.
There are two ways to achieve update of records
One - minor change in your code to just get it working
public function update(Request $request, Qtype_editor $qtype_editor)
{
$qtype_editor = Qtype_editor::findOrFail($request->edit_qtype_id);
$qtype_editor->qtype_name = $request->input('qtype_name');
$qtype_editor->qtype_subject_id = $request->input('qtype_subject_id');
$qtype_editor->qtype_topic_id = $request->input('qtype_topic_id');
$qtype_editor->qtype_option = $request->input('qtype_option');
$qtype_editor->qtype_json = $request->input('qtype_json');
$qtype_editor->sort_order = $request->input('sort_order');
$qtype_editor->save();
return redirect()->route('eqtype-editor.index');
}
Second:
Following Laravel conventions - The Laravel Way
Route definition should be: PUT/PATCH methods for resource update
Route::match(
['PUT', "PATCH'],
'eqtype-editor/{qtype_editor}', //qtype_editor param for route model binding
'QtypeEditorController#update'
);
public function update(Request $request, Qtype_editor $qtype_editor)
{
//$qtype_editor will be resolved via route model binding
//object representing db record with id of $qtype_editor passed from frontend
//$qtype_editor = Qtype_editor::findOrFail($request->edit_qtype_id);
$qtype_editor->qtype_name = $request->input('qtype_name');
$qtype_editor->qtype_subject_id = $request->input('qtype_subject_id');
$qtype_editor->qtype_topic_id = $request->input('qtype_topic_id');
$qtype_editor->qtype_option = $request->input('qtype_option');
$qtype_editor->qtype_json = $request->input('qtype_json');
$qtype_editor->sort_order = $request->input('sort_order');
$qtype_editor->save();
return redirect()->route('eqtype-editor.index');
}
Javascript
$.ajax({
url: `/eqtype-editor/${edit_qtype_id}`, //add the id to the route
type: "PUT",
data :sendInfo,
contentType: "application/x-www-form-urlencoded",
success: function(response)
{
alert('Your file is updated!');
},
error: function (request, status, error)
{
alert('problem with updating record!!!');
},
complete: function()
{}
});

Is there a way to show "Loading data.." option in Rally Grid(ext JS) while making the Ajax request to load the data?

I am trying to set the message to "Data Loading.." whenever the data is loading in the grid. It is working fine if I don't make an Ajax call. But, when I try to make Ajax Request, It is not showing up the message "Loading data..", when it is taking time to load the data. Can someone please try to help me with this.. Thanks in Advance.
_loadData: function(x){
var that = this;
if(this.project!=undefined) {
this.setLoading("Loading data..");
this.projectObjectID = this.project.value.split("/project/");
var that = this;
this._ajaxCall().then( function(content) {
console.log("assigned then:",content,this.pendingProjects, content.data);
that._createGrid(content);
})
}
},
_ajaxCall: function(){
var deferred = Ext.create('Deft.Deferred');
console.log("the project object ID is:",this.projectObjectID[1]);
var that = this;
console.log("User Reference:",that.userref,this.curLen);
var userObjID = that.userref.split("/user/");
Ext.Ajax.request({
url: 'https://rally1.rallydev.com/slm/webservice/v2.0/project/'+this.projectObjectID[1]+'/projectusers?fetch=true&start=1&pagesize=2000',
method: 'GET',
async: false,
headers:
{
'Content-Type': 'application/json'
},
success: function (response) {
console.log("entered the response:",response);
var jsonData = Ext.decode(response.responseText);
console.log("jsonData:",jsonData);
var blankdata = '';
var resultMessage = jsonData.QueryResult.Results;
console.log("entered the response:",resultMessage.length);
this.CurrentLength = resultMessage.length;
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:resultMessage
});
this.pendingProjects = resultMessage.length
console.log("this testcase store:",resultMessage);
_.each(resultMessage, function (data) {
var objID = data.ObjectID;
var column1 = data.Permission;
console.log("this result message:",column1);
if(userObjID[1]==objID) {
console.log("obj id 1 is:",objID);
console.log("User Reference 2:",userObjID[1]);
if (data.Permission != 'Editor') {
deferred.resolve(this.testCaseStore);
}else{
this.testCaseStore = Ext.create('Rally.data.custom.Store', {
data:blankdata
});
deferred.resolve(this.testCaseStore);
}
}
},this)
},
failure: function (response) {
deferred.reject(response.status);
Ext.Msg.alert('Status', 'Request Failed.');
}
});
return deferred;
},
The main issue comes from your Ajax request which is using
async:false
This is blocking the javascript (unique) thread.
Consider removing it if possible. Note that there is no guarantee XMLHttpRequest synchronous requests will be supported in the future.
You'll also have to add in your success and failure callbacks:
that.setLoading(false);

error in image while uploading through ajax

I am trying to upload image through ajax. at theclient side i am using this code.
$(document).on('change','.image_upload',function(){
readURL(this);
});
///
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
save_profile_image(e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
function save_profile_image(image_data){
var image_code = encodeURIComponent(image_data);
$.ajax({
type: "POST",
url: '<?=base_url()."Dashboard/new_valet_picture";?>',
data:'valet_image='+image_code,
success: function(data){
alert('data');
}
});
}
while at the client side i am using codeigniter to save this as image. Image file is created but it won't display because it contains errors.Here is my CI function where this ajax request is being sent.
public function new_valet_picture(){
$user = $this->session->user_id;
$image_data = $this->input->post('valet_image');
$name= "valet_".$user.time().".png";
$profile_image = str_replace('data:image/png;base64,', '', $image_data);
$profile_image = str_replace(' ', '+',$profile_image);
$unencodedData=base64_decode($profile_image);
$pth = './uploads/valet_images/'.$name;
file_put_contents($pth, $unencodedData);
echo $name;
}
can anybody figure out where i am wrong.
you just wrong to pass parameter in ajax request :
this is your code
$.ajax({
type: "POST",
url: '<?=base_url()."Dashboard/new_valet_picture";?>',
data:'valet_image='+image_code,
success: function(data){
alert('data');
}
});
data:'valet_image='+image_code, is wrong pass and change that to data : {vallet_image : image_code}.
just changing the position of encodeURIComponent() helped me
///
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
save_profile_image(encodeURIComponent(e.target.result));
}
reader.readAsDataURL(input.files[0]);
}
else {
swal("Sorry - you're browser doesn't support the FileReader API");
}
}
function save_profile_image(image_data){
var image_code = image_data;
$.ajax({
type: "POST",
url: '<?=base_url()."Dashboard/new_valet_picture";?>',
data:'valet_image='+image_code,
success: function(data){
alert('data');
}
});
}

How can I handle a ajax request response in the Flux Architecture?

Looking at the Flux Documentation I can't figure out how the code to a ajax update, and a ajax fetch would fit into the dispatcher, store, component architecture.
Can anyone provide a simple, dummy example, of how an entity of data would be fetched from the server AFTER page load, and how this entity would be pushed to the server at a later date. How would the "complete" or "error" status of request be translated and treated by the views/components? How would a store wait for the ajax request to wait? :-?
Is this what you are looking for?
http://facebook.github.io/react/tips/initial-ajax.html
you can also implement a fetch in the store in order to manage the information.
Here is an example (it is a concept, not actually working code):
'use strict';
var React = require('react');
var Constants = require('constants');
var merge = require('react/lib/merge'); //This must be replaced for assign
var EventEmitter = require('events').EventEmitter;
var Dispatcher = require('dispatcher');
var CHANGE_EVENT = "change";
var data = {};
var message = "";
function _fetch () {
message = "Fetching data";
$.ajax({
type: 'GET',
url: 'Url',
contentType: 'application/json',
success: function(data){
message = "";
MyStore.emitChange();
},
error: function(error){
message = error;
MyStore.emitChange();
}
});
};
function _post (myData) {
//Make post
$.ajax({
type: 'POST',
url: 'Url',
// post payload:
data: JSON.stringify(myData),
contentType: 'application/json',
success: function(data){
message = "";
MyStore.emitChange();
},
error: function(error){
message = "update failed";
MyStore.emitChange();
}
});
};
var MyStore = merge(EventEmitter.prototype, {
emitChange: function () {
this.emit(CHANGE_EVENT);
},
addChangeListener: function (callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function (callback) {
this.removeListener(CHANGE_EVENT, callback);
},
getData: function (){
if(!data){
_fetch();
}
return data;
},
getMessage: function (){
return message;
},
dispatcherIndex: Dispatcher.register( function(payload) {
var action = payload.action; // this is our action from handleViewAction
switch(action.actionType){
case Constants.UPDATE:
message = "updating...";
_post(payload.action.data);
break;
}
MyStore.emitChange();
return true;
})
});
module.exports = MyStore;
Then you need to subscribe your component to the store change events
var React = require('react');
var MyStore = require('my-store');
function getComments (){
return {
message: null,
data: MyStore.getData()
}
};
var AlbumComments = module.exports = React.createClass({
getInitialState: function() {
return getData();
},
componentWillMount: function(){
MyStore.addChangeListener(this._onChange);
},
componentWillUnmount: function(){
MyStore.removeChangeListener(this._onChange);
},
_onChange: function(){
var msg = MyStore.getMessage();
if (!message){
this.setState(getData());
} else {
this.setState({
message: msg,
data: null
});
}
},
render: function() {
console.log('render');
return (
<div>
{ this.state.message }
{this.state.data.map(function(item){
return <div>{ item }</div>
})}
</div>
);
}
});
I hope it is clear enough.

MVC3 and Twitter Bootstrap TypeAhead without plugin

I have gotten TypeAhead to work properly with static data and am able to call my controller function properly and get data but it is either A: Not parsing the data properly or B: The TypeAhead is not set up correctly.
JavaScript :
<input type="text" id="itemSearch" data-provide="typeahead" value="#ViewBag.Item" name="itemSearch"/>
$('#itemSearch').typeahead({
source: function (query, process) {
parts = [];
map = {};
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data, function (i, part) {
map[part.description] = part;
parts.push(part.description);
});
typeahead.process(parts);
}
});
},
updater: function (item) {
selectedPart = map[item].itemNumber;
return item;
},
matcher: function (item) {
if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
},
sorter: function (items) {
return items.sort();
},
highlighter: function (item) {
var regex = new RegExp('(' + this.query + ')', 'gi');
return item.replace(regex, "<strong>$1</strong>");
}
});
Controller :
public ActionResult MakePartsArray(string query)
{
var possibleItem = query.ToLower();
var allItems = Db.PartInventorys.Where(l => l.ItemNumber.Contains(possibleItem)).Select(x => new { itemNumber = x.ItemNumber, description = x.Description });
return new JsonResult
{
ContentType = "text/plain",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems, },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
In my controller I see the data being retrieved correctly and it appears to parse properly but nothing is showing up for my TypeAhead.
Any idea on how to verify exactly where the breakdown is occurring or does anyone see direct fault in my code?
Problem was in the ajax call-
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data.matches, function (i, part) {
var composedInfo = part.description + ' (' + part.itemNumber + ')';
map[composedInfo] = part;
parts.push(composedInfo);
});
process(parts);
}
});
and in the controller on the return type
return new JsonResult
{
ContentType = "application/json",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};

Resources