I had a problem with combining som javascript functions through one function. I'm trying to build a little system to show at work. A kind a show how it could improve. Not for deployment.
The functions look like this.
// To choose an errand or with a zero start a new errand.
function buildErrandBox(number)
{
$.ajax({
url: 'db/buildErrandBox.inc.php',
type:'POST',
dataType: 'json',
data: { customerNumber: $("#customerNumber").val(), errandNumber: number },
success: function(build){ $('#newErrandsBoxResult').empty(); $('#newErrandsBoxResult').append(build.buildForm); $('#newErrandsBoxTextResult').empty(); $('#newErrandsBoxTextResult').append(build.buildText); showMinorContent('#newErrands'); $('#errandArea').val(build.area); $('#errandGroup').val(build.group); $('#errandType').val(build.type); escalateOptions(); getEscalationGroups(); },
error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); }
});
}
// To save changes on a errand.
function saveErrand()
{
$.ajax({
url: 'db/saveErrandsForCustomer.inc.php',
type:'POST',
dataType: 'json',
data: { id: $("#errandID").val(),
telephone: $("#errandTelephoneNumber").val(),
email: $("#errandEmail").val(),
area: $("#errandArea").val(),
group: $("#errandGroup").val(),
type: $("#errandType").val()
},
success: function(output_string){ showCustomerErrands(); },
error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); }
});
}
// To save a new note on an errand.
function saveTextForErrand()
{
$.ajax({
url: 'db/saveErrandsText.inc.php',
type:'POST',
dataType: 'json',
data: { id: $("#errandID").val(), text: $("#newTextForErrandTextArea").val() },
success: function(output_string){ buildErrandBox($("#errandID").val()); },
error: function (xhr, ajaxOptions, thrownError) { alert(xhr.status); alert(thrownError); }
});
}
These are three seperate functions that work when a use the buttons on the webpage. First click to start a new errand. The change what type of errand it is. Put in some notes. And save the errand. All works fine.
In the background the build errand function build the whole box of inputs and selects to show the errand. But the next function to save the errand recognizes the errand number and saves the errand in the database.
But when i combine these like below
function preMadeErrand(area, group, type, text, servicetext)
{
buildErrandBox(0);
alert($("#errandID").val());
$('#errandArea').val(area);
changeErrandBoxes();
$("#errandGroup").val(group);
changeErrandBoxes();
$("#errandType").val(type);
$("#newTextForErrandTextArea").val(servicetext);
saveTextForErrand();
$("#newTextForErrandTextArea").val(text);
saveTextForErrand();
alert($("#errandID").val());
saveErrand();
}
The errandID becomes undefined. Any ideas?
Update!
When i had the alert in the beginning of the function it works. It seems as the function for building the box is not finished before it try to use the errandID. With two alerts the second gets the errandID.
Is there any way to make it finish execution one function like buildErrandBox(0) before it continues?
If you want the AJAX function to complete before proceeding, set the async option to false:
$.ajax({
url: 'db/buildErrandBox.inc.php',
type:'POST',
dataType: 'json',
async: false, // <-- add this line
...
This will block further execution of the next statement until the result has been returned (or timeout).
Documentation
This is because ajax is asynchronous.. when alert is called. the ajax function is not yet executed..... one way you can fix it is by rearranging your functions and calling others, after the ajax success function of buildErrandBox(0).. this way we can make sure the other function is called only after buildErrandBox() is executed
function buildErrandBox(number)
{
$.ajax({
url: 'db/buildErrandBox.inc.php',
type:'POST',
dataType: 'json',
data: { customerNumber: $("#customerNumber").val(), errandNumber: number },
success: function(build){
//your stuff..
alert($("#errandID").val());
$('#errandArea').val(area);
changeErrandBoxes();
...
saveTextForErrand();
.........
// function you want to execute here
},
error: function (xhr, ajaxOptions, thrownError) {
//your stuff
}
});
}
You should have a look into using jQuery Deferred's when doing async requests like this.
http://api.jquery.com/jQuery.Deferred/
This will ensure that the requests are complete and returned before calling the next function.
Other deferred resources:
http://addyosmani.com/blog/digging-into-deferreds-1/
http://net.tutsplus.com/tutorials/javascript-ajax/wrangle-async-tasks-with-jquery-promises/
You have to make sure that all your AJAX calls have finished and then you should try to further process the server respones.
Related
Hi everyone
After one week searching what could be the problem I have not discovered what could fix it.
I already have done some jquery ajax calls before and I am currently trying to realize a Wordpress pluging.
There I am trying to pass an array in Javascript using Ajax Jquery to a Php page using POST request. Ajax request is correctly achieved ( success and done events are triggered ) but when I am accessing the page $_POST is empty.
I even tried in the code below to simply put simple string data but I can't access it in php page.
This is my Jquery code :
$('#Enregistrer').click(function(){
saveArray= new Array();
var i=0;
$('.q1').each(function(){
if ($(this).hasClass('tablesorter-filter-row')==true){
// doing nothing
}
else{
saveArray[i]=new Array();
for (var j=0; j<6; j++){
if ($(this).children().eq(j).hasClass('m1') || $(this).children().eq(j).hasClass('m2')){
var value = $(this).children().eq(j).children('select').val();
}
else{
var value = $(this).children().eq(j).html();
}
saveArray[i][j]= value;
}
i++;
}
});
console.log(saveArray);
var data = 'test';
$.ajax({
url:'../api/send_form.php',
method:'POST',
data: { 'data': data },
success: function(resp){
console.log('ok');
window.location='../api/send_form.php';
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
If you need more details don't hesitate, this is my first post on stackoverflow.I try to be as precise as possible.
Thanks
maybe your attempt is missing the type: 'POST', also added a few more elements
$.ajax({
dataType: 'html',
type: 'POST',
url:'../api/send_form.php',
method:'POST',
data: { data: data },
processData: false,
contentType: false,
success: function(resp){
console.log('ok');
window.location='../api/send_form.php';
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
I am new to ajax and javascript.
I have the following web method in a page called people.aspx in the root of my web porject:
[System.Web.Services.WebMethod]
public static string RenderDetails()
{
return "Is it working?";
}
I'm attempting to access the web method via an Ajax call from the people.aspx page. I have the following ajax call on the click event of a div:
$("div.readonly").click(function (e) {
e.stopPropagation();
$.ajax({
type: "POST",
async:false,
url: "people.aspx/RenderDetails",
dataType: "json",
beforeSend: function () {
alert("attempting contact");
},
success: function (data) {
alert("I think it worked.");
},
failure: function (msg) { alert("Sorry!!! "); }
});
alert("Implement data-loading logic");
});
I'm not receiving any errors in the javascript console, however, the ajax call also does not hit the web method. Any help will be appreciated.
Thanks!
Try change the type to GET not POST (this is probably why your webpage isn't getting hit). Also your failure parameter is incorrect, it should be error. Expand it to include all parameters (it will provide more information). In short, change your entire AJAX query to this:
$.ajax({
type: "GET",
async:false,
url: "people.aspx/RenderDetails",
dataType: "json",
beforeSend: function () {
alert("attempting contact");
},
success: function (data) {
alert("I think it worked.");
},
error: function (jqXhr, textStatus, errorThrown)
alert("Sorry!!! "); // Insert breakpoint here
}
});
In your browser, debug the error function. The parameters (particularly jqXHR) contain a LOT of information about what has failed. If you are still having more problems, give us the information from jqXHR (error string, error codes, etc).
Minor question (solution seems simple but i can't seem to find it on google). I would like to use the data-setting inside my error: function. I know this may sound cryptic but allow me to use an example.
I have the following Ajax-Call (Jquery).
$.ajax({
type: "GET",
url: "Search.aspx",
data: {
action: 'GetUsers',
userSearchString: $("#txtUserSearchText").val(),
Docbase: docbase
},
success: function (data) {
.... (Do something when successfull)
},
error: function (xhr, errStatus, thrownError) {
// RIGHT HERE, i want to use action,userSearchString,Docbase that were passed to Search.aspx
// Prefferably i would like to use the data as a whole object and pass it too LogException
$("#FindUsersModal").modal("hide")
LogException(errStatus, thrownError, "SearchUsersByInput", params);
}
})
Would anyone care to point me in the right direction?
Thnx for your time.
why not creating the data as an object on the function level and then access it from error callback? for example:
function foo(){
var jsonData = {
action: 'GetUsers',
userSearchString: $("#txtUserSearchText").val(),
Docbase: docbase
}
$.ajax({
type: "GET",
url: "Search.aspx",
data: jsonData,
success: function (data) {
.... (Do something when successfull)
},
error: function (xhr, errStatus, thrownError) {
// RIGHT HERE, i want to use action,userSearchString,Docbase that were passed to Search.aspx
var something = jsonData.action;
$("#FindUsersModal").modal("hide")
LogException(errStatus, thrownError, "SearchUsersByInput", params);
}
})
}
The idea here is simple, just store your data in a variable outside the scope of the function, and you can use it where ever you want it within the function.
Here is what you need to do
var myData = {
action: 'GetUsers',
userSearchString: $("#txtUserSearchText").val(),
Docbase: docbase
}
$.ajax({
type: "GET",
url: "Search.aspx",
data: myData,
success: function (data) {
.... (Do something when successfull)
},
error: function (xhr, errStatus, thrownError) {
console.log(myData);
//You can perform any action with myData here
}
})
When I put an #Url.Action inside a javascript function, Visual Studio will not recognize that function. There will be not collapse/expand option.
function exeAjax(id, destination) {
$("#contents").show();
destination.html("loading...");
$.ajax({
cache: false,
type: "GET",
url: '#Url.Action("MyAction")',
data: { "id": id },
success: function (data) {
destination.html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('failed');
}
});
}
The line will be recognizable if I change from:
url: '#Url.Action("MyAction")'
To:
url: 'MyAction'
Edit:
There's no error and the code runs exactly as expected.
It's just the function region is not recognized by the IDE.
Firstly you should not add any Razor code in Javascript/ Jquery. Because you will ideally like to have all the Javascript/ Jquery in a .js file, and # will try to invoke a razor code. for your issue you can do
$.ajax({
cache: false,
type: "GET",
url: '../MyAction', // path to your action
data: { "id": id },
success: function (data) {
destination.html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('failed');
}
});
Hope it works, happy coding
il give an example
document.ready(function() {
$("#Show").bind("click", function()
{
var F = Function2();
if (F)
{
// Do Other Stuff.
}
}
});
function Function2()
{
$("#Message").Show();
$.ajax({
type: "POST",
url: [MyURL]
async: false;
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(PostData),
dataType: "json",
success: function (returnVal) {
$("#Message").Hide();
return true;
},
error: function (xhr, ajaxOptions, thrownError) {
return false;
}
});
}
</script>
<div id="Message" style="display:none;">
<!-- Loading Image In here -->
</div>
<a href="#" id="Show" onclick="return:false;">Show then Hide</false>
</code>
Now what I want to happen is for this messagebox to show however the AJAX for some reason wont show it until the AJAX Request is finished by which point it is too late. I have set async to false which hasent helped either.
I think the root of this issue is a syntax error. JavaScript is case sensitive, so the correct syntax would be lowercase show() and hide()
If you're still having an issue after fixing the syntax errors, try using the ajaxStart event to show the message and hide it on success.
//use the ajaxstart event to display the message
$('#message').ajaxStart(function() {
$(this).show("slow");
});
$.ajax({
type: "POST",
url: [MyURL]
async: false;
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(PostData),
dataType: "json",
success: function (returnVal) {
$("#Message").hide("slow"); //hide message on success
return true;
},
error: function (xhr, ajaxOptions, thrownError) {
return false;
}
});
Delaying the show or hide
$("#message").delay(3000).hide("slow");
Here's a jsFiddle: http://jsfiddle.net/rs83R/
Try hiding the Message div in the click event after getting true or false.
Remove the async:false, I do not think that is anyway relevant to fixing this problem. The purpose of AJAX call is to make an asynchronous call.
Also, there is an error its not $("#Message").Show() its $("#Message").show() with all lowercase, same goes for hide().
Try changing these, I hope it should work.