Ajax function only succeeds with "alert" - javascript

EDIT: My question is not a duplicate of No response from MediaWiki API using jQuery. Because even though it's a cross-domain request, I'm properly triggering JSONP behavior because jquery is automatically sending a callback parameter under the hood. (As you can see from the link I posted jQuery3100048749602337837095_1485851882249&_=1485851882253
EDIT2: Solved by #AnandMArora. Solution:
<input type="submit" onclick="getUserInput(event)" style="display:none"/>
and function
getUserInput(evt) { evt.preventDefault();
But since it's a comment I can't mark it as the answer. If there's an explanation why this method works (what is the default behavior that is prevented etc.) I will select it as the answer.
I assume that the "alert" method is buying time for the AJAX function since it's asynchronous. But I have no idea WHY do I need to buy time here. It should only be executed when getUserInput() calls getWiki() with the Input parameter.
In fact, I looked at the network monitor and even if we remove alert("") the proper URL is called (assuming "batman" was submitted).
Request URL: https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&generator=search&exsentences=1&exlimit=max&exintro=1&explaintext=1&exsectionformat=wiki&gsrnamespace=0&gsrsearch=batman&callback=jQuery3100048749602337837095_1485851882249&_=1485851882253
If I open this link manually, it works fine.
But there's no status code returned and console logs "Error!"
function getUserInput(){
var Input = document.getElementById("searchBox").value;
getWiki(Input);
alert(""); //If we remove this line the request fails
}
function generatePage(rawData) {
console.log(rawData);
var mainData = rawData.query.pages;
$.each(mainData, function(value){
console.log((mainData[value].title + " " + mainData[value].extract));
});
}
function getWiki(Input){
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&generator=search&exsentences=1&exlimit=max&exintro=1&explaintext=1&exsectionformat=wiki&gsrnamespace=0&gsrsearch=" + Input,
dataType: "JSONP",
type: "GET",
success: function (rawData) {
generatePage(rawData);
},
error: function() {
console.log("Error!")
}
});
}
$(document).ready(function(){
})
The html I'm using to submit is:
<form class="searchForm">
<input type="text" name="searchRequest" id="searchBox" >
<input type="submit" onclick="getUserInput()" style="display:none"/>
</input>
</form>
My questions would be:
1) Why is this happening?
2) How can this be fixed without turning async off or using setTimeout() on the ajax function?

Wrap that console.log call inside a function:
function getWiki(Input){
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&generator=search&exsentences=1&exlimit=max&exintro=1&explaintext=1&exsectionformat=wiki&gsrnamespace=0&gsrsearch=" + Input,
datatype: "JSONP",
type: "GET",
success:
function (rawData){
generatePage(rawData);
},
error:
function(){
console.log("Error!")
}
});
}
Explanation:
The ajax call expects functions definitions to be passed to its event handlers ('success'/'error' in this case).
You do this for the success handler. For your error handler you are not pushing a function definition but a function that you are actually invoking (the console.log method).
Wrapping it in a function declaration (like what you did for the success event callback) allows you to define what happens on the callback when it is invoked rather than invoked it in-line.

You are using ajax, and the input control type of "submit" has a default action of postback for the form in which it is placed. So jQuery and most javascript code use the evt.preventDefault(); // evt is the object of event passed as a parameter for the click event function this prevents the default action i.e. submit the form.
Please make the changes as :
<input type="submit" onclick="getUserInput(event)" style="display:none"/>
and
function getUserInput(evt) { evt.preventDefault(); ...
this will most probably be the solution.

1)You have to specify a callback function, don't put code directly (otherwise it will be executed) but put it in a function
error: function(){console.log("Error!");}
2)In order to wait for the response, you have to specify that your request it synchronous
Set async option to false
If you need an asynchronous solution please see the following snippets (using done method instead of success property):
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</head>
<body>
<form class="searchForm">
<input type="text" name="searchRequest" id="searchBox" >
<input type="submit" onclick="javascript:getUserInput()" />
</input>
</form>
</body>
<script>
function getUserInput(){
var Input = document.getElementById("searchBox").value;
getWiki(Input);
//alert(""); //If we remove this line the request fails
}
function generatePage(rawData) {
console.log(rawData);
var mainData = rawData.query.pages;
$.each(mainData, function(value){
console.log((mainData[value].title + " " + mainData[value].extract));
})
}
function getWiki(Input){
$.ajax({
url: "https://en.wikipedia.org/w/api.php?action=query&format=json&prop=extracts&generator=search&exsentences=1&exlimit=max&exintro=1&explaintext=1&exsectionformat=wiki&gsrnamespace=0&gsrsearch=" + Input,
dataType: "JSONP",
type: "GET",
async: true,
error: function(){console.log("Error!");}
}).done(
function (rawData) {
generatePage(rawData);
}
);
}
$(document).ready(function(){
})
</script>
</html>
I hope it helps you. Bye.

