Passing data from ajax in elgg - php

This is using Elgg 1.8, social networking engine.
I'm new to ajax and trying to make the form submit without refresh, it submits the form but adds item to the list without title.
The form is displayed in fancybox popup.
Here is my document ready script:
$(document).ready(function() {
$('.elgg-form-announcements-save').live('submit', function(e) {
//e.preventDefault();
var $form = $(this);
elgg.action($form.attr('action'), {
data: $form.serialize(),
success: function(data) {
// check the status and do stuff
//e.preventDefault();
var river = $('ul.announcements_list');
if (river.length < 1) {
river.append(data.output); } else {
$(data.output).find('li:first').hide().prependTo(river).slideDown(500);
};
$.fancybox.close();
}
});
return false; // prevent the form from submitting
e.preventDefault();
}); });
Here is code in the action php file:
if ($announcement->save()) {
elgg_clear_sticky_form('announcement');
system_message(elgg_echo('announcement:save:success'));
if (elgg_is_xhr()) {
$options = array( 'type' => 'object', 'subtype' => 'announcements', 'full_view' => false,
'pagination' => false, 'limit' => 1 );
$newannouncement = elgg_list_entities($options);
echo json_encode($newannouncement); }
} else {
I'm not sure what I need to do here, maybe use "success: function(json) {" instead of "success: function(data) {" but not sure how to implement that.
I tried using ajaxForm with no success.
Thank you.

Related

Return array/object to jquery script from AJAX

Hello all and thanks in advance,
Short story, I am using a plugin to dynamically populate select options and am trying to do it via an ajax call but am struggling with getting the data into the select as the select gets created before the ajax can finish.
First, I have a plugin that sets up different selects. The options input can accept an array or object and creates the <option> html for the select. The createModal code is also setup to process a function supplied for the options input. Example below;
$('#modalAccounts').createModal({
{
component: 'select',
options: function () {
let dueDate = {};
for (let i = 1; i < 32; i++) {
dueDate[i] = i;
}
return dueDate;
}
}
});
What I am trying to do is provide an object to the options input via AJAX. I have a plugin called postFind which coordinates the ajax call. Items such as database, collection, etc. are passed to the ajax call. Functions that should be executed post the ajax call are pass through using the onSuccess option.
(function ($) {
$.extend({
postFind: function () {
var options = $.extend(true, {
onSuccess: function () {}
}, arguments[0] || {});
options.data['action'] = 'find';
$.ajax({
url: "../php/ajax.php",
type: "POST",
data: options.data,
statusCode: {
404: function () {
alert("Page not found");
}
},
success: function (result) {
var obj = $.parseJSON(result);
if (obj.success) {
if (typeof options.onSuccess === 'function') {
options.onSuccess.call(this, obj);
}
}
},
error: function (xhr, text, err) {
console.log(err);
}
});
}
});
}(jQuery));
The plugin works fine as when I look at the output it is the data I expect. Below is an example of the initial attempt.
$('#modalAccounts').createModal({
{
component: 'select',
options: function () {
$.postFind({
data: {
database: 'dashboard',
collections: {
accountTypes: {
where: {status: true}
}
}
},
onSuccess: function (options) {
let dataArray = {};
$.each(options, function (key, val) {
dataArray[val._id.$oid] = val.type;
});
return dataArray;
}
})
}
}
});
In differnt iterations of attempting things I have been able to get the data back to the options but still not as a in the select.
After doing some poking around it looks like the createModal script in executing and creating the select before the AJAX call can return options. In looking at things it appears I need some sort of promise of sorts that returns the options but (1) I am not sure what that looks like and (2) I am not sure where the promise goes (in the plugin, in the createModal, etc.)
Any help you can provide would be great!
Update: Small mistake when posted, need to pass the results back to the original call: options.onSuccess.call(this, obj);
I believe to use variables inside your success callback they have to be defined properties inside your ajax call. Then to access the properties use this inside the callback. Like:
$.ajax({
url: "../php/ajax.php",
type: "POST",
data: options.data,
myOptions: options,
statusCode: {
404: function () {
alert("Page not found");
}
},
success: function (result) {
var obj = $.parseJSON(result);
if (obj.success) {
if (typeof this.myOptions.onSuccess === 'function') {
this.myOptions.onSuccess.call(this);
}
}
},
error: function (xhr, text, err) {
console.log(err);
}
});
It's not clear to me where the problem is without access to a functional example. I would start with a simplified version of what you want to do that demonstrates the proper functionality. My guess is the callbacks aren't setup exactly correctly; I would want to see the network call stack before making a more definitive statement. A few well-placed console.log() statements would probably give you a better idea of how the code is executing.
I wrote and tested the following code that removes most of the complexity from your snippets. It works by populating the select element on page load.
The HTML file:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<select data-src='test.php' data-id='id' data-name='name'></select>
</body>
</html>
<html>
<script>
$('select[data-src]').each(function() {
var $select = $(this);
$select.append('<option></option>');
$.ajax({
url: $select.attr('data-src'),
data: {'v0': 'Alligator', 'v1': 'Crocodile'}
}).then(function(options) {
options.map(function(option) {
var $option = $('<option>');
$option
.val (option[$select.attr('data-id')])
.text(option[$select.attr('data-name')]);
$select.append($option);
});
});
});
</script>
And the PHP file:
<?php
header("Content-Type: application/json; charset=UTF-8");
echo json_encode([
[ 'id' => 0, 'name' => 'Test User 0' ],
[ 'id' => 3, 'name' => $_GET['v0'] ],
[ 'id' => 4, 'name' => $_GET['v1'] ]
]);
Here's a fiddle that also demonstrates the behavior.

SugarCRM 6.5 CE how to properly validate form data using ajax?

I need to check the field phone_mobile for duplicate into the database. If a field value is not a duplicate then continue saving.
And if such a phone already exists in the database, then show the alert message and stop the process(form submission).
My actions:
In the file ./modules/Contacts/metadata/editviewdefs.php connected custom js file:
$viewdefs['Contacts']['EditView'] = array(
'templateMeta' => array(
'includes' => array (
array (
'file' => 'custom/include/javascript/custom_contact.js'
),
),
'form'=>array(
...
Works great.
In custom_contact.js file overload check_form(formname) function:
function check_form(formname)
{
if(formname === 'correct')
{
// This part does not work right for me
var _form = document.getElementById('EditView');
_form.action.value='Save';
SUGAR.ajaxUI.submitForm(_form);
return false;
}
if(formname === 'EditView')
{
// Ajax query works perfectly
$.ajax({
url : '/',
method : 'POST',
data : {},// some data
success : function(data) {
data = JSON.parse(data);
if(!data.success)
{
var text = 'The phone already exists';
return false;
}
check_form('correct');
}
});
}
return false;
}
But the if(formname === 'correct') ... block does not work correctly.
I need to stop the work of the form_save and include when necessary.
Please help to solve the problem correctly.I'm new to SugarCRM.
This is something related to javsacrip/jquery error handling and you can find many logics on google as well.
Try following code:
// DOM Ready
$('input#PHONE_FIELD_ID').on('change', function () {
handlePhoneValidation();
return false;
});
var clickAttr = $("#SAVE_BUTTON_ID").attr("onclick");
$("#SAVE_BUTTON_ID").attr("onclick","return handlePhoneValidation(); "+clickAttr);
function handlePhoneValidation(){
clear_all_errors();
var node = $('input#PHONE_FIELD_ID');
current_val = node.val();
/*
* Your validation will go here
* if condition fail then return false otherwise true
*/
return false;
}
I resolved this another way
./custom/modules/Module_name/metadata/editviewdefs.php
$viewdefs ['Accounts'] = [
'EditView' => [
'templateMeta' => [
'form' => [
'includes' => [
[
// include custom js file
'file' => 'modules/Module_name/file_name.js'
],
'buttons' => [
// Override save button and return after click custom function
0 => array (
'customCode' => '<input type="submit" name="save" id="save" onClick="this.form.return_action.value=\'DetailView\'; this.form.action.value=\'Save\'; return check_custom_data(\'EditView\'); " value="'.$GLOBALS['app_strings']['LBL_SAVE_BUTTON_LABEL'].'">',
),
'CANCEL',
After
modules/Module_name/file_name.js:
// Function check_custom_data() :
function check_custom_data(formname)
{
if(formname === 'correct')
{
var _form = document.getElementById('EditView');
_form.action.value='Save';
SUGAR.ajaxUI.submitForm(_form);
return check_form('EditView');
}
if(formname === 'EditView')
{
$.ajax({
url : '/',
method : 'POST',
data : { }, // Some data
success: function(data) {
data = JSON.parse(data);
if(!data.success)
{
// Some code
return false;
}
}
// If everything is ok
check_custom_data('correct');
}
});
return false;
}
This is working for me.

Delete record without a page refresh with ajax in php

I am working on a Cakephp 2.x but I don't think the problem has anything to do with the Cakephp. I want to delete a file without a page refresh.
HTML / PHP :
<div class = "success" style="display:none;">Deleted successfully </div>
<div class = "error" style="display:none;">Error </div>
JavaScript :
function openConfirm(filename, idImage) {
$.modal.confirm('Are you sure you want to delete the file?', function () {
deleteFile(filename, idImage);
}, function () {
});
};
function deleteFile(filename, idImage) {
var filename = filename;
$.ajax({
type: "POST",
data: {
idImage: idImage
},
url: "http://localhost/bugshot/deleteFile/" + filename,
success: function (data) {
if (data == 1) {
$(".success").fadeIn(500).delay(2000).fadeOut(500);
} else {
$(".error").fadeIn(500).delay(2000).fadeOut(500);
}
},
error: function () {
alert("error");
}
});
}
my images which is in foreach loop
this code is displaying the image
foreach($file as $files):?>
<?php $downloadUrl = array('controller' => 'bugshot', 'action' => 'downloadImages', $files['Image']['filename'], '?' => array('download' => true));
$imageUrl = array('controller' => 'bugshot', 'action' => 'downloadImages', $files['Image']['filename']);
?>
<?php echo $this->Html->link(
$this->Html->image($imageUrl),
$downloadUrl,
array('class' => 'frame', 'escape' => false)
);?>
Delete link
The code works great except that after the image or record is deleted the record/image is still displayed on the page until it is refreshed. How do I fix this?
You need to remove it with javascript.
$.ajax({
...
success: function (data) {
if (data == 1) {
$(".success").fadeIn(500).delay(2000).fadeOut(500);
$('img[src="/pathToImg/' + filename + '"]').remove(); // Remove by src
// $('#' + idImage).remove(); // Remove by ID.
} else {
$(".error").fadeIn(500).delay(2000).fadeOut(500);
}
}
...
});
Note : var filename = filename; means nothing because you are assigning filename argument to a new variable with the same name. You can just remove it.

how could i retrieve profile data in a modal using ajax in php?

here's the deal, i've created a search results page and i'd like to open a modal and retrieve profile data via ajax in php but i'm not too sure on how i can implement it. I've created the modal but but i don't know how i would go about getting the 'id' from clicking the search result, passing it onto ajax to retrieve the profile details.
Twitter has this kinda feature; when you click a username in a feed and it opens a modal and gives you a brief overview of the profile with a link to the full profile.
It would mean so much to me if someone could help me out or point me in the right direction! :)
P.S. I'm using codeigniter, if anyone is wondering what framework i'm using.
EDIT: here's the code
<?php
/*** PHP Search Results Loop ***/
if ($num > 0){
foreach ($query->result_array() as $row)
{
echo "link to ajax"'>";
}
} else {
echo "<strong>results not found :(</strong>";
}?>
<script> /* jQuery Runs When Result Has Been Clicked */
$('#ResultText').click(function() {
var targetid = {
id: /*Profile Id*/,
ajax: '1'
};
/* Modal Code */
$('.modal-backdrop, .modal-profilebox').css('display', 'block');
$('.modal-backdrop').animate({'opacity':'.50'}, 100, 'linear');
$('.modal-profilebox').animate({'opacity':'1.00'}, 200, 'linear');
$.ajax({
url: "<?php echo site_url('finder/modal'); ?>",
type: 'POST',
data: form_data,
success: function(profileData) {
$('.modal-profilebox').html(profileData);
}
});
return false;
});
</script>
Try something like this
public function ajax_user_profile($user_id)
{
if( !$this->input->is_ajax_request() )
{
redirect('/'); //only allow ajax requests
}
try
{
$user_profile = ''; //grab user object from DB
if( !$user_profile )
throw new Exception("Error Message");
}
catch(Exception $e)
{
log_message('error', $e->getMessage());
echo json_encode(array(
'error' => 1
));
exit;
}
$data = $this->load->view(array(
'some_view' => 'some_view',
'user' => $user_profile
), TRUE); //NO Template, just the view by adding TRUE
echo json_encode(array(
'error' => 0,
'data' => $data
)); //return view data
}
--
<a rel="modal" data-user-id="1" >Joe Bloggs</a>
--
(function($){
var userObj = {
init : function(){
this.getProfile();
},
getProfile : function(){
var modalSearch = $("a[rel='modal']");
modalSearch.on('click', function(){
//trigger the modal window
//request ajax
$.ajax({
url : BASEPATH + 'users/profile/' + $(this).data('user-id'),
type : 'POST',
dataType: 'json',
success : function(callback){
if(callback.error ==0)
{
$('.modal-profilebox').html(callback.data);
}
}
});
});
}
}
$(function(){
userObj.init()
});
})(jQuery);

CodeIgniter ajax call using jquery when call redirect it prints the whole page i div

no title that fits this bug but this how it goes, i have form with a submit button when pressed jquery ajax calls the controller and the form validation is done if it fails the form is redrawn if it passes the page is redirected to the home page with flash message successes and thats where the bug happens it redraws the whole page in the content(header header footer footer). i hope it makes sense seeing is believing so here is the code
side notes: "autform" is a lib for creating forms "rest" is a lib for templates.
the jquery code:
$("form.user_form").live("submit",function() {
$("#loader").removeClass('hidden');
$.ajax({
async :false,
type: $(this).attr('method'),
url: $(this).attr('action'),
cache: false,
data: $(this).serialize(),
success: function(data) {
$("#center").html(data);
$('div#notification').hide().slideDown('slow').delay(20000).slideUp('slow');
}
})
return false;
});
the controller
function forgot_password()
{
$this->form_validation->set_rules('login',lang('email_or_login'), 'trim|required|xss_clean');
$this->autoform->add(array('name'=>'login', 'type'=>'text', 'label'=> lang('email_or_login')));
$data['errors'] = array();
if ($this->form_validation->run($this)) { // validation ok
if (!is_null($data = $this->auth->forgot_password(
$this->form_validation->set_value('login')))) {
$this-> _show_message(lang('auth_message_new_password_sent'));
} else {
$data['message']=$this-> _message(lang('error_found'), false); // fail
$errors = $this->auth->get_error_message();
foreach ($errors as $k => $v){
$this->autoform->set_error($k, lang($v));
}
}
}
$this->autoform->add(array('name'=>'forgot_button', 'type'=>'submit','value' =>lang('new_password')));
$data['form']= $this->autoform->generate('','class="user_form"');
$this->set_page('forms/default', $data);
if ( !$this->input->is_ajax_request()) { $this->rest->setPage(''); }
else { echo $this->rest->setPage_ajax('content'); }
}
}
function _show_message($message, $state = true)
{
if($state)
{
$data = '<div id="notification" class="success"><strong>'.$message.'</strong></div>';
}else{
$data = '<div id="notification" class="bug"><strong>'.$message.'</strong></div>';
}
$this->session->set_flashdata('note', $data);
redirect(base_url(),'refresh');
}
i think it as if the redirect call is caught by ajax and instead of sending me the home page it loads the home page in the place of the form.
thanks for any help
regards
OK found the problem and solution, it seemed you cant call a redirect in the middle of an Ajax call that is trying to return a chunk of HTML to a div, the result will be placing the redirected HTML in the div.
The solution as suggested by PhilTem at http://codeigniter.com/forums/viewthread/210403/
is when you want to redirect and the call is made by Ajax then return a value with the redirect URI back to Ajax and let it redirect instead.
For anyone interested in the code:
The Jquery Ajax code:
$("form.user_form").live("submit", function(event) {
event.preventDefault();
$("#loader").removeClass('hidden');
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
cache: false,
dataType:"html",
data: $(this).serialize(),
success: function(data) {
var res = $(data).filter('span.redirect');
if ($(res).html() != null) {
[removed].href=$(res).html();
return false;
}
$("#center").html(data);
},
error: function() {
}
})
return false;
});
The PHP Controller
function _show_message($message, $state = true, $redirect = '')
{
if ($state)
{
$data = '<div id="notification" class="success"><strong>'.$message.'</strong></div>';
} else {
$data = '<div id="notification" class="bug"><strong>'.$message.'</strong></div>';
}
$this->session->set_flashdata('note', $data);
if ( !$this->input->is_ajax_request())
{
redirect(base_url() . $redirect, 'location', 302);
}
else
{
echo '<span class="redirect">'.base_url().$redirect.'</span>';
}
}
just use individual errors
json_encode(array(
'fieldname' => form_error('fieldname')
));
AJAX
success: function(cb)
{
if(fieldname)
{
{fieldname}.after(cb.fieldname)
}
}
see this

Categories