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 ) );
}
Related
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!
I am trying to validate my forms by using jQuery and php .. What I am trying to achieve is pass my form inputs to process.php in the background, check if inputs pass my validation code, then return true or false back to my jQuery checkForm() function .. so far the below code is now working ..
function checkForm() {
jQuery.ajax({
url: "process.php",
data: {
reguser: $("#reguser").val(),
regpass: $("#regpass").val(),
regpass2: $("#regpass2").val(),
regemail: $("#regemail").val()
},
type: "POST",
success: function(data) {}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form action="register.php" method="post" onSubmit="return checkForm()">
send all input's in php to validate all the data.
function checkForm() {
$.ajax({
url : "process.php",
type: "POST",
data: $('#yourForm').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status)
{
alert("Success");
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
alert(data.inputerror[i] + "|" + data.error_string[i]);
}
}
}
});
};
validating the data you've sent through Ajax.
public function process()
{
$this->_validate_all_data();
echo json_encode(array("status" => true));
}
private function _validate_all_data()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = true;
if(empty($POST['reguser']))
{
$data['inputerror'][] = 'reguser'; // input name
$data['error_string'][] = 'Reguser is required'; // message for validation
$data['status'] = false;
}
if($data['status'] === false)
{
echo json_encode($data);
exit();
}
}
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 am new to cakephp and trying to send data from ajax to my controller action..
i have a popup model in which there is a input box ..i want to grab that value and send to controller without page refresh
here is my code ..
<a class="button anthracite-gradient" onclick="openPrompt()">submit </a>
my javascript
function openPrompt()
{
var cancelled = true;
$.modal.prompt('Please enter a value:', function(value)
{
$.ajax({
type:"POST",
url:"/cakephp/controller/action/",
success : function(data) {
alert(value); //value right now is in this variable ... i want to send this variable value to the controller
},
error : function() {
alert("false");
}
});
}, function()
{
});
};
</script>
myController
public function action(){
if( $this->request->is('ajax') ) {
$new = $this->request->data;
echo "ok"
return;
}
}
i want to first get the value here and then send the response to may ajax request
Its simple post the value to the controller and do what you want , in ajax request bind the value in data:{value_to_send:value} and get in controller
function openPrompt()
{
var cancelled = true;
$.modal.prompt('Please enter a value:', function(value)
{
$.ajax({
type:"POST",
data:{value_to_send:value},
url:"/cakephp/controller/action/",
success : function(data) {
alert(data);// will alert "ok"
},
error : function() {
alert("false");
}
});
}, function()
{
});
};
</script>
public function action(){
if( $this->request->is('ajax') ) {
// echo $_POST['value_to_send'];
echo $value = $this->request->data('value_to_send');
//or debug($this->request->data);
echo "ok"
die();
}
}
For more see accessing-post-data
I will give you some example. In my case, list out book list as a smart search while typing on text box.
$( ".selectBook" ).each(function(){
$(this).keyup(function( event ) {
var tri = $(this).val();
var oPrnt = $(this).parents('.smartsearch');
var str = '';
if(tri.length > 2){
$.ajax({
type: "POST",
url: "/utility/getbooks/",
data: JSON.stringify({string: tri, activeonly:false}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function(key, val) {
str += '<li id="a'+key+'" term="'+val+'" data-did="'+key+'">'+val+'</li>';
});
oPrnt.find("ul.result").html(str);
},
error: function (errormessage) {
oPrnt.find("ul.result").html('<li><b>No Results</b></li>');
}
});
oPrnt.find("ul.result").slideDown(100);
}
});
});
And in the controller, action (getbooks Action in UtilityController in my case)
public function getbooks($string = '', $activeonly = true){
$this->autoRender = false;
if( $this->request->is('ajax') ) {
$data = $this->request->input('json_decode');
$string = $data->string;
$activeonly = $data->activeonly;
}
$aReturn = array();
// ... fetch books data from DB goes here...
$aResult = $this->Book->fetch('list');
foreach($aResult as $r){
if(isset($r['bookname'])){
$aReturn[$r['id']] = $r['bookname'];
}
}
return json_encode($aReturn);
}
For some reason IE is asking us to download a file instead of running it as ajax. This works in all browsers except IE. I tried messing with the headers that it returns with no luck.
The function grabs form data then post's it the response is a can be an array of any number of items to be updated on the page.
Its not suppose to be file its suppose to be just a json response.
PHP
header('Content-type: application/json');
$error = "The Email and Password you entered could not be resolved.";
$elements[0]['target'] = '.error_report';
$elements[0]['action'] = 'inside';
$elements[0]['data'] = '<p>'.$error.'</p>';
$this->output->set_output(
json_encode(array("elements" => $elements))
);
Javascript
$(document).ready(function () {
jQuery.ajaxSetup({
cache: false,
dataType: 'json',
error: function () {
alert("Request was not successful. Please try again shortly.");
}
});
$(document).ajaxSuccess(function (e, xhr, settings) {
var response = xhr.responseText;
if (settings.dataType != 'json') {
return;
};
try {
response = jQuery.parseJSON(response);
} catch (e) {
alert(e);
return;
}
if (response.elements instanceof Array) {
var reqs = ['target', 'action'];
var valid = true;
for (var i=0;i<response.elements.length;i++) {
var cur = response.elements[i];
var sel;
for (var j=0;j<reqs.length;j++) {
if (typeof cur[reqs[j]] !== "string") {
valid = false;
break;
};
};
if (!valid) {
continue;
};
sel = $(cur.target);
switch (cur.action) {
case "inside":
sel.html(cur.data);
break;
case "instead":
sel.replaceWith(cur.data);
break;
case "remove":
sel.remove();
break;
case "refreshPage":
window.location.reload();
default:
if (typeof sel[cur.action] === "function") {
sel[cur.action](cur.data);
}; // else continue
break;
};
};
};
// Dispatch the AJAX request, and save it to the data object so that
// is can be referenced and cancelled if need be.
self.data('ajaxify.xhr', jQuery.ajax({
url: this.action,
type: 'post',
dataType: options.dataType,
data: (beforeSubmitIsJquery ? beforeSubmitResult.serialize()
: self.serialize()),
success: function (/**/) {
cleanup();
options.onSuccess.apply(that, arguments);
},
error: function (/**/) {
cleanup();
options.onError.apply(that, arguments);
},
complete: function (/**/) {
options.onComplete.apply(that, arguments);
}
}));