i have tried to call variable $hetest but it always return with true however i add false as a parameter when i am calling the function
//function which i call in javascript file
create_new_user_send_sms(user_Mobile_Number,false)
.fail(error => console.error(error))
.done(response => {})
//the ajax call of the function i created
function create_new_user_send_sms(mobile_number,hestatus){
return jQuery.ajax({
type : "POST",
url: ajax_object.ajax_url,
data: {
action : 'create_user_send_sms',
mobile_number : mobile_number,
auto_Login_status : "true",
he : hestatus,
},
success: function (data) {
},
error : function(error){
console.log("error:" + error);
}
});
}
//the code in the php function create_user_send_sms
$mobile_number = $_POST['mobile_number'];
$auto_Login_status = $_POST['auto_Login_status'];
$hetest = $_POST['he'];
$password = wp_generate_password( 4, false, false );
Try using the filter_validation function to treat boolean post vars:
$hetest = filter_var ($_POST['he'], FILTER_VALIDATE_BOOLEAN);
Related
I dont understand what i did wrong, can anyone give me a suggestion on what causes the above error below is my code. I can confirm that, i am hitting the route, succesfully because the code inside get it executed. I am also adding the 1 value at the end, to be passed it to json as per wp_send_json_success. At this point i dont know what to next, can anyone explaint to me, on what is going on?
route.php
function update_employee_photo($request){
global $wpdb;
$data_with_photo = array(
'photo' => $request['photo'],
'photo_privacy' => $request['photoPrivacy'],
'photo_description' => $request['photoDescription']
);
$data_null_photo = array(
'photo_privacy' => $request['photoPrivacy'],
'photo_description' => $request['photoDescription']
);
$data = ($request['photo'] != "null") ? $data_with_photo : $data_null_photo;
$where = array('wp_user_id' => get_current_user_id());
$result = $wpdb->update("aupair_registered_employee", $data, $where);
if($result){
wp_send_json_success($result, 200, 1);
} else {
wp_send_json_error($wpdb->last_query);
}
die();
}
add_action('rest_api_init', function(){
register_rest_route( 'activeAupair/v1', '/updateEmployeePhoto', [
'methods' => 'POST',
'callback' => 'update_employee_photo'
]);
});
file.js
$.ajax({
type: 'POST',
url: myAjax.restURL + 'activeAupair/v1/updateEmployeePhoto',
contentType: 'application/json',
datatype: 'json',
data: {
photo: photo,
photoPrivacy: getPhotoPrivacy(),
photoDescription: getPhotoDescription()
},
beforeSend: function (xhr) {
xhr.setRequestHeader('X-WP-Nonce', myAjax.nonce);
},
success: function(response){
console.log('TYPE OF ', typeof response);
console.log('RESPONSE ', response);
msg.empty();
msg.append($('<p id="required"></p>').text('Updated'));
uploadBtn.attr('value', 'Update');
uploadBtn.attr('disabled', false);
},
error: function (xhr, ajaxOptions, thrownError) {
},
complete: function(data){
console.log('COMPLETE ', data);
}
});
As per the wordpress wp_send_json_success() function expect third parameter 1(default 0) to encode it into JSON format (see the reference). So you need to pass the status code as second parameter and 1 for the JSON object.
wp_send_json_success($result, 200, 1);
I try to load data from service yelp, no problem with the request, but I can't push it to array and return it.
I need to get ajax result in every iteration.
How to stop it until ajax result has received?
can anyone help me?
this.getDataForPlaces = function(addresses){
var locationDescs = [];
_.each(addresses, function(address){
var promise = getLocationDesc(address).then(function(data) {
locationDescs.push(data);
});
})
return locationDescs;
};
var getLocationDesc = function(address){
var parameters = [];
var message = {
'action' : 'http://api.yelp.com/v2/search',
'method' : 'GET',
'parameters' : parameters
};
OAuth.setTimestampAndNonce(message);
OAuth.SignatureMethod.sign(message, accessor);
var parameterMap = OAuth.getParameterMap(message.parameters);
return $.ajax({
'url' : message.action,
'cache': true,
'method':message.method,
'data' : parameterMap,
'dataType' : 'jsonp',
'jsonp' : 'callback',
'success':function(data){
console.log(data);
}
});
};
You have to return the data variable instead of ajax function like this : replace the following
return $.ajax({
'url' : message.action,
'cache': true,
'method':message.method,
'data' : parameterMap,
'dataType' : 'jsonp',
'jsonp' : 'callback',
'success':function(data){
console.log(data);
}
});
with
$.ajax({
'url' : message.action,
'cache': true,
'method':message.method,
'data' : parameterMap,
'dataType' : 'jsonp',
'jsonp' : 'callback',
'success':function(data){
return data;
}
});
for pausing / stoping the loop until the ajax request completes you can replace the following :
var promise = getLocationDesc(address).then(function(data) {
locationDescs.push(data);
});
with
var promise = $.when(getLocationDesc(address)).done(function(data){
locationDescs.push(data);
});
if above does not work then use the following and replace the whole loop with following
var locationDescs = [];
_.each(addresses, function(address){
locationDescs.push(getLocationDesc(address));
});
$.when.apply($,locationDescs).done(function(){
});
Don't return complete ajax function , just inside the success function of ajax return the data like this : return data; because return whole ajax function it is not an data that you are getting from services , you have to return data variable.
this is how the javascript looks like
<script type="text/javascript">
$(document).ready(function () {
$('#loginButton').click(function () {
//this.disabled = true;
debugger;
var data = {
"userid": $("#username").val(),
"password": $("#password").val()
};
$.ajax({
url: "/Account/LoginPost",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
},
error: function () {
alert('Login Fail!!!');
}
});
});
});
I am getting the alert('Login fail') also debugger not getting hit.
I am using jquery 1.9.1 and have included unobstrusive
my controller is this as you can i am passing string values not object values
to the controller so stringify is justified here
[HttpPost]
public JsonResult LoginPost(string userid, string password)
{
using (someentities wk = new someentities())
{
var LoginUser = wk.tblUsers.Where(a => a.Username.Equals(userid)&&a.Password.Equals(password)).FirstOrDefault();
if (LoginUser != null)
{
FormsAuthentication.SetAuthCookie(userid,false);
Session["Username"] = LoginUser.Username;
Session["Password"] = LoginUser.Password;
Session["Name"] = LoginUser.Name;
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
else
{
TempData["Login"] = "Please Enter Correct Login Details";
return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
}
}
// If we got this far, something failed, redisplay form
}
when page is loading these error are shown
$(..) live is not a valid function in
(anonymous function) # jquery.unobtrusive-ajax.js:115
(anonymous function) # jquery.unobtrusive-ajax.js:163
take a look to the success function
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
}
you are using multiple ", combine it with the single one ', this is a syntax error, try to check the code on an editor such as Atom, to avoid this kind of errors
Stringify converts an object to a string. Have you tried passing data an object instead of a string? Try replacing JSON.stringify(data), with data?
I'm trying to call Javascript function inside controller action method, Is there any right way to call setTimeout() to be invoked on certain condition inside controller action method ?
window.setTimeout(function() {
alert("test");
$.ajax({
type: "POST",
url: "'.$this->createUrl("/operator/createViopNode/").'",
data: {
id: '.$bc_id.',
callid:"'.$num.'",
taskid:'.$this->taskid.'
},
success: function(msg){
var ifrm = document.getElementById("frame");
ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;
ifrm.document.open();
ifrm.document.write(msg);
ifrm.document.close();
},
error: function (jqXHR, textStatus, errorThrown){
alert("" + textStatus + ", " + errorThrown);
}
});
}, parseInt('.$tps_call.'));
I need to write above js function inside controller action method, how to write this ?
Index.csHtml
function abc()
{
alert("called")
}
now Ajax Call function
function ExecuteAjax(URL,Data,Success)
{
try {
$.ajax({
type: "post",
url: URL,
data: Data,
contentType: "json",
success: function (data) { if (typeof Success == "function") { Success(data); } }
})
} catch (e) {
alert(e.message)
}
}
Call ajax like this
ExecuteAjax("/Home/FillColorDropDown", "", function (data) {
eval(data.script);
});
return from controller
if(demo=="true")//put condition here whatever you want
{
string strscript="abc();";
}
protected JObject jobj = new JObject();
jobj.Add("Script", strscript);
return Json(jobj);
Execute js function when controller return success
You should register your javascript function like this:
function actionTest(){
$cs = Yii::app()->clientScript;
$cs->registerScript('my_script', 'alert("Hi there!");', CClientScript::POS_READY);
$this->render('any_view');
}
source
I'm attempting to get started with google wallet and am generating a jwt token via an ajax request.
When a user hits the purchase button it fires the purchase() function which in turn sends off some data to get the jwt using the get_jwt_token_for_user() function. I've set the ajax request to not be asynchronous to ensure that the jwt is sent to the google payments handler.
However the purchase() function seems to continue before the jwt is returned by the get_jwt_token_for_user() function. The log output shows that the numbers 1 and 2 are printed to console before the jwt is printed to the console from the get_jwt_token_for_user() function.
function get_jwt_token_for_user(the_key)
{
var JwtTokenURL = "/get_jwt_token";
var the_user_name = $('#user_name').val();
var the_user_email = $('#user_email').val();
var the_user_number = $('#user_number').val();
$.ajax({
type: "Get",
url: JwtTokenURL,
data: {user_number : the_user_number, user_name : the_user_name, user_email : the_user_email, the_d_key : the_key},
async: false,
success: function(result) {
var myObject = JSON.parse(result);
console.log(myObject.jwt_token);
return myObject.jwt_token
},
failure: function(fail){ alert(fail); }
});
}
function purchase(the_key)
{
console.log("1");
var jwt_token = get_jwt_token_for_user(the_key);
console.log("2");
if (jwt_token !== "")
{
console.log(jwt_token);
goog.payments.inapp.buy({
parameters: {},
'jwt' : jwt_token,
'success' : successHandler,
'failure' : failureHandler
});
}
}
Any idea what I can do to ensure that the ajax request has returned the data before the purchase() function marches on without the jwt value?
Your get_jwt_token_for_user function doesn't return anything, you need something more like this:
function get_jwt_token_for_user(the_key) {
//...
var myObject;
$.ajax({
//...
success: function(result) {
myObject = JSON.parse(result);
},
//...
});
return myObject ? myObject.jwt_token : '';
}
Returning something from your success callback doesn't cause that value to be returned by $.ajax and JavaScript functions do not return the value of their last expressions, you must include an explicit return if you want your function to return something.
You should also stop using async:false as soon as possible, it is rather user-hostile and it is going away. Your code should look more like this:
function get_jwt_token_for_user(the_key, callback) {
//...
$.ajax({
type: "Get",
url: JwtTokenURL,
data: {user_number : the_user_number, user_name : the_user_name, user_email : the_user_email, the_d_key : the_key},
success: function(result) {
var myObject = JSON.parse(result);
callback(myObject.jwt_token);
},
failure: function(fail){ alert(fail); }
});
}
function purchase(the_key) {
get_jwt_token_for_user(the_key, function(jwt_token) {
if (jwt_token !== "") {
//...
}
});
}