Related

Calling same controller's method using ajax GET and POST type

Hi I am a newbie to Grails and Groovy. Please help me to solve the below issue related to calling controller's method using ajax call.
The scenario behind the code is to recover the password using the username whenever the user is unable to remember the password. I have explained the code flow in detail below.
Application begins with the below auth.gsp page:
<form action='${postUrl}' method='POST' id='loginForm' autocomplete='off'>
<input type='text' name='j_username' id='username'/>
<input type='password' name='j_password' id='password'/>
<input type='submit' id="submit" value='${message(code: "default.button.login")}'/>
<g:message code="etranscripts.forgotPassword"/>
</form>
When I click on the Forgot password link of the anchor tag, it will call the below ajax method:
<script>
$(document).ready(function () {
$('#recovery-link').click(function () {
var url = $(this).attr('recovery-url')
$.ajax({
url: url,
dataType: "html"
}).done(function (html) {
$('#loginForm').replaceWith(html)
$('#sign-in-instruct').text('<g:message code="js.resetEnterName"/>')
}).fail(function (jqXHR, textStatus) {
console.log("Request for url failed: " + url)
})
event.preventDefault()
return false
});
});
The controller method for the above call is as below.
def recoverPassword = {
println "RecoverPassword method of ctrl....."
if (!request.post) {
// show the form
render(template: "recoverPassword" )
return
}
//some other stuff based on the input conditions.
The successful output template for the above ajax call is:
<div id="recover-password" >
<ul>
<li>
<span><g:textField name="username" id="username" value="" /></span>
<input type='submit' id="submit-username-link" recovery-url="<g:createLink controller='recoverPassword' action="recoverPassword"/>" value='Submit'/>
</li>
</ul>
Till here my code works perfect. But the issue begins from here.
i.e When I enter some value in the username field of the template and click on submit, it should call the below ajax method.
$(document).on('click', '#submit-username-link', function (event) {
var url = $(this).attr('recovery-url')
var username = $('input#username').val();
$.ajax({
url: url,
type: "POST",
data: {username:username},
dataType: "json"
}).done(function (responseJson) {
$('#sign-in-instruct').text(responseJson.message)
$('div.copyright').css('margin','74px 0px 0px 140px')
$('#home-link').show()
if ( responseJson.status == 'success') {
$('#recover-password').remove()
}
}).fail(function (jqXHR, textStatus) {
$('#recover-password').remove()
$('#sign-in-instruct').text(textStatus)
console.log("Failed to send the email " + textStatus)
})
event.preventDefault()
return false
});
The thing is, url refers to the same method of the controller but the only change is POST type is used and that will be taken into consideration inside the method using if conditions.(i.e some other stuff of the controller)
These GET and POST type of method calls are configured as shown below in the URLMappings.groovy file.
"/recoverPassword/recoverPassword"(controller: 'recoverPassword') {
action = [GET: "recoverPassword", POST: "recoverPassword"]
}
The whole summary of this question is, for the same method of controller, GET request is working but POST type of ajax call is not able to reach the controller's method.
Am I doing anything wrong over here? Please help me to solve this issue. Thanks in advance :-)
Overcomplicated. Why don't you use separate function in controller for GET (rendering the form) and separate function for POST (for handling the recovering the password)?
Check out also https://en.wikipedia.org/wiki/KISS_principle
Change input Type submit to button
<input type='button' id="submit-username-link" recovery-url="<g:createLink controller='recoverPassword' action="recoverPassword"/>" value='Submit'/>

I can't set value or get value from select elements created via Ajax

