How to write a small helper function for Ajax Post requests? - javascript

such that an object literal contains the parameters you want to send and the result is a string you can send as data.
Here is my first try:
function makeData(obj) {
var data_send = '';
_.each(obj, function (val, key) {
data_send += encodeURIComponent(key) + '=' + encodeURIComponent(val) + '&';
});
data_send.slice(1,-1);
return data_send;
}
Is this the correct form for ajax post data?

Related

How to get POST raw data on PHP using $_SERVER

I have a dynamic page using on-page-filter i change the data on the page using AJAX response, my question is how can i get from POST raw data when on the URL is not written..
my link on the page is similar like this "example.com/default/list_data"
and on my AJAX I created the query string like this
function create_qs() {
var qs = '?1=1';
$('.fltlist').each(function (index, item) {
var val = ($(item).hasClass('active')) ? 'Y' : 'N';
qs += '&' + $(item).attr('f') + '=' + val;
});
qs += '&from=' + $('#startdate').val();
qs += '&to=' + $('#enddate').val();
qs += '&sort=' + $('#sort_sppt_ticket').val();
qs += '&search=' + $('#search').val();
qs += '&developer=' + $('#fltlistdev').val();
return qs;
}
but on the URL bar it didn't show anything (because the post) I'm using AJAX POST..
i need the raw data and store on the PHP array (maybe in global variable) to pass the raw data to another page..
any help?
Try using this
$rawData = file_get_contents("php://input");

Recursive promise not returning expected value

With a slight modification, I am attempting to use the code provided by Bergi in jQuery Recursive AJAX Call Promise. In my case I make an AJAX call to test if a username is already used. If it is already in use then compose a new username and test that one. Once we have a username that is not in use then we are done and return that unused username. However, I am not getting the expected return value. The return value I get is undefined. The console log statement:
console.log("Return => " + username);
just before the return from the requestUsername function shows that I am returning a good value, but it is not making it to the:
requestUnused().done(function(unused_uname)
statement. Here is my code:
$(document).ready(function() {
function request(query_val) {
// return the AJAX promise
return $.ajax({
url: "/php/is_dup_ad_json.php",
method: 'GET',
dataType: 'json',
data: {
query: query_val, sid: Math.random()
},
});
}
function requestUsername(username) {
console.log("Initial => " + username);
return request(username).then(function(ajax_json){
$.each(ajax_json, function(key, value) {
$.each(value, function(k, v) {
if ((k == "duplicate") && (v > 0)) {
// try again with a different username
var first_initial = fname.substr(0,1);
var surname = lname.substr(0,6);
var idx = v + 1;
var tmpUname = surname + first_initial + idx;
console.log("Temp => " + tmpUname);
return requestUsername(tmpUname);
}
else {
console.log("Return => " + username);
return username;
}
});
});
});
}
function requestUnused(){
var fname = "bugs";
var lname = "bunny";
var first_initial = fname.substr(0,1);
var surname = lname.substr(0,7);
var init_uname = surname + first_initial;
return requestUsername(init_uname);
}
$("#test").on('click', function() {
requestUnused().done(function(unused_uname) {
console.log("Done => " + unused_uname);
});
});
});
Without debugging tools at hand, I would guess that the return value from "requestUnused()," which is a ".then" returned from "requestUsername" is competing with the ".done". I believe ".done" and ".then" serve a similar purpose. If you want to keep a modular approach, separating the functions as it were, you could define the function in the ".then" externally and remove "requestUsername" entirely. Then (no pun intended) call "request" directly in "requestUnused," applying the ".then" functionality extracted previously in the ".click" function instead of ".done."
Alternatively, you could simply call "requestUnused()" in the click function without a ".done".

jquery Return ajax response and user defined variable to function

I am having an issue passing in a defined variable to a function from an ajax call. What should happen is on click of an element, it should pass the text of the clicked element to the function, do an ajax call which has nothing to do with the defined variable, return the variable and the data from the call to another function that renders the elements. When I get to the function that renders the html content, the variable is now undefined.
My question is how can I send the ajax response data and a user defined variable that has no correlation to the ajax call to another function?
My JSON function:
function getJSONP(url, data) {
return $.ajax(url, {
dataType: 'json',
data: data
});
}
My click event:
$('.day').on('click', function() {
getTimes($(this).text());
});
My first function that does the ajax (this is where the selector returns a value):
function getTimes(selector) {
console.log(selector);
var eventDate = selector;
getJSONP(CAL_API_URL).then(function(data) {
data = _.valuesIn(data)[5][0];
return data;
}).then(appendTimes(eventDate));
}
My 2nd function that renders the HTML (here the selector is undefined):
function appendTimes(dates, selector) {
console.log(selector);
_.forEach(dates, function(k, v) {
// Returns each event
_.forEach(k, function(k2, v2) {
// Returns multiple objects for each event
var availableTimes = k2.startTime + " (" + k2.open + " spots left!)",
timeId = k2.id;
$('.timeslot select').append('<option data-id="' + timeId +'">' + availableTimes + '</option>');
});
});
}
In this case, if you switched appendTimes to only accept selector and have it return a function, the returned function will get called when data is available.
function appendTimes(selector) {
console.log(selector);
return function (datas) {
_.forEach(dates, function(k, v) {
// Returns each event
_.forEach(k, function(k2, v2) {
// Returns multiple objects for each event
var availableTimes = k2.startTime + " (" + k2.open + " spots left!)",
timeId = k2.id;
$('.timeslot select').append('<option data-id="' + timeId +'">' + availableTimes + '</option>');
});
});
}
}
You are calling the method, not assigning a reference to it
}).then(appendTimes(eventDate));
needs to use a closure or binding
}).then(function() { appendTimes(eventDate) });
also you can not return from a promise so the return data is useless.

