Add AJAX response data to a Div - javascript

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…

Related

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/

jquery .ajax's .done function get done on alert only

This seems a bit strange and i cant get a hold of the situation, apparently i used jquery's .ajax() function to process some script to get some data from the database. The script works fine and data gets returned as accordingly:
$.ajax({
type: "POST",
url: "getevaluationdata.php",
data: { evaluation_ID: value }
})
.done(function( msg ) {
$("#error2").html(msg);
});
After the scripts process, it is suppose to populate the data echoed in the script to the div i mentioned, but this does not happen. However, if i write an alert statement before the div population, the div gets populated. meaning:
$.ajax({
type: "POST",
url: "getevaluationdata.php",
data: { evaluation_ID: value }
})
.done(function( msg ) {
alert(msg);
$("#error2").html(msg);
});
I dont seem to get why this is happening and what I can do to resolve this.
P.S. I have done this before, and this was working correctly before
Is it possible #error2 is not on the page yet?, so the alert gives it time? try putting the ajax call in
$(function(){
$.ajax({
type: "POST",
url: "getevaluationdata.php",
data: { evaluation_ID: value }
}).done(function( msg ){
$("#error2").html(msg);
});
});
Another thing you can try for reference is using the success callback
$.post("getevaluationdata.php",{evaluation_ID:value},function(msg){
$("#error2").html(msg);
});

Error with Jquery Ajax Success Event and Receiving Response Message

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);
}

Cant seem to set global vars correctly

I am trying to store a token into a global var. When the alert is run it says null, but if I put 2 alerts one after the other the 1st shows null but the second shows the token.
Its like the token is not being set because the 1st alert is run before the ajax request has finished.
Does anyone have any ideas on what I am doing wrong?
var csrf_token = null;
$(document).ready(function(){
get_csrf_token();
alert('token 1 '+csrf_token);
alert('token 2 '+csrf_token);
});
function get_csrf_token()
{
$.ajax({
type: "GET",
url: "http://buscore/index.php/includes/csrf_token/",
dataType: "json",
success: function(resp, status) {
if (resp.status != 'success')
{
alert('Error - Update CSRF Token\n\n' + resp.status);
return;
}
csrf_token = resp.csrf_token;
}
});
}
Thanks
UPDATED
Ok thanks for your help everyone but still dont see how this would work. I use get_csrf_token() like jqgrid to send the token with the request like below. So how do I pass the token to and have it working?
beforeRequest: function (){
get_csrf_token()
//alert(csrf_token);
$("#customer_grid").setPostDataItem('<?php echo $csrf_token_name; ?>', csrf_token);
}
The success callback function runs when the HTTP response arrives.
In your test, the response is arriving between the time that the first alert is displayed and the time you click the button to let the script continue.
Do whatever you need to do with the data in the callback, not as the statement after the one where you initiate the Ajax request.
Example as requested by comment:
$(document).ready(function(){
get_csrf_token();
});
function get_csrf_token()
{
$.ajax({
type: "GET",
url: "http://buscore/index.php/includes/csrf_token/",
dataType: "json",
success: function(resp, status) {
if (resp.status != 'success')
{
alert('Error - Update CSRF Token\n\n' + resp.status);
return;
}
alert('token 1 '+csrf_token);
alert('token 2 '+csrf_token);
}
});
}
The A in AJAX stands for 'asynchronous'. While you are busy clicking on the first alert, the AJAX request is going through and the value is filled. You will need to place all code that needs the variable csrf_token into your callback function. Alternatively, you can look into using jQuery 1.5 or above (if you aren't already). It has so-called Deferred Objects
This API allows you to work with return values that may not be immediately present (such as the return result from an asynchronous Ajax request).
You can also set the async value on your post request tofalse, like this:
$.ajax({
type: "GET",
async: false,
url: "http://buscore/index.php/includes/csrf_token/",
dataType: "json",
success: function(resp, status) {
if (resp.status != 'success')
{
alert('Error - Update CSRF Token\n\n' + resp.status);
return;
}
csrf_token = resp.csrf_token;
}
});
This will make the browser wait for the response before proceeding with the rest of your code. I wouldn't necessarily recommend it, but it should work.
The AJAX request is async. That means the script doesn't wait for it to finish. When the first alert fires the token is not set. But until you hit OK it has time to load and the token will be set.
Here's the order of the operations:
call get_csrf_token
make token request
show alert 1
finish request and set csrf_token
client hits OK on the first alert
show alert 2 (the token variable was set at 4.)

Categories

Resources