How to replace function params? - javascript

I'm using the following code to make ajax call where the form data is passed as params.
//ajax call
function restServiceCall(origin,destination,tripType,dateDepart,dateReturn){
dataString = 'origin='+ origin + '&destination=' + destination + '&tripType='+tripType;
$.jsonp({
"url": flightURL,
callbackParameter:jsonpCallBack,
data: dataString,
beforeSend:function(){$('#loadingdiv').show()},
"success": function(data) {
if(data.error != null){
$('#errtitle').html('<h2 class="pgtitle">Error !! '+data.error+'</h2>').show();
$("#displaydiv,loadingdiv").hide();
}else{
renderData (data,dateDepart,dateReturn);
}
},
"error": function(xOptions, textStatus) {
$('#errtitle').html('<h2 class="pgtitle">Sorry the service you are looking for is currently unavailable</h2>').show();
$("#displaydiv,loadingdiv").hide();
}
});
}
Besides making the call from form I also use it in the following function wherein I just need to pass either the dateDepart/dateReturn as params.
//for pagination
$('.pagenation a').bind('click',function(){
var numDays = 7;
var self = $(this);
var dateTemp = self.parents(':eq(1)').attr('id')=="onewaytripdiv"? parseDate(dateDepart):parseDate(dateReturn);
if(self.hasClass('left')){
var tempDepDate = removeNumOfDays(dateTemp,numDays);
}else{
var tempDepDate = addNumOfDays(dateTemp,numDays);
}
var changedDate = tempDepDate.getDate()+' '+cx.monthNamesShort[tempDepDate.getMonth()]+' '+tempDepDate.getFullYear();
if(self.parents(':eq(1)').attr('id')=="onewaytripdiv"){
dateDepart = changedDate;
}else{
dateReturn = changedDate;
}
restServiceCall(origin,destination,tripType,dateDepart,dateReturn);
});
I would like to remove the params in the function call, as the params may vary. Please suggest an alternative to pass the params.

How about passing an array of parameters instead? And then pass another value, such as an integer to indicate to the function what to expect in it's parameter array.
e.g
restServiceCall(myParams, 0);

Related

How to Send Ajax Request After A Specific Time

