This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
i have this script for submitting a form using jquery ajax, everything works fine except i can only get two responses, the loading part is implemented but the rest of them i can only get the else statement. the else if, none is working.
the json statement works just fine. and the data is passed to php successfully but the responses are not according.
(function($) {
'use strict';
const FormFunction = function(){
const checkSelectorExistence = function(selectorName) {
if(jQuery(selectorName).length > 0){return true;}else{return false;}
};
let registerForm = function() {
if(!checkSelectorExistence('.registration-form')){return;}
jQuery('.registration-form').on('submit', function( event ) {
event.preventDefault();
let response = $('.loading').addClass('show').show();
jQuery(this).find(".message").addClass('active').show('slow');
const formData = new FormData(this);
const formAction = jQuery(this).attr('action');
jQuery.ajax({
type: 'POST',
url: formAction,
data: formData,
contentType: false,
cache: false,
processData:false,
dataType: 'json',
beforeSend : function(){
$('.info').addClass('show').show('slow');
},
complete : function(){
$('.registration-form .message').html(response).delay(5000).hide('slow');
$('.registration-form')[0].reset();
},
success : function(data)
{
if(data.status === 1){
response = $('.success').addClass('show').show('slow');
}
else if(data.status === 2) {
response = $('.taken').addClass('show').show('slow');
}
else if(data.status === 0){
response = $('.empty').addClass('show').show('slow');
}
else {
response = $('.error').addClass('show').show('slow');
}
$('.registration-form .message').html(response).delay(5000).hide('slow');
$('.registration-form')[0].reset();
},
error : function(data){
$('.error').addClass('show').show('slow');
$('.registration-form')[0].reset();
},
});
});
}
/* Functions Calling */
return {
afterLoadThePage:function(){
registerForm();
},
}
}(jQuery);
/* jQuery Window Load */
jQuery(window).on("load", function (e) {FormFunction.afterLoadThePage();});
})(jQuery);
Based on some comments that we traded I managed to test it out and found out, what is the root of your problem. Even thought you are setting dataType as JSON, what you actually pass from PHP is a string of value "{\"status\":1}". This is currently the content of your data variable in Success function of your AJAX call.
Adding following line of code at begging of your Success function will do what you want it to do: data = JSON.parse(data);. This will parse string returned by PHP into an JSON object in JS which will create data.status instance holding desired value of number type.
I did some test on my end and it worked as expected with IF and ELSE IF as well.
Related
I am really new to CefSharps Chromium browser and have difficulty figuring out how to get the result of a jquery ajax request.
My first attempt was to pass my AJAX requesto to EvaluateScriptAsync. In fact the script works. It does exactly what I want, but I do not get any results/status codes, because my Cef-Task does not wait until AJAX has completed its work.
Here an example (just a sample code):
var tasks = pdBrowser.EvaluateScriptAsync(#"
(function(){
$.ajax({
type: ""POST"",
dataType: ""json"",
cache: false,
url: ""_resources/php/ajaxRequests.php"",
async: false,
data: {
action: ""insertCrossPlatform"",
type: """",
values: JSON.stringify(""foo bar"")
},
success: function(response) {
if (typeof response === 'string' && response.substring(0, 5) == ""ERROR"")
{
return response;
}
else
{
//pageReload();
return ""OK"";
}
},
error: function(xhr, textStatus, errorThrown) {
return errorThrown + ""\n"" + xhr.responseText;
},
complete: function() {
return ""COMPLETE"";
}
});
})();", null);
tasks.ContinueWith(t =>
{
if (!t.IsFaulted)
{
var response = t.Result;
if (response.Success)
{
if (response.Result != null)
{
MessageBox.Show(response.Result.ToString());
}
}
else
{
MessageBox.Show(response.Message, "Ein Fehler ist aufgetreten", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
}, TaskScheduler.Default);
Afterwards I have read that there is a SchemeHandler, but I do not properly understand how to implement it. Can anyone help me out?
Thanks in advance.
Firstly SchemeHandler is unlikely to be suitable in this scenario, you would typically implement a SchemeHandler when your providing the response.
Most people choose to bind an object, and call a method on their bound object when they wish to communicate with the parent application. See the FAQ for an example. https://github.com/cefsharp/CefSharp/wiki/Frequently-asked-questions#3-how-do-you-expose-a-net-class-to-javascript
With 49.0.0 you can implement ResponseFilter to gain access to the underlying response buffer, it's complex and not well documented, so if your not comfortable digging through reference C++ code then this option isn't for you. Here's a reference https://github.com/cefsharp/CefSharp/blob/cefsharp/49/CefSharp.Example/Filters/PassThruResponseFilter.cs#L17
Something that I did was create an element on the page through javascript with an ID that is the response of the ajax call. So for example, when you make an ajax call assign an ID to the ajax call.
When the ajax call returns, write an element on the page with the pre-assigned id and callback information. Then you can just use cefsharp to read the element content from the page and this will be your callback information.
var myDivElement =document.getElementById('textareaInfo');
if( myDivElement === null)
{
var input = document.createElement('textarea');
input.id = "textareaInfo";
input.value = "Test"
input.rows="4";
input.cols="50";
input.style="height:100%;width:900px;"
var dom = document.getElementsByClassName("page-body")[0];
dom.insertAdjacentElement('afterbegin', input)
}
Then later with ajax
var root = 'https://jsonplaceholder.typicode.com';
var _holder = callbackObj;
callbackObj.showMessage(""ajax"");
$.ajax({
url: root + '/posts/1',
contentType: 'application/json; charset=utf-8',
method: 'GET',
complete: function(data){
},
success: function(response) {
$(#'textareaInfo').value(response);
}
}).then(function(data) {
callbackObj.showMessage(data);
});
Then read the texarea from cefsharp in c#
chromeBrowser.GetMainFrame().EvaluateScriptAsync(function()...$(textareaInfo).value).Result
You can use PostMessage javascript method to notify .NET application:
CefSharp.PostMessage('Your data Here');
Here is .NET code example for headless browser:
var browser = new ChromiumWebBrowser("", null, RequestContext);
browser.JavascriptMessageReceived += (sender, e) =>
{
if ((string)e.Message.notificationid == "notification1")
{
// Your processing code goes here
}
};
browser.Load(destinationUrl);
browser.ExecuteScriptAsync("(function() { ... ; CefSharp.PostMessage({data: data, notificationid: 'notification1'});})()");
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am not able get the returned value after ajax call. I can see that values are being returned but when I do console.log() it shows undefined. Is there something wrong in my approach.
var base_path = "http://localhost/lab/theapp/api/"
$(function () {
var url = base_path + "tasks"
var type = "post"
var data = ""
var get = submit_me(type, data, url)
console.log(get)
})
function submit_me(type, data, url) {
try {
$.ajax({
url: url,
type: type,
data: data,
dataType: "json",
beforeSend: function (request) {
request.setRequestHeader("X-CSRF-Token", $.cookie("token"))
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//alert('page_login_submit - failed to login');
console.log(JSON.stringify(XMLHttpRequest))
console.log(JSON.stringify(textStatus))
console.log(JSON.stringify(errorThrown))
},
success: function (r) {
if (r.sessid) {
var sessid = r.sessid
var session_name = r.session_name
var token = r.token
jQuery.cookie("token", token)
return r
}
},
})
} catch (error) {
console.log(error)
}
}
Your ajax call will take some time to retrieve that values. You cannot pass the value directly to the variable. Write the code in ajax success function. ie console.log() in ajax request function. That would follow the delay caused by the ajax call. Try this link https://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings Check the async attribute here and experiment.
I'm using Symfony2.
I want to do some validation in a php controller in that way:
if ($request->isMethod('POST')) {
$old_name = $category->getName();
$new_name = $request->get('value');
if ($same == 0) {
//valid
$new_response = new Response($name);
return $new_response;
} else {
//not valid
$old_response = new Response($old_name);
return $old_response;
}
}
Is there a way to check in the .js file which response was sent - $new_response or $old_response? The point in this is to append to the body a message saying to the user that he entered a duplicate value if the response sent was $old_response. And to remove this message if the response sent was $new_response.
Thank you very much in advance! :)
You might use JSON for returning a set of data, not only the name.
Controller:
if ($same == 0) {
//valid
$new_response = new JsonResponse(array('type' => 'new', 'name' => $name));
return $new_response;
} else {
//not valid
$old_response = new JsonResponse(array('type' => 'old', 'name' => $old_name));
return $old_response;
}
JS:
$.ajax({
url: '...',
type: 'POST',
dataType: 'json',
data: 'value=...',
success: function(json) {
if (json.type == 'new')
// this is new response
else
// this is old or some other response
alert(json.name); // this is the response body (old or new name)
}
});
See also:
Creating a JSON response
jQuery.ajax()
Simply look in the response body. The first constructer parameter is the content (normally a parsed template) of the response.
Maybe you want to use a JsonResponse($data)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to return the response from an AJAX call from a function?
I'm trying to get some HTML content via ajax. But for some reason, though the HTML makes it to the ajax function, when I try to use it as a returned value, I get undefined.
Like this:
function get_additional_options(name) {
var post = $.ajax({
type: 'post',
url: 'order_queries_templates/html/' + name + '_additional_options.php?<?=time()?>',
//data:'product_id=' + product_id,
dataType: 'html'
});
post.done(function (p) {
console.log(p); //prints out all the HTML just as I would expect
return p;
});
}
but when I try to get the HTML to append it to my page like this
if (has_additional_options == "t"){
var html_to_append = get_additional_options(name);
console.log(html_to_append); // undefined
}
It is the same result if I use the done() method, or just return the value as a success callback. What is my error?
You can't return values from asynchronously called functions.
You should return post (i.e. the result of $.ajax) and then register a .done handler outside of your function:
function get_additional_options(name) {
return $.ajax({
...
});
};
if (has_additional_options == "t") {
get_additional_options(name).done(function(p) {
console.log(p);
});
// NB: code execution continues here immediately - don't do anything
// else here - all further stuff must be done in the above callback
}
You are returning the HTML value inside the anonymous function.
You're basically passing it to the post.done method.
Maybe it's better to use events in this case since you're running asynchronous code here.
function get_additional_options(name) {
var post = $.ajax({
type: 'post',
url: 'order_queries_templates/html/' + name + '_additional_options.php?<?=time()?>',
//data:'product_id=' + product_id,
dataType: 'html'
});
post.done(function (p) {
$("body").trigger("html_loaded",[p]);
);
}
$("body").on("html_loaded", function (htmlData) {
// Do something with your HTML data here.
$(this).append(htmlData);
});
function createLead(values) {
var url = "/api/v1/createlead/?apikey=XXXX-XXXX-XXXX-XXXX";
//debugger;
$.ajax({
type : "POST",
contentType : "application/x-www-form-urlencoded; charset=UTF-8",
url : url,
data : values,
success: function (result) {
result = $.parseJSON(result);
if (result.redirect) {
$(window).trigger('googleEvent' , 'regFailure');
window.location.href = values.returnUrl;
return;
}
else if (result.status === "OK" ) {
if (result.data.isPixelToBeFired){
$(window).trigger('googleEvent' , 'pixelFire');
}
else {
$(window).trigger('googleEvent', 'noPixelFire');
}
olp_sLeadId = result.data.leadId;
olp_sPathId = result.data.pathId;
$(window).trigger('googleEvent', 'regSuccess');
window.location = "path.html?curPathId=" + olp_sPathId
+ "&curLeadId=" + olp_sLeadId; // Enter the path
}
else {
// console.log('FAIL' , result , values);
$(window).trigger('googleEvent' , 'regFailue');
window.location.href = values.returnUrl;
return;
}
},
statusCode: {
404: function() {
$(window).trigger('googleEvent' , 'createLead404');
window.location.href = values.returnUrl;
//console.log('Something is seriously wrong');
return false;
}
},
failure: function (result) {
$(window).trigger('googleEvent' , 'createLeadFailure');
window.location.href = values.returnUrl;
//console.log('Something is seriously wrong');
return false;
}
});
}
I've been scratching my head here for a while, all version of IE seem to have an issue with this call. A few important pieces of information here:
values is a data object and I can verify that it has data.
All window .trigger functions are for Google analytics tracking, they are used in several other parts of the code and do not present an issue.
In IE the function seems to be spaced oddly, all the other functions line up properly, but this one seems to be aligned oddly, making me wonder if something isn't parsing right?
The success function appears to not run, and the failure and statusCode functions are completely ignored. This leads me to wonder if this isn't an issue with the jQuery methods, but they function elsewhere in the code?
I guess there is an issue with cache. The IE automatically cached the ajax request. To overcome this problem set option cache: false in you $.ajax code.
Example :
$.ajax({
type : "POST",
contentType : "application/x-www-form-urlencoded; charset=UTF-8",
url : url,
data : values,
cache : false,
// existing stuff
});
Hope this will help !!