show() overwritten multiple ajax calls - javascript

I have one html element (elem1) and 2 JS functions (func1, func2) that hides and shows elem1 respectively. These JS functions make individual ajax calls and func2 is calling func1 internally.
Problem: I need to call func2, which internally calls func1. Calling func1 hides elem1. After calling func1, I want to show elem1. But this show is not working.
JSFiddle: https://jsfiddle.net/46o93od2/21/
HTML:
<div id="elem">
Save ME
</div>
<br/>
<button onclick="func1()" id="func1">Try Func1</button>
<button onclick="func2()" id="func2">Try Func2</button>
JS:
function func1() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {}, // send in your data
success: function (data) {
//var aData = JSON.parse(data); // there is no data to parse
$('#elem').hide();
},
error: function (xhr, errmsg, err) {
alert('error');
}
});
}
function func2() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {}, // send in your data
success: function (data) {
//var aData = JSON.parse(data); // there is no data to parse
func1();
$('#elem').show();
},
error: function (xhr, errmsg, err) {
alert('error');
}
});
}

Make func1 take a callback function that tells it what to do after it gets the response. func2 can pass a function that shows the element.
function func1(callback) {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {
json: ''
}, // send in your data
success: function(data) {
if (callback) {
callback();
} else {
$('#elem').hide();
}
},
error: function(xhr, errmsg, err) {
alert('error');
}
});
}
function func2() {
$.ajax({
url: '/echo/json/', //use the correct processing url here
type: "POST",
data: {
json: ''
}, // send in your data
success: function(data) {
func1(function() {
$('#elem').show();
});
},
error: function(xhr, errmsg, err) {
alert('error');
}
});
}
DEMO

Related

Loader works only on the first ajax call

I want the loader to stay until the complete execution is complete and statement $("#xyzDiv").html(data) has been executed. Currently the loader gets hidden after the first ajax call. Even if i add "beforeSend: function () { $("#loader").show(); }" to GetDataList(), the loader is not staying.
$.ajax
({
type: "POST",
url: ajaxUrl,
data: dataObj,
beforeSend: function () { $("#loader").show(); },
success: function (data)
{
if (data.result)
{
GetDataList();
toastr.success(data.strMsg);
}
else
{
toastr.error(data.strMsg);
}
},
error: function (jqXHR, textStatus)
{
var msg = HandleAjaxErrorMessage(jqXHR, textStatus);
console.log(msg);
toastr.error('An error occurred. Please try again');
},
complete: function () { $("#loader").hide(); }
});
function GetDataList()
{
$.ajax
({
type: "Get",
url: ajaxUrl,
data: dataObj,
success: function (data)
{
$("#xyzDiv").html(data);
},
error: function (jqXHR, textStatus)
{
var msg = HandleAjaxErrorMessage(jqXHR, textStatus);
console.log(msg);
toastr.error('An error occurred. Please try again');
}
});
}

How to send WebSocket data from View to Controller and reworked data send to View with Ajax