I created "omarkasec" as a function and I get car brands from database via ajax and I added at the select element this car brands as options via ajax --> success.
But I can't set a value this select element.
I tried this codes for set value:
$('select[name=marka]').val('Lada');
$('select[name=marka] option[value=Lada]').prop('selected', true);
$('select[name=marka] option[value=Lada]').attr('selected', 'selected');
this codes don't work. But if I add alert(""); in "omarkasec" function the codes do work and if I remove alert(""); the codes don't work.
<div id="marka" class="gizle" >
Marka: <br>
<select name="marka" onchange="omodelsec()" size="10" ></select>
</div>
<script language='javascript' type='text/javascript'>
function omarkasec() {
$.ajax({
type: "POST",
url: "aracsor.php",
dataType: "json",
data: {
otomobilmodelyili : $("select[name=modelyili]").val(), //This work, because i created php.
},
success: function(donen){
$("#marka").removeClass("gizle");
$("#model").addClass("gizle");
$("#yakit").addClass("gizle");
$("#sanziman").addClass("gizle");
$("#cekis").addClass("gizle");
$("#kasatipi").addClass("gizle");
$("select[name=marka]").empty();
$.each(donen, function (index, otomarka) {
$("select[name=marka]").append($("<option>", {
text : otomarka,
value : otomarka,
}));
});
},
});
//if I add here alert(""); The following code works.
}
</script>
<script language='javascript' type='text/javascript'>
omarkasec();
$('select[name=marka]').val('Lada');
alert($('select[name=marka]').val()); //if I add alert(""); this code work but if I remove alert(""); this code get null value.
</script>
Ajax calls are asynchronous. Your code executes the $.ajax() call passing it a call back function, but that call back function is not executed at that very moment.
The execution immediately proceeds with the statement after $.ajax() but at that moment the content has not been loaded.
However, if you perform an alert(), the call back might eventually be triggered while the alert dialog is open, and thus content is loaded by your call back function. If you then close the popup, any code following it will find the content is there.
One way to solve this, is to use the return value of the $.ajax call, which is a promise, and chain a then call to it:
function omarkasec(oncomplete) {
return $.ajax({
// ^^^^^^
type: "POST",
url: "aracsor.php",
dataType: "json",
data: {
otomobilmodelyili : $("select[name=modelyili]").val(),
},
success: function(donen){
$("#marka").removeClass("gizle");
$("#model").addClass("gizle");
$("#yakit").addClass("gizle");
$("#sanziman").addClass("gizle");
$("#cekis").addClass("gizle");
$("#kasatipi").addClass("gizle");
$("select[name=marka]").empty();
$.each(donen, function (index, otomarka) {
$("select[name=marka]").append($("<option>", {
text : otomarka,
value : otomarka,
}));
});
},
});
}
// provide (anonymous) callback function to the `then` method:
omarkasec.then(function () {
// this code will only be executed when content is loaded:
$('select[name=marka]').val('Lada');
alert($('select[name=marka]').val());
});
You have a race condition. You are calling omarkasec() and not waiting for it to finish to execute the select.val() action. When you add the alert it "works" because it gives the code some extra time to complete the ajax call an fill the values. When you alert it, the values are already filled.
All your code that depends on the result from the ajax call must be inside the success callback.

HTML onchange not getting fired from Ajax insert

I am new to Jquery Ajax.
I have a jquery ajax function, which receives a value from a server.
function servertransfer_reg(datapack1,datapack2,datapack3,datapack4) {
alert('Start of Ajax Call');
//Ajax , Jquery Call to Server for sending free time data
$.ajax({
type: "POST",
dataType: 'json',
url: "xyz.php",
data: {M_N : datapack1,
Em : datapack2,
TandC: datapack3,
News: datapack4
},
success: function(data) {
alert(data.appid);
$("#server_answer_reg").html('<p>Your App ID Successfully created<p/>' + data.appid);
//document.getElementById("partyID").innerHTML = data.appid;
$("#partyID").html(data.appid);
}
});
}
Here, I am getting data.appid from server.
I want to insert it into an html element #partyID, and after insert I am expecting onchange event to get fired which will do some work for me.
Below is the html.
<input onchange="saveIDs()" type="text" id="partyID" class="none_visible" value=""></input>
Here, my saveIDs() function is not getting called.
I am receiving the intended data from my Ajax call.
Please let me know if you need more information.
The onchange will fire when you leave the focus from it (if you performed any changes). After the successful execution why don't you call the saveIDs() function in the next line? What I mean is
success: function(data) {
alert(data.appid);
$("#server_answer_reg").html('<p>Your App ID Successfully created<p/>' + data.appid);
//document.getElementById("partyID").innerHTML = data.appid;
$("#partyID").html(data.appid);
saveIDs();
}
You must trigger the onchange event.
See:
http://api.jquery.com/trigger/

When and when doesn't success: value executes in jQuery Ajax method? (Header location not changed)

