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/
Related
Having trouble with following code, it gets the data that I want but it won't append to the div #playercontent instead it appears in a console when I run it.
WORKING WITH PHP, Slim, HTML, JSON. To clear it up.
$(document).ready(function(){
$.ajax({
type: 'GET',
dataType: "json",
url: "db.php/players",
success: showResponse,
error: showError
});
});
console.debug("error");
function showResponse(responseData){
$("#get1").click(function getPlayers(responseData) {
console.log('Image is clicked');
console.log(responseData);
$.each(responseData.player, function(index, player){
console.log(' is ');
$("#playercontent").append(" </br>Player Position:" +player.PlayerPosition+"</br> Full Name:" +player.PlayerName+ " "+player.PlayerLastName+" </br>Team Name:" +player.TeamName);
// $("#playercontent").append("</li>");
console.log('Data should output');
});
});
console.log(responseData);
}
console.debug("hello");
function showError(){
alert("Sorry, but something went wrong. Fix it!!!!")
}
The code to append the data to the #playercontent div is within an onclick event handler that's within your AJAX request's success handler. i.e. it's not going to run because the click will never happen as you're within an .ajax success callback. Try moving the code that iterates over the responseData outside of the onclick handler so that it is directly in the showResponse function.
Also console.debug("error"); and console.debug("hello"); messages will display every page request and before the .ajax call happens…
We have a search functionality in our application, when user types in something, the result will be generated based on the filter and displayed on page.
Here's the dynamic result after each keyup:
htmlResult = `
<li>
<div>
<img src='${user.avatar}' width='80' alt='${user.fullName}' />
</div>
<a tabindex='0'
class ='btn2'
data-html='true'
data-toggle='popover'
data-content="<div class='list-group'>add
</li>
`;
Here are the event handlers:
$("[data-toggle=popover]").popover();
$(document).on('click', '.btn2', function(event) {
event.preventDefault();
$(this).popover({ html: true });
});
$(document).on('click', '.item', function (event) {
event.preventDefault();
const value1 = $(this).attr('data-val1-value');
const params = {
value1: value1
};
$.ajax({
type: "POST",
url: endPoint,
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(params),
success: (result) => {
// refresh
}
});
});
There are two problems with this code:
popover will be displayed after 3 times clicking on .item
jQuery ajax won't succeed, it shows 400 Bad Request error on console.
PS: this code works fine with not-generated markup.
any idea?
For popover you must reinitiate every your dynamic content was append to HTML.
For Ajax 400 this is because the URL not found the route path, please check again your backend requirement for this request.
a) to make sure your url is correct,
1) update your serverside funtion not to accept any parameter just for testing
2) call ajax with data: NULL
3) debug and see if it reaches to server side function.
b) if not reached to server side, check if it is a POST or GET in server side function.
c) if you are sure that server side function is correctly called, data without stringfy.
that might help.
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.
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.
I am calling jQuery Ajax function, everything works fine.. except, it is not receving any response and appending it in.
When form is submitted.. beforeSend event is called and loading image successfully runs, and also there is an alert box with message 'Deleted', but the request and response from page is not appended.... in network tab of chrome, i can see message of selected post deleted... but its not appending in page.
$(document).ready(function() {
$("#post").submit(function() {
var post = $('#post').val();
var token = $('#token').val();
var str = 'token='+ token + '&post='+ post;
$.ajax({
type: "POST",
cache: false,
url: "http://localhost/delete.php",
data: str,
beforeSend: function(){
$("#post").html('<img src="http://localhost/loader.gif" align="absmiddle"> Deleting...');
},
success: function(msg) {
alert('Deleted');
$("#post").ajaxComplete(function(event, request, settings) {
$("#post").html(msg);
});
}
});
return false;
});
});
You're attaching a new event listener to #post after the AJAX query succeeds. Basically what you're saying is, "after this query succeeds, wait for another query to succeed and then change the HTML." Since the query has already succeeded, you need to remove ajaxComplete and simply use:
success: function() {
alert('Deleted');
$("#post").html(msg);
}