How to Send Ajax Request in specific time and only that particular event
I m User Time Interval But it’s not Working.
i want get data in request 1 for use in request 2 but it get null data in request 2
setInterval()
it's not Working for me.
I want To send Request 2 After the some time of Request 1
Request 1:-
$(document).on("change", ".supplyItem", function (event) {
var id = $(this).attr("data-id");
var supplyItem = $(".supplyItem[data-id=" + id + "]").val();
var hospital = $("#hospital").val();
var physician = $("#physician").val();
var category = $("#category").val();
var manufacturer = $("#manufacturer").val();
var project = $("#project").val();
if (hospital != "" && physician != "" && category != "" && manufacturer != "" && project != "") {
$.ajax({
url: "{{ URL::to('admin/repcasetracker/getitemfile')}}",
data: {
supplyItem: supplyItem,
hospital: hospital,
project: project,
},
success: function (data) {
console.log(id);
if (data.status) {
var html_data = '';
var item = data.value;
console.log(item);
$('.hospitalPart[data-id=' + id + ']').val(item.hospitalNumber);
$('.mfgPartNumber[data-id=' + id + ']').val(item.mfgPartNumber);
// $('.mfgPartNumber[data-id='+id+']').text('something');
} else {
$('.hospitalPart[data-id=' + id + ']').val('');
$('.mfgPartNumber[data-id=' + id + ']').val('');
}
$('.quantity[data-id=' + id + ']').val('');
$('.purchaseType[data-id=' + id + ']').val('');
$('#serial-text' + id).val('');
$('#serial-drop' + id).val('');
$('#serial-drop' + id).empty();
}
});
}
});
Request 2:-
$(document).on('change', '.supplyItem', function (event) {
var timer, delay = 2000;
var id = $(this).attr("data-id");
var client = $("#hospital").val();
timer = setInterval(function(){
var supplyItem = $(".supplyItem[data-id=" + id + "]").val();
var hospitalPart = $(".hospitalPart[data-id=" + id + "]").val();
var mfgPartNumber = $(".mfgPartNumber[data-id=" + id + "]").val();
alert(supplyItem);
alert(hospitalPart);
alert(mfgPartNumber);
$.ajax({
url: "{{ URL::to('admin/repcasetracker/getdevicedata')}}",
data: {
supplyItem: supplyItem,
hospitalPart: hospitalPart,
mfgPartNumber: mfgPartNumber,
client: client,
},
success: function (data) {
if (data.status) {
var html_data = '';
var check = data.value;
if (check == 'True') {
html_data += "<option value=''>Purchase Type</option><option value='Bulk'>Bulk</option><option value='Consignment'>Consignment</option>";
$('.purchaseType[data-id=' + id + ']').html(html_data);
} else {
html_data += "<option value=''>Purchase Type</option><option value='Consignment'>Consignment</option>";
$('.purchaseType[data-id=' + id + ']').html(html_data);
}
}
}
});
}, delay);
clearInterval(timer);
});
You can move Request 2 into a function and this JS code will call the Request2 function after given interval of time (milliseconds), I have set it to 5 seconds for now.
setInterval(function () { Request2(); }, 5000);
function Request2(){
console.log("Request 2 called");
//add request 2 code here
}
jQuery's $.ajax method returns a promise, which is passed the result of the server-side call. You can chain these calls together so that you can build the result of multiple ajax calls. When you use it this way you do away with success callbacks as they are no longer necessary.
Applied to your code it might looks something like this:
$(document).on("change", ".supplyItem", function (event) {
var id = $(this).attr("data-id");
var supplyItem = $(".supplyItem[data-id=" + id + "]").val();
var hospital = $("#hospital").val();
var physician = $("#physician").val();
var category = $("#category").val();
var manufacturer = $("#manufacturer").val();
var project = $("#project").val();
if (hospital != "" && physician != "" && category != "" && manufacturer != "" && project != "") {
$.ajax({
url: "{{ URL::to('admin/repcasetracker/getitemfile')}}",
data: {
supplyItem: supplyItem,
hospital: hospital,
project: project,
})
.then(function(data1){
// process result of call1 and make call2
var item = data1.value;
return $.ajax({
url: "{{ URL::to('admin/repcasetracker/getdevicedata')}}",
data: {
supplyItem: supplyItem,
hospitalPart: value.hospitalPart, // note using result from 1 directly
mfgPartNumber: value.mfgPartNumber,
client: hospital
}
});
})
.then(function(data2){
// process result of call2
});
};
});
The point here is that you don't need to stash the result of call1 into some elements and re-read them before making call2, and trying to wait enough time before making call2. You just chain it all together with then.
Ok first though: Instead of using setInterval and then clearing the interval after it has run a single time, why not just use
setTimeout(function, delay);
Then personally I prefer to use XMLHttpRequest instead of Jquery AJAX, Jquery uses XMLHttpRequest at its base anyway,I just prefer it so I dont have to use Jquery, but if your already using Jquery in your site then it should be no more heavy. Here is a quick example of XMLHttpRequest so u can use it if you prefer.
var xhr = new XMLHttpRequest();
xhr.open("POST", 'URL::to("admin/repcasetracker/getdevicedata")', true);
xhr.setRequestHeader("Content-Type", "application/json charset=utf8");
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// content is loaded...
if (xhr.responseText) {
//Some code to run after the server responds and it was successfull
}
}
};
xhr.send(JSON.stringify({test:'test'})); //This is the data you are handing to the server
Notice the use of xhr.responseText, JQuery uses the same variable and this is usually the response from the server. One sure way to know is use your browser's debugging engine (F12 on Chrome and Firefox, have no idea on other browsers) to inspect the variables, it is very easy to ascertain the correct variable to use.
And then one last thought: I see you are not declaring the content-type and not JSON.stringify'ing() your data when you send it to the server.
Best way to debug a situation like this is 'proccess of elimation' so find out if the server is receiving the data then if the server is proccessing the data correctly and then check if the server is sending the data correctly.
If you are using Nginx use the /var/log/nginx/error.log to see if it throws any errors ( tip: tail -f /var/log/nginx/error.log | Apache uses /var/log/http/error.log on most distros ) and if you are using .NET just debug it in Visual Studio.
And read up on the Jquery success event there is 2 more arguments that gets passed - String textStatus and jqXHR jqXHR
http://api.jquery.com/jquery.ajax/
So to summarize:
Make sure to declare the dataType: 'json'
Use the correct variable, should be responseText
when passing the server data and using 'json' make sure to JSON.stringify() it
And I don't quite see why you want to use setTimeout in the first place.
If you are simply waiting for the server to respond then using any type of delay will be a terrible idea, instead use the events that gets fired after the server responds.
So in Jquery that is success: function() {} and error: function() {}
and in XMLHttpRequest its the xhr.onreadystatechange = function () { }