Force function to show result when they received with jquery.get method

this function gets results with $.get method from an asp ashx XML file :
$.get("http://www.example.com/example.ashx",
{ From: txtFrom, To: txtTo, Date: txtTime },
function (data) {
var arrFrom = [], arrTo = [], arrPrice = [];
$(data).find("F").each(function (index, item) {
arrFrom[index] = [];
arrTo[index] = [];
arrPrice[index] = [];
$(item).find("From").each(function (i, fromIndex) {
arrFrom[index].push($(fromIndex).text());
});
$(item).find("To").each(function (i, toIndex) {
arrTo[index].push($(toIndex).text());
});
$(item).find("Price").each(function (i, priceIndex) {
arrPrice[index].push($(priceIndex).text());
});
});
/**********************************************************/
var htmlResult = "<table style=\"background-color:red;\">";
for (i = 0; i < arrFrom.length; i++) {
htmlResult += "<tr><td>" + arrFrom[i] + "</td>" +
"<td>" + arrTo[i] + "</td>" +
"<td>" + arrPrice[i] + "</td></tr>"
};
htmlResult += "</table>";
$('#divSearchResults').html(htmlResult);
/**********************************************************/
}, "text");
but ashx needs some time (unpredictable) to response.
I used a function to recall this each 5seconds, but it is not affordable.
how can I make htmlResult be created right when the response is received?
Your sample code is correct, in the sense that the anonymous function that you've defined fires as soon as your backend responds. If your data is empty, it could mean that something happens to the data while you're processing it in your javascript, your backend returned an empty dataset, or your backend timed out. To check whether the problem is with your backend or your data processing, try this:
$.get("http://www.example.com/example.ashx",
{ From: txtFrom, To: txtTo, Date: txtTime },
function (data) {
console.log(data);
//Or in case you don't have a developer console use alert:
alert(data);
}, "text");
You should now be able to verify that you are indeed getting data. If that's the case, then something is happening to the data when you're parsing it, and you should debug that code instead, perhaps with a static dataset. You could also make your life a lot easier by sending json encoded data instead of plaintext. I don't know how you would do that with your backend but I'm sure Google will help. On the javascript side of things you could then change the last line to:
}, "json");
Then, instead of find()ing things, you would have a neat json object to work with.

pass two parameters DDL in JavaScript / jQuery

This function works fine but passes only one parameter from one DropDownList to the controller. How to make the transfer of two parameters of an (two DDL)?
$(function () {
$('#DDL_1_ID').change(function () {
var URL = $('#FormID').data('someAction');
$.getJSON(URL + '/' + $('#DDL_1_ID').val(), function (data) {
$.each(data, function (i, format) { });
});
});
});
You could continue appending query string parameters as you've done with ddl_1_tc...
$.getJSON(URL + '/' + $('#DDL_1_ID').val() + '&myotherparam=' + yourotherinput
Your url appears to be malformed though. I believe you're missing the name of the first value...
$.getJSON(URL + '?nameforfirstparam=' + $('#DDL_1_ID').val() + '&nameforsecondparam=' + yoursecondinput

Categories