I'm trying to make another ajax call when one is executed successfully to pass the post variable to another controller action. However, it is returning null when I check the console log message. I'm not sure why.
Here is my code:
jQuery:
$('#modify-store-name').on('change', function() {
$.ajax({
type: "POST",
url: "/user/get-one-store",
dataType: "json",
data: {
store_name: $(this).val()
}
}).done(function (msg) {
$.each(msg, function (i) {
$('#modify-store-label').attr('style', '');
$('#modify-store-desc').attr('style', '');
$('#modify-store-category-label').attr('style', '');
$('#modify-store-category').attr('style', '');
$('.upload-btn-wrapper').attr('style', '');
$('#modify-store-desc').val(msg[i].store_description);
$('#modify-store-category').html($("<option />").val(msg[i].store_category).text(msg[i].store_category));
$('#msubmit').attr('disabled', false);
});
$.ajax({
type: "POST",
url: "/user/modify-store",
dataType: "json",
data: {
store_name2: $('#modify-store-name').val() // why is this sending a null value
}
}).done(function(msg) {
console.log(msg);
}).fail(function(msg) {
console.log(msg);
});
}).fail(function (msg) {
$("#msg").html(msg.failure);
});
});
and my php code:
public function getonestoreAction()
{
$layout = $this->layout();
$layout->setTerminal(true);
$view_model = new ViewModel();
$view_model->setTerminal(true);
try {
$store_name = $this->params()->fromPost('store_name');
echo json_encode($this->getUserService()->getAStore($store_name));
} catch (\Exception $e) {
echo json_encode(array('failure' => $e->getMessage()));
}
return $view_model;
}
public function modifystoreAction()
{
$layout = $this->layout();
$layout->setTerminal(true);
$view_model = new ViewModel();
$view_model->setTerminal(true);
if ($this->getRequest()->isPost()) {
try {
$store_name = $this->params()->fromPost('store-name2');
echo json_encode($store_name); // returning null
$mstore_name = $this->params()->fromPost('modify-store-name');
$mstore_description = $this->params()->fromPost('modify-store-description');
$mstore_category = $this->params()->fromPost('modify-store-category');
$mstore_image = $this->params()->fromFiles('modify-store-image');
if (count($mstore_image) > 0) {
if ($this->getUserService()->modifyStore($store_name, array('store_name' => $mstore_name, 'store_description' => $mstore_description, 'store_category' => $mstore_category, 'store_image' => $mstore_image, 'tmp_name' => $mstore_image['tmp_name']))) {
echo json_encode(array('success' => 'Store was modified successfully.'));
}
}
} catch (\Exception $e) {
echo json_encode(array('failure' => $e->getMessage()));
}
}
return $view_model;
}
I read that you can make two ajax calls like this but I'm not sure why one is not passing the store name via post.
Any help would be appreciated
Thanks!
Related
I send a store request to my laravel application through AJAX. The controller function works properly, but either I cannot get a success message in my ajax function, or the function on success is not working.
Ajax code:
$.ajax({
type: "POST",
url: 'http://127.0.0.1:8000/dreams',
data: {
description: description,
offset_top: offset_top,
offset_left : offset_left
},
success: function(msg){
console.log("done");
}
});
Controller's store function:
public function store(Request $request)
{
echo $request;
if (Auth::check()) {
$user = Auth::user();
$dream = new Dream($request->all());
if ($dream) {
$user->dreams()->save($dream);
$response = array(
'dream' => $dream,
'status' => 'success',
'msg' => 'Setting created successfully',
);
return \Response::json($response);
}
return \Response::json(['msg' => 'No model']);
} else {
return \Response::json('msg' => 'no auth');
}
}
Try to pass data in ajax using this way.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: 'http://127.0.0.1:8000/dreams',
data: {
description: description,
offset_top: offset_top,
offset_left: offset_left
},
success: function(msg) {
console.log("done");
}
});
Try below code for store method:
public function store(Request $request)
{
if (Auth::check()) {
$user = Auth::user();
$dream = new Dream($request->all());
if ($dream) {
$user->dreams()->save($dream);
$response = array(
'dream' => $dream,
'status' => 'success',
'msg' => 'Setting created successfully',
);
return \Response::json($response);
}
return \Response::json(['msg' => 'No model']);
} else {
return \Response::json(['msg' => 'no auth']);
}
}
i've created a upload form with text fields to create custom posts from frontend in Wordpress.
The requst is working, but i can't get the response message in ajax when a file is uploaded. If no file is uploaded and only the text field is set then i get the response.
here is my ajax form:
//upload-form.js
_submit: function (event) {
event.preventDefault();
this.$submitButton.prop('disabled', true);
var $formdata = false;
var $form = this.$form;
if (window.FormData) {
$formdata = new FormData();
}
var $files_data = this.$upload;
if ($files_data.val() == '') {
$formdata.append('fields', $form.serialize());
} else {
$.each($($files_data), function (i, obj) {
$.each(obj.files, function (j, file) {
$formdata.append('files[' + j + ']', file);
$formdata.append('fields', $form.serialize());
})
});
}
$formdata.append('action', 'upload_form_submit');
$formdata.append('nonce', upload.form_nonce);
$.ajax({
url: upload.ajaxurl,
type: 'POST',
data: $formdata,
dataType: "json",
async: false,
success: this._success.bind(this),
error: this._error.bind(this),
cache: false,
contentType: false,
processData: false
});
return false;
},
_success: function (jsonResponse) {
var response = jsonResponse;
if (response.type == 'success') {
// Clear fields
this.$fields.val('');
this.$submitButton.prop('disabled', true);
// Show message
if (response.message) {
$('.response-success').text(response.message);
}
} else {
this._error(response.message);
}
return jsonResponse;
},
_error: function (error) {
this.$submitButton.prop('disabled', false);
// Show message
if (error) {
if (typeof error === 'object') {
$('.response-success').text(error.statusText);
} else {
// Custom error
$('.response-success').text(error);
this.$form.find('*[required]').each(function (i, elem) {
var $elem = $(elem);
if (!$elem.val()) {
$elem.parent().addClass('empty-field');
}
});
}
}
}
My PHP response
/**
* Callback to validate AJAX request
*/
public function ajax_submit_form() {
check_ajax_referer( 'form_submit', 'security' );
if ( !isset( $_POST['fields'] ) ) {
return;
}
$json = array();
// Parse $.serialize()
parse_str( $_POST['fields'], $this->_post_fields );
// Check if required fields are not empty
if ( $this->is_valid_data() ) {
// save posts
if ( $this->handle_frontend_new_post_form_submission() ) {
$json['type'] = 'success';
$json['message'] = $this->_notices['post_sent'];
} else {
$json['type'] = 'error';
$json['message'] = $this->_notices['post_not_sent'];
}
} else {
$json['type'] = 'error';
$json['message'] = $this->_notices['empty_fields'];
}
die( wp_json_encode( $json ) );
}
I am using an AJAX call to insert some data into MYSQL
JS code:
$("input.addtruck").click(function (event) {
event.preventDefault();
var user_id = $("input#user_id").val();
var numar = $("input#numar").val();
var serie = $("input#serie").val();
var marca = $("select#marca").val();
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "aplicatie/add_truck",
dataType: 'json',
data: {user_id: user_id, numar: numar, serie: serie, marca: marca},
});
success: function (res) {
if (res)
{
jQuery("div#truck_form").hide();
jQuery("div#success").show();
} else {
jQuery("div#error").show();
}
}
});
Method used from controller:
function add_truck() {
$data = array(
'user_id' => $this->input->post('user_id'),
'marca' => $this->input->post('marca'),
'serie' => $this->input->post('serie'),
'numar' => $this->input->post('numar')
);
//Transfering data to Model
$this->trucks_model->insert_truck($data);
$data['confirmare'] = 'Data Inserted Successfully';
}
And method from models file
function insert_truck($data){
$this->db->insert('trucks', $data);
}
Basicly i need to hide the #truck_form and show #success if the data was inserted, or show #error .
You need to check data is inserted or not in database using affected_rows in model
Model
function insert_truck($data){
$this->db->insert('trucks', $data);
$afftectedRows=$this->db->affected_rows();
if($afftectedRows>0)
{
return TRUE;
}
else{
return FALSE;
}
}
YOu need to echo your result in Controller
Controller
function add_truck() {
$data = array(
'user_id' => $this->input->post('user_id'),
'marca' => $this->input->post('marca'),
'serie' => $this->input->post('serie'),
'numar' => $this->input->post('numar')
);
//Transfering data to Model
$res=$this->trucks_model->insert_truck($data);
if($res){
$data['msg'] = 'true';
}else{
$data['msg'] = 'false';
}
echo json_encode($data);
}
Ajax
success: function (res) {
if (res.msg=='true')
{
jQuery("div#truck_form").hide();
jQuery("div#success").show();
} else {
jQuery("div#error").show();
}
}
You can create an array of response like this. As you ajax dataType is json so you will send response in json.
function add_truck() {
$response = array();
$data = array(
'user_id' => $this->input->post('user_id'),
'marca' => $this->input->post('marca'),
'serie' => $this->input->post('serie'),
'numar' => $this->input->post('numar')
);
//Transfering data to Model
$check_insert = $this->trucks_model->insert_truck($data);
if(check_insert){
$response['status'] = 'true';
$response['msg'] = 'Data Inserted Successfully';
}else{
$response['status'] = 'false';
$response['msg'] = 'Problem in data insertion';
}
echo json_encode($response);
die;
}
and then in ajax :
success: function (res) {
if (res.status == 'true')
{
jQuery("div#truck_form").hide();
jQuery("div#success").show();
} else {
jQuery("div#error").show();
}
}
error: function (result) {
console.log('Problem with ajax call insert');
}
And method from models file
Just to ensure row inserted return insert_id
function insert_truck($data){
$this->db->insert('trucks', $data);
$insert_id = $this->db->insert_id();
return $insert_id;
}
In AJAX
<script type="text/javascript">
$("#addtruck").click(function (event) { // change
event.preventDefault();
var user_id = $("#user_id").val(); // remove input(input#user_id)
var numar = $("#numar").val();
var serie = $("#serie").val();
var marca = $("#marca").val();
$.ajax(
{
type: "post",
dataType: 'json',
url: "<?php echo base_url(); ?>aplicatie/add_truck",
data: {user_id: user_id, numar: numar, serie: serie, marca: marca},
}
);
success: function (res) {
if (res == TRUE)
{
jQuery("truck_form").hide(); // remove div on here
jQuery("success").show(); // remove div on here
} else {
jQuery("error").show(); // remove div on here
}
}
});
</script>
In HTML
Button should be
<input type="button" id="addtruck" value="Add New Truck">
and form action="" should be removed
In Controller
function add_truck() {
$data = array(
'user_id' => $this->input->post('user_id'),
'marca' => $this->input->post('marca'),
'serie' => $this->input->post('serie'),
'numar' => $this->input->post('numar')
);
# passing to model
$res = $this->trucks_model->insert_truck($data);
# Check return value on $res
if($res == TRUE)
{
$data['msg'] = 'true';
}
else
{
$data['msg'] = 'false';
}
echo json_encode($data);
}
In Model
function insert_truck($data){
$this->db->insert('trucks', $data);
$row_affect = $this->db->affected_rows();
if($row_affect > 0)
{
return TRUE;
}
else
{
return FALSE;
}
}
You can add error after success to know ajax called successfully or not.
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "aplicatie/add_truck",
dataType: 'json',
data: {user_id: user_id, numar: numar, serie: serie, marca: marca},
success: function (res) {
if (res)
{
jQuery("div#truck_form").hide();
jQuery("div#success").show();
} else {
jQuery("div#error").show();
}
},
error: function (xhr,err) {
alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
alert("responseText: "+xhr.responseText);
}
});
Just remove event.preventDefault() from the code and use success like below
jQuery.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "aplicatie/add_truck",
dataType: 'json',
data: {user_id: user_id, numar: numar, serie: serie, marca: marca},
success : functionName
});
function functionName(){
//your code for success
}
I have a table with title and done and id fields,
Now the problem is that when I click on the add button, the data is not stored in the table and the data is not displayed, if you test this code and create a task model with gii, you will see that add button does not work that is when you type a name and click on add button, the task will not be added
Fields related to this model: id, title, done
I have the following code:
todo.js in the assets file
var todo = {
taskTemplate: null,
refs: {},
options: {},
reload: function(){
$.ajax({
url: todo.options.taskEndpoint,
type: 'get',
dataType: 'json',
success: function(response) {
$.each(response.data, function(index, value){
todo.refs.tasks.append(todo.taskTemplate(value));
});
},
error: todo.onFailure
});
},
onFailure: function(xhr){
var data = $.parseJSON(xhr.responseText);
todo.refs.status.text('');
$.each(data.errors, function(index, value){
todo.refs.status.append('<p>'+value+'</p>');
});
},
onAdd: function(e){
e.preventDefault();
var form = this;
$.ajax({
url: todo.options.taskEndpoint,
type: 'post',
data: $(form).serialize(),
dataType: 'json',
success: function(response) {
todo.refs.tasks.append(
todo.taskTemplate(response.data));
form.reset();
},
error: todo.onFailure
});
},
onDelete: function(e) {
e.preventDefault();var id = $(this).parents('.task').attr('data-id');
$.ajax({
url: todo.options.taskEndpoint,
type: 'delete',
data: {
id: id
},
dataType: 'json',
success: function() {
$('.task[data-id='+id+']').remove();
},
error: todo.onFailure
});
},
onChange: function(e) {
e.preventDefault();
var data = {
id: $(this).parents('.task').attr('data-id'),
Task: {}
};
if(this.type==='checkbox') {
data.Task.done = + this.checked;
}
else if(this.type==='text') {
data.Task.title = $(this).val();
}
$.ajax({
url: todo.options.taskEndpoint,
type: 'put',
data: data,
dataType: 'json',
success: function(response) {
$('.task[data-id='+response.data.id+']')
.before(todo.taskTemplate(response.data))
.remove();
},
error: todo.onFailure
});
},
initLoader: function() {
var loadingText = 'Loading...';
$(document).ajaxSend(function(){
todo.refs.status.text(loadingText);}).ajaxStop(function(){
if(todo.refs.status.text()===loadingText) {
todo.refs.status.fadeOut(500, function(){
todo.refs.status.text('').show();
});
}
});
},
bindEvents: function() {
todo.refs.taskForm.submit(todo.onAdd);
todo.refs.tasks.on('click', '.delete', todo.onDelete);
todo.refs.tasks.on('change', 'input', todo.onChange);
},
initRefs: function() {
todo.refs.page = $('.todo-index');
todo.refs.tasks = todo.refs.page.find('.tasks');
todo.refs.status = todo.refs.page.find('.status');
todo.refs.taskForm = todo.refs.page.find('.new-taskform');
},
init: function(options){
todo.options = options;
todo.taskTemplate = doT.template($('#template-task').html());
todo.initRefs();
todo.initLoader();
todo.bindEvents();
todo.reload();
}
};
controller
<?php
class TodoController extends Controller
{
public function actionIndex()
{
$task = new Task();
$this->render('index', array(
'task' => $task,
));
}
public function actionTask()
{
$req = Yii::app()->request;
if($req->isPostRequest) {
$this->handlePost($req->getPost('id'),
$req->getPost('Task'));
}
elseif($req->isPutRequest) {
$this->handlePut($req->getPut('Task'));
}
elseif($req->isDeleteRequest) {
$this->handleDelete($req->getDelete('id'));
}
else {
$this->handleGet($req->getParam('id'));
}
}
private function handleGet($id)
{
if($id) {
$task = $this->loadModel($id);
$this->sendResponse($task->attributes);
}
else {
$data = array();
$tasks = Task::model()->findAll(array('order' => 'id'));
foreach($tasks as $task) {
$data[] = $task->attributes;
}
$this->sendResponse($data);
}
}
private function handlePut($data)
{
$task = new Task();
$this->saveTask($task, $data);
}
private function handlePost($id, $data)
{
$task = $this->loadModel($id);
$this->saveTask($task, $data);
}
private function saveTask($task, $data)
{
if(!is_array($data)){
$this->sendResponse(array(), 400, array('No data
provided.'));
}
// $task->setAttributes($data);
$task->attributes = $data;
if($task->save()) {
$this->sendResponse($task->attributes);
} else {
$errors = array();
foreach($task->errors as $fieldErrors) {
foreach($fieldErrors as $error) {
$errors[] = $error;
}
}
$this->sendResponse(array(), 400, $errors);
}
}
private function handleDelete($id)
{
$task = $this->loadModel($id);
if($task->delete()) {
$this->sendResponse('OK');
}
else {
$this->sendResponse(array(), 500, array('Unable to
delete task.'));
}
}
private function loadModel($id)
{
$task = Task::model()->findByPk($id);
if(!$task) {
$this->sendResponse(array(), 404, array('Task not
found.'));
}
return $task;
}
private function sendResponse($data, $responseCode = 200,
$errors = array())
{
$messages = array(
200 => 'OK',
400 => 'Bad Request',
404 => 'Not Found',
500 => 'Internal Server Error',
);
if(in_array($responseCode, array_keys($messages))) {
header("HTTP/1.0 $responseCode ".$messages[$responseCode],
true, $responseCode);
}
echo json_encode(array(
'errors' => $errors,
'data' => $data,
));
Yii::app()->end();
}
}
?>
view
<?php
Yii::app()->clientScript->registerPackage('todo');
$options = json_encode(array(
'taskEndpoint' => $this->createUrl('todo/task'),
));
Yii::app()->clientScript->registerScript('todo', "todo.
init($options);", CClientScript::POS_READY);
?>
<div class="todo-index">
<div class="status"></div>
<div class="tasks"></div>
<div class="new-task">
<?php echo CHtml::beginForm('todo/task')?>
<?php echo CHtml::activeTextField($task, 'title')?>
<?php echo CHtml::submitButton('Add')?>
<?php echo CHtml::endForm()?>
</div>
</div>
<script id="template-task" type="text/x-dot-template">
<div class="task{{? it.done==1}} done{{?}}" data-id="{{!it.
id}}">
<input type="checkbox"{{? it.done==1}}checked {{?}}/>
<input type="text" value="{{!it.title}}" />
Remove
</div>
</script>
Can anyone help ?
Am I doing something wrong with the following code? I can't seem to get alert("success") to process when the Ci session expires. Below is my jquery and Ci code:
setInterval(function() {
jQuery.getJSON("<?=base_url()?>index.php/regUserDash/sessionExpire", function(data) {
var sessionState = jQuery.parseJSON('{"sessionExpired":"true","sessionExpired":"false"}');
if(sessionState.sessionExpired === "true") { // if session is expired run the following code
var dataString = 'true';
jQuery.ajax({ // send the expired signal to Ci so that it knows the session has expired
type: 'POST',
dataType: 'JSON',
url: '<?=base_url()?>index.php/regUserDash/extendSession',
data: {'dataString': true},
success: function(data) {
if (data.extendedSession == true) {
alert('success');
} else {
return false;
}
}
});
} else if(sessionState.sessionExpired == "false") {
return;
}
});
}, 120000); // loop through every 2 minutes
CodeIgniter Code:
public function sessionExpire() {
if ($this->session->userdata("logged") == "1") {
echo json_encode(array("sessionExpired" => false));
} elseif($this->session->userdata("logged") == "0") {
echo json_encode(array("sessionExpire" => true));
}
} public function extendSession() {
// set loggedIn session var
$this->session->set_userdata('logged', '1');
// return json to ajax call
echo json_encode(array("extendedSession" => true));
}
jQuery.parseJSON('{"sessionExpired":"true","sessionExpired":"false"}'); return first sessionExpired = true and second sessionExpired = false, which overwrite the first.
So, here is one way to do this (need test):
setInterval(function() {
jQuery.getJSON("<?=base_url()?>index.php/regUserDash/sessionExpire", function(data) {
if(data.sessionExpired == "true") { // if session is expired run the following code
// var dataString = 'true'; // Remove this
jQuery.ajax({ // send the expired signal to Ci so that it knows the session has expired
type: 'POST',
dataType: 'JSON',
url: '<?=base_url()?>index.php/regUserDash/extendSession',
data: {'dataString': true},
success: function(data) {
//if (data.extendedSession == true) {
alert('success');
//} else {
// return false;
//}
// Remove commented code, because extendSession() always return true
}
});
} else {
return 'Session not expired!';
}
});
}, 120000); // loop through every 2 minutes
And CI functions:
public function sessionExpire()
{
if ($this->session->userdata("logged") == "1") {
echo json_encode(array("sessionExpired" => false));
} elseif ($this->session->userdata("logged") == "0") {
echo json_encode(array("sessionExpired" => true));
}
}
public function extendSession()
{
// set loggedIn session var
$this->session->set_userdata('logged', '1');
// return json to ajax call
echo json_encode(array("extendedSession" => true));
}