JavaScript and Scope Issue - javascript

I have an issue with calling ajax request with jquery.
The order that I'm doing this in is:
click the button
do ajax post
when the ajax request is finished I call a function that is out side the scope.
For some reason and supecting that it has to do with the fact that i am in the on click callback that the load function is out of scope. But I don't even see the console.log message either. But I do see the ajax call.
Any ideas? Maybe I'm doing this the wrong way???
Here's the prototype code that resembles what I'm trying to do:
$(document).ready(function(){
$('#button').on('click',function(evt){
var data = {};
ajax('index.html', data).done(function(){
console.log('Fire Please'); // this does not fire after the ajax call!!!
load(); // this does not fire after the ajax call!!!
});
});
function load(){
// do another ajax call and add to the dom
}
function ajax(url, data){
return $.ajax({
url: url,
type: 'post',
dataType: 'json',
data: data
});
}
});
And Here's the Actual Code I'm trying to use
$(document).ready(function(){
// add onclick event to the Add Unit Button
addUnitButt.on('click', function(evt){
var data = {
id: id,
dept_no: dept_no.val(),
dept: dept.val()
};
evt.preventDefault();
dept.val('');
dept_no.val('');
$(this).prop('disabled', true);
ajax('index.html', data).done(function(){
load();
});
});
function load(){
var data = {
id: 575
};
// show loading
showLoading();
// reset the table dom
$("#listTable").find("tr:gt(0)").remove();
// do initial load of the list data
ajax('index.html', data)
.done(function(units){
var data = toJSONObject(units);
for(var x = 0; x < data.length; x++){
if((x & 1) == 0){
addRow(data[x], data.length, 'odd');
}else{
addRow(data[x], data.length, 'even');
}
}
// hide loading
hideLoading();
});
}
// ajax function to call for data
function ajax(url, data){
return $.ajax({
type: 'POST',
data: data,
dataType: 'json',
url: url
});
}
});
Thanks in advance!

Maybe the code of your index.html is not valid JSON

.always() must be called.
Make sure your server response have the right headers like Content-Type. And the response body is valid JSON.

Related

What is the best place to call ajax which is calling an API?

I know there are many question like this but i didn't found a proper solution for me.
I am calling API using ajax so my problem is my web page gets unresponsive so some where I have found that this is just because of the improper ajax handling can you please help to know where do I put my ajax.I need ajax to be called on the load of the page.
I have tried calling ajax without any function like..
show('ajax Call start for player');
$('#loading').show();
$.ajax({
url: '/home/getPlayers',
success: function (data) {
data = JSON.parse(data);
playerData = data.Data;
show('data of player');
// show(playerData);
showPlayers(1);
show('ajax Call complete for player');
flag = 1;
}
});
show('ajax Call start for loadplayeronpitch');
$.ajax({
url: '/home/checkUserTeam',
success: function (data) {
while (true) {
if (flag) {
loadUserTeampitch(data);
break;
}
}
show('ajax Call complete for loadplayeronpitch');
}
});
This is not working which cause the unresponsive page.
then from other questions I have tried calling the ajax in following functions
$(document).load(function(){
});
$(function(){
});
$(document).bind("load", function () {
});
but this all are also not working properly can you help me for this?
Thank you.
The unresponsiveness is caused by your while(true) loop, so never ever do this again :-)
What you want to do is: Run the second ajax call only after the first one finishes. So you should put both ajax calls into separate functions, then call the first function on page load.
In the success part of the first ajax (inside the first function), call the second function. Done.
function firstAjax() {
$.ajax({
url: '/home/getPlayers',
success: function (data) {
data = JSON.parse(data);
playerData = data.Data;
show('data of player');
//show(playerData);
showPlayers(1);
show('ajax Call complete for player');
secondAjax();
}
});
}
function secondAjax() {
$.ajax({
url: '/home/checkUserTeam',
success: function (data) {
loadUserTeampitch(data);
}
});
}
$(function() {
firstAjax();
});
This should work like you want to, but I can't test it right now.
$('#loading').show();
var deferedA = $.ajax({
url: '/home/getPlayers',
success: function (data) {
data = JSON.parse(data);
playerData = data.Data;
show('data of player');
// show(playerData);
showPlayers(1);
show('ajax Call complete for player');
}
});
show('ajax Call start for loadplayeronpitch');
var deferedB = $.ajax({
url: '/home/checkUserTeam'
});
//wait until both request are finished
$.when(deferedA, deferedB)
.done( function (dataA, dataB) {
loadUserTeampitch(dataB);
show('ajax Call complete for loadplayeronpitch');
});
EDIT I would suggest to use Promise instead $.when (the Promise like implementation of jQuery is a bit strange), but the problem with Promise is that it is only available with the newer browser, for older one you need a library like bluebird or when
EDIT : If you want to go simple than you can use below approach..
<script type="text/javascript">
$(function() {
var flag = 0;
var data1;
$('#loading').show();
$.ajax({
beforeSend: function() {
show('ajax Call start for player');
},
url: '/home/getPlayers',
success: function(data) {
flag++;
data = JSON.parse(data);
playerData = data.Data;
show('data of player');
showPlayers(1);
show('ajax Call complete for player');
checkFlag();
}
});
$.ajax({
beforeSend: function() {
show('ajax Call start for loadplayeronpitch');
},
url: '/home/checkUserTeam',
success: function(data) {
flag++;
data1 = data;
show('ajax Call complete for loadplayeronpitch');
checkFlag();
}
});
function checkFlag()
{
if (parseInt(flag) == parseInt(2))
{
loadUserTeampitch(data1);
}
}
});
</script>