Function as parameter in Jquery Ajax

Is it possible to put a function into a parameter for Jquery Ajax like below. dataType and data are given as functions. dataType returns a value of JSON if the returntype is JSON and text if isJson is false.
dataVal and dataVar are arrays containing the parameter names and values used to construct the data paramater. The result of the data: function would be a string as:
{dataVar[0]:dataVal[0],dataVar[1]:dataVal[1],.....,}
I'm getting an error when I try this, so, just wanted to know if this method was possible.
function getAjaxResponse(page, isJson, dataVar, dataVal, dfd) {
$.ajax(page, {
type: 'POST',
dataType: function () {
if (isJson == true) {
return "JSON";
} else {
return "text";
}
},
data: function () {
var dataString = '{';
for (var i = 0; i < dataVar.length; i++) {
dataString = dataString + dataVar[i] + ':' + dataVal[i] + ',';
}
console.log(dataString);
return dataString + '}';
},
success: function (res) {
dfd.resolve(res);
}
});
}
Edit
As per answers and comments, made the changes. The updated function is as below. This works:
function getAjaxResponse(page, isJson, dataVar, dataVal, dfd) {
$.ajax(page, {
type: 'POST',
dataType: isJson ? "JSON" : "text",
data: function () {
var dataString ="";
for (var i = 0; i < dataVar.length; i++) {
if (i == dataVar.length - 1) {
dataString = dataString + dataVar[i] + '=' + dataVal[i];
} else {
dataString = dataString + dataVar[i] + '=' + dataVal[i] + ',';
}
}
return dataString;
}(),
success: function (res) {
dfd.resolve(res);
}
});
}
And my original question is answered. But apparently, data is not getting accepted.
The return value of the data function is just treated as the parameter name and jquery just adds a : to the end of the request like so:
{dataVar[0]:dataVal[0]}:
So, my server is unable to pick up on the proper paramater name.
From the manual:
data
Type: PlainObject or String
So no.
Call the function. Use the return value.
data: function () { ... }();
// ^^ call the function
Not that way. But it will work with a little change:
(function () {
if (isJson == true) {
return "JSON";
} else {
return "text";
}
})()
That should work. You just call the function immidiately after you created it. This way, dataType is a String and the script will work.
Same with data. Also use the (function(){})()-notation here
jquery just adds a : to the end of the request like so:
{dataVar[0]:dataVal[0]}:
No, your devtools display does. However, as you're data string does not contain a = sign, and you send the content as application/x-www-form-urlencoded, the whole body is interpreted as if it was a parameter name.
For sending JSON, you should:
use contentType: "application/json"
use data: JSON.stringify(_.object(dataVar, dataVal))1
to ensure valid JSON is sent with the correct header (and correctly recognised as such at the server).
1: _.object is the object function from Underscore.js which does exactly what you want, but you can use an IEFE as well:
JSON.stringify(function(p,v){var d={};for(var i=0;i<p.length;i++)d[p[i]]=v[i];return d;}(dataVar, dataVal))
You need to call the function with parenthesis like below:
function func1(){
//func1 code in here
}
function func2(func1){
//func2 code in here
//call func1 like this:
func1();
}
So, you can use like this:
data: function () {
//your stuff her
}(); // which mean you are having data()