I'm trying send websocket data from view to controller and again reworked data send to view in for example table with button or something like this.
Now sending data to controller works:
View:
<script type="text/javascript">
var webSocket;
var webSocketValue;
function webSocketResults() {
webSocket = new WebSocket("ws://......");
webSocket.onmessage = function (event) {
webSocketValue = event.data;
$("#webSocketValue").text(webSocketValue);
$.ajax({
url: "#Url.Action("getWebSocketResults", "Home")",
type: "POST",
contentType: "application/json",
data: webSocketValue
});
};
showCurrenciesData(webSocketValue);
}
function showCurrenciesData() {
$.ajax({
cache: false,
type: "GET",
url: "#Url.Action("getWebSocketResults", "Home")",
dataType: 'json',
success: function (result) {
alert("Sukcess!!" + result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve data.');
}
});
}
window.onload = webSocketResults;
Controller
public ActionResult getWebSocketResults(Currencies currencies)
{ //do something with data "currencies" and dynamicly send this to view
var webSocketItems = currencies.items.ToList();
return Json(webSocketItems, JsonRequestBehavior.AllowGet);
}
In Controller i have data (Object) from View.
How to send this data dynamically. New data from WebSocket arrives every minute.
Sending data to view does'nt work.
you called two times. first times did not handle result. second times no have paremeter.
<script type="text/javascript">
var webSocket;
var webSocketValue;
function webSocketResults() {
webSocket = new WebSocket("ws://......");
webSocket.onmessage = function (event) {
showCurrenciesData(event.data);
};
}
function showCurrenciesData(data) {
$.ajax({
cache: false,
type: "GET",
url: "#Url.Action("getWebSocketResults", "Home")",
dataType: 'json',
data: data,
success: function (result) {
alert("Sukcess!!" + result);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Failed to retrieve data.');
}
});
}
window.onload = webSocketResults;

Double ajax request response

I'm using ajax successives requests and I need do a callback when all the successives requests are done
function doAjaxRequest(data, id) {
// Get payment Token
return $.ajax({
type: "POST",
url: 'exemple1.php',
data: data
success: function(msg){
$.ajax({
type: "POST",
url: 'exemple2.php',
data: msg,
success: function(msgr) {
document.getElementById(id).value=msgr;
},
error:function (xhr, status, error) {
//Do something
}
});
},
error:function (xhr, status, error) {
//Do something
}
});
}
$.when(
doAjaxRequest(data, "input-1"),
doAjaxRequest(otherData, "input-2")
).done(function(a1, a2){
//Need do something when both second ajax requests (example2.php) are finished
}
With this code, the done function is call before my calls to "exemple2.php" are succeeded.
How can I wait for that?
Thanks for answering!
function doAjaxRequest(data, id) {
// Get payment Token
return new Promise(function(resolve,reject){
$.ajax({
type: "POST",
url: 'exemple1.php',
data: data
success: function(msg){
$.ajax({
type: "POST",
url: 'exemple2.php',
data: msg,
success: function(msgr) {
document.getElementById(id).value=msgr;
resolve();
},
error:function (xhr, status, error) {
//Do something
reject();
}
});
},
error:function (xhr, status, error) {
//Do something
reject();
}
});
});
}
Promise.all([
doAjaxRequest(data, "input-1"),
doAjaxRequest(otherData, "input-2")])
.then(function(values){
//Need do something when both second ajax requests (example2.php) are finished
}
Your sub ajax request is independant of the first ajax result, then the call to example2 is completely separated from the $.when() promise.abort
Just try to use the fact that jquery $.ajax return promise like object
Here my code from plnkr
// Code goes here
function doAjaxRequest(data, id) {
// Get payment Token
return $.ajax({
type: "GET",
url: 'example1.json',
data: data
}).then(function(msg, status, jqXhr) {
return $.ajax({
type: "GET",
url: 'example2.json',
data: msg
});
}).done(function(msgr) {
console.log(msgr);
return msgr;
});
}
var data = {foo:'bar'};
var otherData = {foo2:'bar2'};
$.when(
doAjaxRequest(data, "input-1"),
doAjaxRequest(otherData, "input-2")
).done(function(a1, a2) {
console.log(a1, a2);
//Need do something when both second ajax requests (example2.php) are finished
});
Attention, I replace POST by GET and use exampleX.json files for my tests on plnkr
You can test it here : https://plnkr.co/edit/5TcPMUhWJqFkxbZNCboz
Return a custom deferred object, e.g:
function doAjaxRequest(data, id) {
var d = new $.Deferred();
// Get payment Token
$.ajax({
type: "POST",
url: 'exemple1.php',
data: data
success: function(msg){
$.ajax({
type: "POST",
url: 'exemple2.php',
data: msg,
success: function(msgr) {
document.getElementById(id).value=msgr;
d.resolveWith(null, [msgr]); // or maybe d.resolveWith(null, [msg]);
},
error:function (xhr, status, error) {
//Do something
d.reject();
}
});
},
error:function (xhr, status, error) {
//Do something
d.reject();
}
});
return d;
}
Now, i'm not sure what is your expected datas passed to $.when().done() callback.

Calling PHP functions through AJAX using jQuery callback parameters

I have problems with AJAX results using jQuery.
I have defined these functions:
<script>
function hello(callback, funct, val) {
var ret = 0;
console.log(val);
$.ajax({
type: 'GET',
dataType: 'json',
url: 'SGWEB/header.php',
data: {
'funct': funct,
'val': val
}
}).done(function (data) {
// you may safely use results here
console.log(data);
callback(data);
});
};
function change() {
hello(function (ret) {
console.log(ret);
$("#b1").text(ret);
}, "hello", 1);
};
change();
</script>
SGWEB/header.php:
extract($_GET);
$validFunctions = array("readPin","hello");
if(in_array($funct, $validFunctions)) $funct();
// functions
// ....
function hello($val) {
if ($val == 1) {
echo "1";
} else
echo "2";
}
The problem I have is that the AJAX passes only the first parameter in data {'funct': funct} and it's working, but val is completely ignored (it always echoes "2").
How can I solve this? Thanks
You are forgetting to pass the $val parameter to your function in PHP
Change this:
if (in_array($funct, $validFunctions)) $funct();
to this:
if (in_array($funct, $validFunctions)) $funct($val);
Another problem is that your AJAX is expecting JSON as you are defining it here dataType:'json' but you are not sending that. I would redo your ajax call like this so that you can see other errors as well:
$.ajax({
type: 'GET',
url: 'SGWEB/header.php',
data: {
'funct': funct,
'val': val
},
success: function (result) {
console.log(result);
callback(result);
},
error: function (xhr, textStatus, error) {
console.log(xhr);
console.log(textStatus);
console.log(error);
}
});

Unable to access json data retrieved from php page using jquery $.ajax

How to access this json data in JavaScript.
when I alert it the result is undefined
Here is jQuery code
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Here is the problem
alert(data[0]['Result']);
}
});
This is PHP code
$data=array($no);
for($i=0;($i<$no && ($row=mysql_fetch_array($result)));$i++)
{
$data[$i]=array();
$data[$i]['Result'] = $row['Result'];
$data[$i]['TestCode'] = $row['TestCode'];
$data[$i]['TestStatus'] = $row['TestStatus'];
$data[$i]['SrNo'] = $row['SrNo'];
}
$data1=json_encode($data);
echo $data1;
exit;
I have tested the PHP file independently,
The json data is output as follows:
[{"Result":"1","TestCode":"22","TestStatus":"0","SrNo":"1"},{"Result":"1","TestCode":"23","TestStatus":"1","SrNo":"2"}]
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = jQuery.parseJSON(data)
alert(data[0]['Result']);
}
});
You can access to your data by doing
data[0].Result
It's an Object, not an array.
so data[0]['Result'] it's not the proper way
EDIT:
Since you have more objects, you have to do a loop this way:
$.each(data, function(key, val){
console.log(val.Result);
console.log(val.TestCode);
//...
});
When you see something like
{
"foo":"bar",
...
}
you can access to it the same way as above:
name_of_the_object.foo
that will have the value "bar"
Try to add parse JSON. I have added. Now it may be work.
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = $.parseJSON(data)
alert(data[0]['Result']);
}
});

Categories