Waiting for Ajax called DOM manipulation to finish

Sorry for the title but I had no idea how to call it.
I got some ajax call function that on success adds some HTML elements to the page:
function ajax_submit_append(form_data, url, result, complete) {
$.ajax({
url: url,
type: 'POST',
data: form_data,
success: function(msg) {
var res = $(msg).filter('span.redirect');
if($(res).html() != null){
window.location.replace($(res).html());
return false;
}
$(result).append(msg);
},
complete: complete()
});
};
Function does something on success where the most important is the .append and then this ajax function is called in some button .click function like this:
$(function() {
$("#product_list_add_btn").click(function(e){
ajax_submit_append(
form_data = {
product_name: $('.selectpicker option:selected').val(),
amount: $('#amount').val()},
"<?php echo site_url('admin_panel/new_order/add_product'); ?>",
'#add_product_result',
calculateSum
);
return false;
});
});
What I want to achieve is that calculateSum function (sums table columns) is called after .append is done via ajax.
For now, when I add calculateSum to ajax complete event it is still called before new row is added to the table with .append
Edit: I present You calculateSum, but I believe there is nothing faulty there.
function calculateSum() {
var sum = 0;
// iterate through each td based on class and add the values
$(".countit").each(function() {
var value = $(this).text();
// add only if the value is number
if(!isNaN(value) && value.length != 0) {
sum += parseFloat(value);
}
});
$('#total_price').text(sum);
alert("test");
};
If I had to guess, I would say its something with click event?
How to fix this?
Try using jqXHR's done() method:
function ajax_submit_append(form_data, url, result, complete) {
$.ajax({
url: url,
type: 'POST',
data: form_data,
success: function(msg) {
var res = $(msg).filter('span.redirect');
if($(res).html() != null){
window.location.replace($(res).html());
return false;
}
$(result).append(msg);
}
}).done(complete);
};

How to connect to the Parse Javascript API? (502 error)

I am building a chatroom-type app using the Parse Javascript API. The task is to get some data from Parse, display it, add user input to the messages, and send it right back to parse.
The problem is I am not being able to see the data from parse, and receive a 502 error. I am a bit newer to javascript, so any advice on how to accomplish this, or any mistakes you may see in my code, would be fantastic. I also commented out my code the best I could. Thanks for the help.
Here is my code;
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages')
//fetches data from parse
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success: console.log("Success"),
function message(a) {
my_messages.append('<ul>' + a +'</ul>'); //adds ul 'text' to messages
};
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
function(message){
window.location.reload(1) //refresh every 3 seconds
});
});
});
</script>
you have syntax error in both of your success functions of $.ajax calls. In the first ajax call you have places console.log, which should be inside the success callback. In the second one u haven't even added success: callback.
Try below updated code
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages');
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success:function message(a) {
console.log("Success")
$.each(a,function(i,item){
my_messages.append('<ul>' + item.username +'</ul>'); //adds ul 'text' to messages
});
}
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
success:function(message){
window.location.reload(1) //refresh every 3 seconds
}
});
});
});

Getting variable from success function ajax

I have a variable in the success part of ajax and I want to reuse it in another function (which executed every 3 seconds), I tried to declare it global, but it does not work; Tdata is not known.
I know that $.ajax is an asynchronous function and I saw some posts similar to mine but it did not help me.
Help me please. Thank you.
This is a part of my code:
<script language='Javascript'>
var Tdata;
$.ajax({
method : "GET",
url: "load-data.php",
success : function(data){
Tdata=jQuery.parseJSON(data);
////
}
});
window.setInterval(function() {
$(window).load(function() {
$.each(Tdata, function(variable) {
/////////////
});
});
}, 3000);
</script>
Why not wait until the AJAX request has successfully returned data before starting your interval? Since any executions of the interval's function aren't going to do anything (due to no data) before that point waiting isn't going to change the way the page would function in any way.
$.ajax({
method: "GET",
url: "load-data.php",
dataType: "json"
success: function(data) {
var Tdata = data;
// do some more stuff with the response of the AJAX request
var interval = setInterval(function() {
$.each(Tdata, function(variable) {
// do something with variable
});
}, 3000);
}
});
Note that I've removed the binding of the load event to the window every time the interval runs because doing so really doesn't seem to make any sense. I've also added a dataType property with a value of json to the options object passed to $.ajax() so you don't have to parse the response as JSON yourself.
try this,
<script language='Javascript'>
var Tdata;
$.ajax({
method : "GET",
url: "load-data.php",
success : function(data){
Tdata=jQuery.parseJSON(data);
////
}
});
$(window).load(function() {
window.setInterval(function() {
$.each(Tdata, function(variable) {
/////////////
});
}, 3000);
});
</script>
Function that uses the variable from AJAX call should be called from inside AJAX success, like this:
$.ajax({
method : "GET",
url: "load-data.php",
success : function(data){
Tdata=jQuery.parseJSON(data);
myFunction();
}
});
function myFunction(){
var interval = setInterval(function() {
$.each(Tdata, function(variable) {
/////////////
});
}, 3000);
}
is callback tdataAjax function ajax success method run; #param parseJSON
var tdataAjax = function(callback) {
$.ajax({
method : "GET",
url: "load-data.php",
success : function(data){
var Tdata=jQuery.parseJSON(data);
setInterval(function() {
callback(Tdata);
}, 3000);
}
});
};
is Callback function #param data in tdataAjax function
tdataAjax(function(data) {
$.each(data, function(variable) {
// code
});
});
tdataAjax ++ :)
tdataAjax(function(data) {
$.each(data, function(variable) {
// cla bla
});
});

Execute php url with JS

Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request

Categories