Removing Javascript alert line stops my append code working correctly

So, I've got the below code: -
function testing(results) {
$table = $('#formList')
for (var event in results) {
var formIDX = results[event]["forms_idx"]
var formID = results[event]["form_id"]
var eventIDX = results[event]["events_idx"]
var eventID = results[event]["event_id"]
var objID = results[event]["object_id"]
var testVal = results[event]["value"]
alert($table.find("#" + formIDX).find('td:eq(1)').find("div").find("table").html())
$subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
var url ="http://localhost:3278/FARTFramework/testScenario/ajaxPopulateSubTables"
$.post(url, {
formID: formID, eventIDX:eventIDX, eventID:eventID, objID:objID, testVal:testVal
}, function(data) {
$subTable.append(data);
}).done(function(){});
}
}
It basically takes a JSON file and then adds the data into the right sub tables within a main table via appends etc.
The oddity is during debug I had an alert in there to check the html of the table it was identifying (making sure it had found the right sub table etc) and all worked well. But if I remove that alert it then suddenly only appends all the data to the last sub table in the main table?! Any clues?
It's a classic JavaScript closure-loop problem. The variables defined in the for loop are being reassigned each time within the loop and responses from the AJAX requests(which are async) get appended to the last sub-table. It works when you have an alert because the variables have not been reassigned(as alert blocks the for loop execution) by the time AJAX request is completed.
You could handle this by having a function do the AJAX request and append. The variables are not reassigned within this function and hence should work.
function testing(results) {
$table = $('#formList')
function appendSubTable(formIDX, formID, eventIDX, eventID, objID, testVal){
alert($table.find("#" + formIDX).find('td:eq(1)').find("div").find("table").html())
var $subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
var url ="http://localhost:3278/FARTFramework/testScenario/ajaxPopulateSubTables"
$.post(url, {
formID: formID, eventIDX:eventIDX, eventID:eventID, objID:objID, testVal:testVal
}, function(data) {
$subTable.append(data);
}).done(function(){});
}
for (var event in results) {
var formIDX = results[event]["forms_idx"]
var formID = results[event]["form_id"]
var eventIDX = results[event]["events_idx"]
var eventID = results[event]["event_id"]
var objID = results[event]["object_id"]
var testVal = results[event]["value"]
appendSubTable(formIDX, formID, eventIDX, eventID, objID, testVal);
}
}
Without seeing more of your code, I can't say for sure. But when I had a similar issue it was because I was using append outside of my $(document).ready(function(){ /*stuff here*/ })
Essentially the object I was appending to hadn't loaded yet.
in your Ajax call use its argument 'async';
it accepts Boolean value, pass the value 'false' in it.
Try it
Move
$subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
To your callback function:
$.post(url, {
formID: formID, eventIDX:eventIDX, eventID:eventID, objID:objID, testVal:testVal
}, function(data) {
$subTable = $table.find("#" + formIDX).find('td:eq(1)').find("div").find("table")
$subTable.append(data);
}).done(function(){});

Use a FOR loop within an AJAX call

