I'm trying to verify data.announce but i'm getting this error "Uncaught TypeError: Cannot read property 'announce' of null"
So here is my code
php file:
$return = array("msg" => "You'll recive an email with instructions!");
return json_encode($return);
jquery:
$("form[id='common-handler/register'] #submit").click(function(e) {
e.preventDefault();
if(locked == 1)
return false;
locked = 1;
var _form = $(this).closest('form').attr('id');
$.post("/"+_form, $(this).closest('form').serialize(), function(data) {
if(!isEmpty(data.announce))
$("#search_bar").html(data.msg).fadeIn("slow");
else
$("form[id='" + _form + "'] p.msg").text(data.msg);
}, "json");
});
function isEmpty(str) {
return (!str || 0 === str.length);
}
You cannot return data in a PHP file, unless you're including it somewhere in another PHP file, so you will need this to get your $.post(), working via JSON output:
echo json_encode(array("msg" => "You'll recive an email with instructions!"));
exit(0);
try this:
return $return = json_encode( array( "announce" => array("msg" => "You'll recive an email with instructions!") ) );
You don't have "announce" as one of the keys in the array you are returning, only "msg"
You want:
array("msg" => "You'll recive an email with instructions!", "announce"=>"My announcement");
Try changing:
if(!isEmpty(data.announce))
to:
if(null == data.announce)
Related
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.
I have a file ajax.php which I am using to process data passed through jquery. I have this particular line of code called on successful form verification:
$.post("/ajax.php",{'request': 'emailLogin', 'loginmail': mail, 'loginpass': pass}, function(data) {} );
data in my case is: {"valid":true}{"auth":false}which is returned as a response from ajax.php, but I can't seem to file the correct way of defining "auth" and a variable with value "false".
My ajax.php is just checking if login and password are in the database and than echo json_encode(array('auth' => false)); or echo json_encode(array('auth' => true)); depending on the result. But it has also contain these lines:
if( isset($_POST['loginmail'])) {
$usermail = htmlspecialchars($_POST['loginmail']);
if (!filter_var($usermail, FILTER_VALIDATE_EMAIL)) {
$response = array('valid' => false, 'message' => 'You did not enter a correct email address.');
} else {
// All good
$response = array('valid' => true);
}
}
echo json_encode($response);
Don't echo json_encode($response) separately from the authentication result, you need to combine them. After you do the authentication, do:
$response['auth'] = $result_of_authentication;
then do
echo json_encode($response);
Once you do this, you should be able to access data.auth in Javascript. You should tell $.post that it's returning JSON:
$.post("/ajax.php",{
'request': 'emailLogin',
'loginmail': mail,
'loginpass': pass},
function(data) {
alert(data.auth);
},
"json");
Based on your PHP code you should be able to access the valid attribute like so:
$.post("/ajax.php",{'request': 'emailLogin', 'loginmail': mail, 'loginpass': pass}, function(data) {
var auth = data.valid;
if (auth) {
// do something!
} else {
// do something else!
}
});
Also there is a bug in your PHP code, you need to set up a default value for $response like so:
$response = array('valid' => false, 'message' => 'Email address is required');
if( isset($_POST['loginmail'])) {
$usermail = htmlspecialchars($_POST['loginmail']);
if (!filter_var($usermail, FILTER_VALIDATE_EMAIL)) {
$response = array('valid' => false, 'message' => 'You did not enter a correct email address.');
} else {
// All good
$response = array('valid' => true);
}
}
echo json_encode($response);
Otherwise if $_POST['loginmail'] is not set your app with throw an undefined variable exception
EDIT:
As Barmar pointed out in his answer, you should only echo a response back once time to avoid creating an invalid response. Any data you need should be sent back in a single array. I don't see you doing that in your PHP code but you do make mention of echoing another array ['auth' => false] which will not work the way you want it to
Here is my Controller's return in case of error
return "0".",".$messages = $validator->messages();
So the ouput will be
0,{"firstname":["The firstname field is required."]"lastname":["The lastname field is required."]}
And splitting with ,
var dat = data.split(",");
if(dat[0] == "0")
{
$('#stage').html(dat[1]);
}
So, if i have a first error the output will be
{"firstname":["The firstname field is required."]
How can i make splitting or handle it to make display only the errors
i.e.,The firstname field is required.
Update :
As Codebird suggests :
return $validator->messages();
if(data != '')
{
obj=JSON.parse(data);
var error_string='';
$.each(obj, function(entry) {
error_string+=obj[entry]+'<br />';
});
$('#stage').html(error_string);
} else {
$('#stage').html('Success Saving');
}
Console :
As I commented above, I would have handled this, this way:
first thing, you have to json_encode the $validator->messages() as it is an array, so your php becomes like this:
The return
return json_encode($validator->messages());
then the JS:
if(data != '')
{
obj=JSON.parse(data);
var error_string='';
$.each(obj, function(entry) {
error_string+=obj[entry]+'<br />';
});
$('#stage').html(error_string);
} else {
//Success goes here.
}
Try this approach:
// php - I assume $validator->messages() returns json
$response = array(
'messages' => json_decode($validator->messages()),
'success' => false,
);
echo json_encode($response);
and
// javascript
if (!data['success']) {
$.each(data['messages'], function(index, value) {
$('#stage').append(value + '<br/>');
});
}
Have a look here: http://jsfiddle.net/hzf5tuuc/
I'm making an ajax call in a meta box and returning some very simple data. However, it keeps throwing an error:
parsererror
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
Here's the ajax call:
uid = new Date().getTime();
appReq = jQuery.ajax({
type : 'post',
dataType : 'json',
url : 'admin-ajax.php',
data : { action : 'get_app_sidebars', post_id : currentApp, uid : uid }
});
appReq.done(function(data){
if(data.widgetNum > 0 && data.widgetName != '' && data.widgetBase != '') {
alert(data);
}
else {
// do something here
}
});
appReq.fail(function(jqXHR, textStatus, errorThrown){
alert(textStatus + '\n' + errorThrown);
});
And here's the php:
function get_app_sidebars(){
// get the meta for a custom post type
$meta = $this->get_app_meta($_REQUEST['post_id']);
$result['widgetNum'] = $meta['num_widgets'];
$result['widgetName'] = $meta['widget_name'];
$result['widgetBase'] = $meta['widget_base'];
$result = json_encode($result);
echo $result;
}
The problem comes in when I get the data back:
{"widgetNum":"6","widgetName":"Custom Sidebars","widgetBase":"my-custom-sidebars"}0
Ok, that "0" at the end is in the response when I look at this in firebug. This is driving me nuts, and I can't figure out WTF is going on with the JSON as it's being sent to the browser. If I trim the 0 and run it through jsonlint, it passes.
I'd suggest using wp_send_json_success, as it takes care of everything (json encoding, echo and die()):
function get_app_sidebars()
{
$meta = $this->get_app_meta($_REQUEST['post_id']);
if( $meta )
{
$result['widgetNum'] = $meta['num_widgets'];
$result['widgetName'] = $meta['widget_name'];
$result['widgetBase'] = $meta['widget_base'];
wp_send_json_success( $result );
}
else
}
wp_send_json_error( array(
'error' => 'Custom error message'
));
}
}
Also, make the necessary security checks with check_ajax_referer.
Somewhere in your code, a 0 is being printed. It's not in the function you gave, but that function is obviously getting called somewhere. You can confirm this by changing echo $result to die($result), although this doesn't fix the root problem, which is that somewhere you have a print statement that shouldn't be there.
You need to add:
die();
after echoing the results.
I would like to save a message in PHP variable and send it back with my other array variable that is already coming back. For instance, I have some error checking that takes place inside the PHP code and would like a string variable with the specific message sent back for use in my javascript.
Here is the PHP:
<?php
include('config-searchres.php');
$term = $_POST['resid'];
$sql = mysql_query("SELECT * FROM ap_form_8 WHERE id = '$term'"); //select first name (element_1_1) from form #8
if ($row = mysql_fetch_array($sql)){ //if reservation number exists
if ($row['element_11'] != 'Cancelled'){ //if reservation has not already been cancelled
if (strtotime($row['element_3']) >= strtotime(date("Y-m-d"))){ //if reservation has not already passed date
echo json_encode($row);
}
else //Reservation already passed (old reservation)
{
echo 'passed';
}
}
else //Reservation already cancelled
{
echo 'cancelled';
}
}
else //Reservation not found
{
echo 'not found';
}
mysql_close();
?>
As you can see, there are 3 different messages, "passed", "cancelled", and "not found"... if one of these conditions exists, I would like to send this string back to my javascript so I can display it in a DIV. However, I also want to send the $row data with it.
My javascript:
<script type="text/javascript">
$(document).ready(function(){
resetForms('reservation');
$('#form-reservation').submit(function(event){
event.preventDefault(); //the page will no longer refresh on form submit.
var resCheck = $(this).find('input[class="reservationid"]').val(); //now we have the reservation ID, let's perform our check.
$.ajax({
url: 'inc/searchres.php',
type: 'POST',
data: 'resid='+resCheck,
success: function(data){ //data is all the info being returned from the php file
$('#reservation-id').val(resCheck); //add read ID back into text box
var jsonData = $.parseJSON(data); //parse returned JSON data so we can use it like data.name, data.whatever
//****I wanted the line just below this to display the appropriate message sent back from the PHP****
$("#res-message").html('<a>Reservation ID Located, Information is displayed below</a>');
$('#json-reservation').populate({personal_first_name:jsonData['element_1_1'],personal_last_name:jsonData['element_1_2'],personal_phone_1:jsonData['element_7'],personal_email:jsonData['element_2'],reservation_status:jsonData['ADD THIS CELL'], reservation_id:jsonData['id'], reservation_date:jsonData['element_3'],reservation_time:jsonData['element_4'],reservation_party:jsonData['element_5'],reservation_special_request:jsonData['element_6'],reservation_using_coupon:jsonData['element_9'],reservation_coupon_code:jsonData['element_10'],reservation_status:jsonData['element_11']});
$("#res-cancel-message").html('');
},
error: function(){
$("#res-message").html('<a>There was an error with your request</a>');
$("#res-cancel-message").html('');
}
});
});
});
</script>
I marked with asterisks where I populate the DIV with a static message at this time, this is the line where I would populate the message from PHP. Any ideas?
You could add that message as one of your JSON properties and then search for it appropriately.
You can always wait a little with echoing json encoded $row.
Add $row and you message to an array variable, which you json encode and echo out.
Not 100% sure about syntax details/dots
$response_array = array('message' => 'yourmessage', 'row' => $row);
echo json_encode($response_array);
Send both in ajax. LIke
Dont echo anything in the body of your if else, just store the message in variable, say, $message = 'passed', now do this at the end of your php request page:
echo json_encode(array('message_js'=>$message, 'row_js' => $row));
This sends json array as responce so u can send as much variables in it as much u like. Just put them in an array() and convert them into json using json_encode()
to convert into json and pass as response. When recieved in success function of your ajax, just decode the two json variables : message_js and row_js.
You can use parsejson of jquery to get your variables then
Just pass the appropriate message from the server .let us suppose your message is in message variable:
$("#res-message").html('' + data.message +'Reservation ID Located, Information is displayed below');
By the time you convert your row data into the $row, it is an array. You can, if you dare, simply add your message to that array before you json_encode it.
$row["message"] = ...
You can do it this way:
$result = array();
if ($row = mysql_fetch_array($sql)){ //if reservation number exists
if ($row['element_11'] != 'Cancelled'){ //if reservation has not already been cancelled
if (strtotime($row['element_3']) >= strtotime(date("Y-m-d"))){ //if reservation has not already passed date
$result = array('status' => 'OK', 'data' => $row);
}
else //Reservation already passed (old reservation)
{
$result = array('status' => 'passed', 'data' => $row);
}
}
else //Reservation already cancelled
{
$result = array('status' => 'cancelled', 'data' => $row);
}
}
else //Reservation not found
{
$result = array('status' => 'not found', 'data' => null);
}
echo json_encode($result);