I'm submitting a form using jQuery Ajax.
The data is submitted successfully but there's a little problem. When I add the commented statements in this code, the success: function(){} doesn't run (location is not changed).
Q. 1 When I remove those statements, it runs. I don't understand this logic. When does it actually executes and how does checking for xy affects this?
Here's my Ajax code:
$(document).ready(function(){
$("#button").click(function(){
**//FOLLOWING TWO LINES MAKES SUCCESS NOT RUN**
//var **xy**= $("#digits").val();
//if(xy!=""){
$.ajax({
url: "submitform.php",
type: "POST",
data: $('#signupform').serialize(),
success: function(result){
$(location).attr('href', 'login2.php');
},
error: function(){
alert(error);
}
});
// }
});
});
Here's concerned input tag:
<form id="signupform" name="form1" method="post" enctype="multipart/form-data">
<input id="digits" type="text" name="phone" maxlength="10" placeholder="Enter your phone no." required />
......
Q.2 When I write event.preventDefault(); to stop the default action of submit button, the required atrributes of input fields don't work. Why is it so? Can it be solved?
To Question 2:
If you call preventDefault for the event of the click on the submit button, then the default behaviour (initiating the submit) is prevented, so the input fields are not checked.
You have to listen on the submit event of the form instead and prevent the default behaviour of this, because the submit event is send after the input elements are checked and before the form is submitted.
$(document).ready(function() {
$("#signupform").on('submit', function(e) {
e.preventDefault();
//FOLLOWING TWO LINES MAKES SUCCESS NOT RUN**
//var **xy**= $("#digits").val();
//if(xy!=""){
$.ajax({
url: "submitform.php",
type: "POST",
data: $('#signupform').serialize(),
success: function(result) {
$(location).attr('href', 'login2.php');
},
error: function() {
alert(error);
}
});
// }
});
});
When you use jquery ajax there is two types of result:
400 - OK status which be capture by the success function
402 or 500 are internal errors and those will be capture by the error function.
Now, in your error function youre trying to print an error variable that does not exist.
Also, when you use preventDefault you have pass variable that handles de event too cancel.

Run JS after div contents loaded from AJAX

There are a ton of proposed answers to my question, but even with all the answers I have found, I can not seem to get any to work. I can make the JS work by adding a delay in execution of the code, but I can't rely on a delay to execute the JS after div has finished loading it's HTML.
I'm creating a page where users can search for an item, and the results are displayed in a div using AJAX. I need some JS to run after the div's html has finished loading. Some of the results data will be hidden until a user clicks on it. The JS code to accomplish this is what I am trying to run once the div finishes loading.
I have tried the following extensively with no luck anywhere:
.load
.ajaxComplete
.complete
.success
.done
Document.ready
I'm sure there are a few others as well, but my brain is just too beat up from dealing with this to remember everything I've tried so far.
My HTML:
<form name ="CardName" method="post" action="">
<div "class="w2ui-field">
<div> <input type="list" Name="CardName" id="CardName" style="width: 80%;"></div>
</div>
<div class="w2ui-buttons">
<input type="submit" name="search" style="clear: both; width:80%" value="Search" class="btn">
</div>
</form>
<div class="Results" id="Results" name="Results"></div>
My JS:
$(function() {
$("#CardSearch").bind('submit',function() {
var value = $('#CardName').val();
$.ajax({
method: "POST",
url: "synergies.php",
data: {value}
})
.success(function(data) {
$("#Results").html(data);
})
.complete(function() {
alert("div updated!"); //Trying to run JS code AFTER div finishes loading
});
return false;
});
});
If there is anything else that could help with this request just let me know!
Thanks in advance!
Note that success and failure are options that you should provide to the $.ajax call, not the returned promise. Also, bind is deprecated in favour of on since jQuery 1.7. Finally, you need to give the value that you're posting to your PHP page a key so that it can be retrieved via $_POST. Try this:
$("#CardSearch").on('submit', function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "synergies.php",
data: {
CardName: $('#CardName').val()
},
success: function(data) {
$("#Results").html(data);
},
complete: function() {
alert("div updated!"); //Trying to run JS code AFTER div finishes loading
}
})
});
You can then retrieve the value sent in your synergies.php file using $_POST['CardName'].
If you prefer to use the method provided by the returned promise, you can do that like the below, although the result is identical.
$("#CardSearch").on('submit', function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "synergies.php",
data: {
CardName: $('#CardName').val()
}
}).done(function(data) {
$("#Results").html(data);
}).always(function() {
alert("div updated!");
})
});
you can try Synchronous Ajax request, demo code is given below:
$(function() {
$("#CardSearch").bind('submit',function() {
e.preventDefault();
sendData = $('#CardName').val();
reqUrl = "synergies.php";
// this will wait until server request complete
var ajaxOpt = AjaxSyncRequest(reqUrl, sendData);
// after complete server request
ajaxOpt.done(function(data) {
$("#Results").html(data);
});
});
});
function AjaxSyncRequest(reqUrl, sendData) {
var ajaxData = $.ajax({
method: "POST",
url: reqUrl,
data: {
data: sendData
}
});
return ajaxData;
}

Categories

Resources