So, what i'm trying to do is to send an AJAX request, but as you can see i have many fields in my form, and i use an array to make validations, i would like to use the same array, to pass the values to be sent via AJAX:
I never used the for loop in JS, but seems familiar anyway.
The way the loop is made, obviously wont work:
for (i=0;i<required.length;i++) {
var required[i] = $('#'+required[i]).attr('value');
This will create the variables i want, how to use them?
HOPEFULLY, you guys can help me!!! Thank you very much!
required = ['nome','sobrenome','endereco','codigopostal','localidade','telemovel','email','codigopostal2','localidade2','endereco2','nif','entidade','codigopostal3','localidade3','endereco3','nserie','modelo'];
function ajaxrequest() {
for (i = 0; i < required.length; i++) {
var required[i] = $('#' + required[i]).attr('value');
var dataString = 'nome=' + required[0] + '&sobrenome=' + required[1];
}
$.ajax({
type: "POST",
url: "ajaxload/como.php",
data: dataString,
success: function() {
$(".agendarleft").html("SUCESS");
}
});
To help ensure that the appropriate element IDs and values are passed, loop through the various elements and add the data to an object first.
jQuery:
required = ['nome', 'sobrenome', 'endereco', 'codigopostal', 'localidade', 'telemovel', 'email', 'codigopostal2', 'localidade2', 'endereco2', 'nif', 'entidade', 'codigopostal3', 'localidade3', 'endereco3', 'nserie', 'modelo'];
function ajaxrequest() {
var params = {}; // initialize object
//loop through input array
for (var i=0; i < required.length; i++) {
// set the key/property (input element) for your object
var ele = required[i];
// add the property to the object and set the value
params[ele] = $('#' + ele).val();
}
$.ajax({
type: "POST",
url: "ajaxload/como.php",
data: params,
success: function() {
$(".agendarleft").html("SUCESS");
}
});
}
Demo: http://jsfiddle.net/kPR69/
What would be much cleaner would be to put a class on each of the fields you wish to save and use this to iterate through them. Then you wouldn't need to specify the input names either and you could send a json object directly to the Service;
var obj = {};
$('.save').each(function () {
var key = $(this).attr('id');
var val = $(this).val();
if (typeof (val) == "undefined")
val = "''"
obj[key] = val;
}
Then send obj as the data property of your AJAX call....
There are a few issues with your code. 'required' is being overwritten and is also being re-declared inside of the loop.
I would suggest using pre-written library, a few I included below.
http://jquery.malsup.com/form/#validation
https://github.com/posabsolute/jQuery-Validation-Engine
Otherwise the follow would get you close. You may need to covert the array into a string.
var required = ['nome','sobrenome'];
function ajaxrequest() {
var values;
for (i = 0; i < required.length; i++) {
var values[i] = $('#' + required[i]).attr('value');
}
$.ajax({
type: "POST",
url: "ajaxload/como.php",
data: values,
success: function() {
$(".agendarleft").html("SUCESS");
}
});
}

jquery passing array data to function

I have made a function to get the variable of onclick and pass it to the function, but I want it in different format:
$('.ajax').live('click', function() {
var Loading = 'Loading...';
var url = $(this).attr('href');
var container = '#myDivcontent';
looadContents(url,Loading,container);
return false;
});
and the function looks like :
looadContents(url,Loading,container) {
..
...
$(contaner).load(url);
...
..
}
I would like to have like array format or json data format when I call the function:
$('.ajax').live('click', function() {
looadContents({
url : $(this).attr('href'),
Loading : 'Loading...',
container: '#myDivcontent'
});
return false;
});
Any idea how can I do this?
If you pass the information like an object, you can simply access it as one:
function looadContents(options) {
$(options.container).load(options.url);
}
looadContents({ url: '...', container: '#...' });
This syntax works as expected.
function display(obj)
{
console.log(obj.name + " loves " + obj.love);
}
display({name:"Jared", love:"Jamie"});
Is this possibly what you are looking for?
function looadContents(o) {
alert(o.url);
alert(o.container);
}
looadContents({ url:"abc", container: "def" });
Use what's sometimes called an "options" object (what you refer to as "JSON data format" is simply a JavaScript object literal):
function loadContents(options) {
var url = options.url;
var Loading = options.Loading;
/* etc. */
}
You can also leverage this approach to provide default values for certain parameters:
function loadContents(options) {
var url = options.url || "http://default-url.com/",
var Loading = options.Loading || "Loading...";
var container = options.container || "#container";
$(container).load(url);
}
Try this
looadContents(input) {
//...
$(input.contaner).load(input.url);
//...
}

Categories

Resources