Delivery value input to function - javascript

I have written a simple page which have a form input. While a user prints text at the form a script gets request on server and take JSON data. I need to pass a value from the input to a function which reprocess the value.
var search = document.querySelector('#search');
function iReceived(msg) {
var mass = msg.data;
mass.map(function(e) {
var city = document.querySelector('#city');
var newLi = document.createElement('li');
newLi.innerHTML = e.Description;
city.appendChild(newLi);
});
};
function Foo(e) {
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "https://api.novaposhta.ua/v2.0/json/",
data: {
"modelName": "Address",
"calledMethod": "getCities",
"methodProperties": {},
"apiKey": "6f94a6391cb5134ee68ddb7924de2a3d"
},
success: iReceived, /* this function I would like to pass value input
but I can write just a reference on this
function without () and arguments */
});
console.log(e.target.value);
};
search.oninput = Foo;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form>
<input type="text" id="search" onchange="Foo()">
</form>
<div id="content"></div>
<div id="city"></div>
May have I built this program a bad way?

Have you read the jQuery docs?
success Type: Function( Anything data, String textStatus, jqXHR jqXHR
)
A function to be called if the request succeeds. The function gets
passed three arguments: The data returned from the server, formatted
according to the dataType parameter or the dataFilter callback
function, if specified; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the
success setting can accept an array of functions. Each function will
be called in turn. This is an Ajax Event. timeout
So in your case you would modify your Foo() functions success method like below
function Foo(e) {
$.ajax({
type: "POST",
dataType: 'jsonp',
url: "https://api.novaposhta.ua/v2.0/json/",
data: {
"modelName": "Address",
"calledMethod": "getCities",
"methodProperties": {},
"apiKey": "6f94a6391cb5134ee68ddb7924de2a3d"
},
success: function(data) {
// the data is the data returned from the server
// do whatever you want with the data here
// get the value you need for iReceived here.
iReceived(value); /* this function I would like to pass value input
but I can write just a reference on this
function without () and arguments */
}
});
console.log(e.target.value);
};

I can't comment yet but here is a good starting point:
You should start by having the user submitting their data with a button before it runs the function. As soon as you input any text into that box the json request fires off with one character, then two, and so on.
Currently what ever you put into that box returns 2070 results that are all objects, I'm not sure of the formatting of the api but you should try to call just the part of the objects/array that you need.

Related

A part of AJAX response storing in PHP variable

I need to store a piece of data, into PHP variable, which is received through AJAX response in an input box. How can I do this?
<script type="text/javascript">
$(document).ready(function() {
$("#user_id").change(function() {
var id = $(this).val();
var dataString = 'user_id='+ id;
$.ajax({
type: "POST",
url: "wmat_details.php",
data: dataString,
cache: false,
success: function(result) {
var data = result.split(",");
$('#name').val(data[0]);
$('#email').val(data[1]);
$('#ref_id').val(data[2]);
$('#candidature_start').val(data[3]);
$('#candidature_end').val(data[4]);
$('#default_attempts').val(data[5]);
$('#existing_complimentary').val(data[6]);
$('#wmat_start').val(data[9]);
$('#wmat_end').val(data[10]);
$('#attempts_taken').val(data[11]);
}
});
});
});
</script>
As shown in above code, I want to store $('#attempts_taken').val(data[11]); this value to a PHP variable. Any insight is appreciated.
Unfortunately you can't.
PHP is server side while jQuery (JS) is client side. They are two separate layers of abstraction that interact only when the client call the server.
I don't have enough informations about what you need to do with data[11] but it seems that you have only one option: make a consecutive AJAX call to the php file that will manipulate data[11].
The consecutive AJAX call must be executed from inside the first call success callback; something like this:
success: function(result){
// Your on success logic
// ...
// Prepare the object to send to the server
var objData = {};
objData.attemptsTaken = data[11];
// Execute the second AJAX call to the server
$.ajax({
type: "POST",
url: "second_call_destination_file.php",
data: objData,
success: function(result){
// Do something on success
},
error: function(){
// Do something on error
},
complete: function(){
// Do something on complete (executed after success and error)
}
}
You cannot store ajax response into a php variable.
way 1 :
You can make another ajax call.
way 2 :
you can set session.

Access to object after ajax function

I have this ajax jquery code:
$("#serial_number").submit(function(e) {
var url = "/getVoucher"; // the script where you handle the form input.
$.ajax({
type: "GET",
url: url,
data: $("#serial_number").serialize(),
dataType: "json",
success: function(data)
{
console.log(data);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
and I get this fron console.log:
How I can access to object Code element?
I try with: data.Code also try data.Description but browser give me error... How to access inside success function in ajax code?
When you console.log a variable, the output in the console are it's contents, so if you are still seeing:
Object{ data: Object }
That means that the variable data has a key data inside of it. Try:
console.log( data.data.Code );
To access the object's contents.

AJAX form submission hits proper endpoint but doesn't pass variables

I'm working on the review page before a user buys a product, and on the page is a small field for discount codes, which I want to pass to an endpoint via ajax. I'm using the following javascript function, and the submission happens and returns (even hits the intended endpoint) - but no data gets passed through (verified in logs).
Any idea why no params would be getting passed through?
<script>
$("#discount_code_submit").click(function() {
var url = "/confirm_discount"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#discount_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response
if(data != "false")
{
console.log(data);
}
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
This is because jQuery's serialize method creates a String representation of the form data, in the traditional url query string format. (Please see here: http://api.jquery.com/serialize/)
E.g., calling serialize can return a string such as:
'?query=help&numResults=200'
On the other hand, jQuery's ajax method expects the form data to be provided as an object literal. (Please see here: http://api.jquery.com/jQuery.ajax/)
E.g.
{
query: 'help',
numResults: 200
}
So you can change your ajax call to look like:
$.ajax({
type: "POST",
url: url,
data: {
param1: 'somevalue',
param2: 200
},
success: function(data)
{
alert(data); // show response
if(data != "false")
{
console.log(data);
}
}
});
Or, you could also construct your object literal from the form using a custom function and then provide the reference in the ajax call.
$.ajax({
type: "POST",
url: url,
data: myPreparedObjectLiteral,
success: function(data)
{
alert(data); // show response
if(data != "false")
{
console.log(data);
}
}
});
You could also use http://api.jquery.com/serializeArray/ since it does pretty much what you'll need to convert a form to the json literal representation.
Finally, for a good discussion on converting forms to json objects for posting, you can see the responses here on an SO question: Convert form data to JavaScript object with jQuery

Why is AJAX/JSON response undefined when used in Bootstrap typeahead function?

I created a function that makes a jquery AJAX call that returns a JSON string. On its own, it works fine -- and I can see the JSON string output when I output the string to the console (console.log).
function getJSONCustomers()
{
var response = $.ajax({
type: "GET",
url: "getCustomers.php",
dataType: "json",
async: false,
cache: false
}).responseText;
return response;
};
However, when I set a variable to contain the output of that function call:
var mydata = getJSONCustomers();
, then try to use it within my Twitter-Bootstrap TypeAhead function (autocomplete for forms):
data = mydata;
console.log(data);
I get an 'undefined' error in my console.
Below is a snippet of this code:
$(document).ready(function() {
var mydata = getJSONCustomers();
$('#Customer').typeahead({
source: function (query, process) {
customers = [];
map = {};
data = mydata;
console.log(data);
// multiple .typeahead functions follow......
});
Interesting here, is that if I set the data variable to be the hardcoded JSON string returned from the AJAX function, everything works fine:
data = [{"CustNameShort": "CUS1", "CustNameLong": "Customer One"}]
How can I use the JSON string within my typeahead function?
.responseText returns a string. You have to parse the string first to be able to work with the array:
var mydata = JSON.parse(getJSONCustomers());
That being said, you should avoid making synchronous calls. Have a look at How do I return the response from an asynchronous call? to get an idea about how to work with callbacks/promises.
The problem is that the Ajax request hasn't had the chance to complete before typeahead is initialised, so typeahead is initialised with an uninitialised mydata variable. Also, as of jQuery 1.8+ async: false has been deprecated and you need to use the complete/success/error callbacks.
Try this:
function getJSONCustomers(callback) {
$.ajax({
type: "GET",
url: "getCustomers.php",
dataType: "json",
cache: false,
success: callback
});
};
And then you could do something like:
getJSONCustomers(function(mydata) {
// mydata contains data retrieved by the getJSONCustomers code
$('#Customer').typeahead({
source: function (query, process) {
customers = [];
map = {};
console.log(mydata);
// multiple .typeahead functions follow......
});
});
So your code completes the Ajax call before initialising the typeahead plugin.

Waiting for a function to return a value before firing jQuery Ajax request

I'm trying to fire an Ajax request with some data being returned by a function call and, as far as I can tell, the Ajax call isn't waiting for my function call to return.
I'm calling getSelectedMessages to get the values of a variable number of checkboxes before firing an Ajax request with an array of the values returned by getSelectedMessages.
getSelectedMessages looks like this:
var getSelectedMessages = function() {
var selected = [];
$('input:checkbox[name=multipleops]:checked').each(function() {
selected.push($(this).attr('value'));
});
return selected;
}
And the Ajax request that's invoking it looks like this:
$.ajax({
type: "POST",
url: "/api/messages/",
data: { ids: getSelectedMessages(), folder: folder },
cache: false,
success: function(){ location.reload() }
});
I've done a little bit of searching around and all I'm turning up are answers on how to return a value from a call and to it.
use
beforeSend attribute with ajax
try
var getSelectedMessages = function() {
var selected = [];
$('input:checkbox[name=multipleops]:checked').each(function() {
selected.push($(this).attr('value'));
});
return selected;
}
$.ajax({
type: "POST",
url: "/api/messages/",
beforeSend : function () { return jQuery.isEmptyObject(getSelectedMessages); }
data: { ids: getSelectedMessages(), folder: folder },
cache: false,
success: function(){ location.reload() }
});
Reference
beforeSend
isEmptyObject
Call getSelectedMessages() outside the ajax function of jquery (?)
The function is executed before the request is sent.
The real problem is that the getSelectedMessaged() returns an array.
This results in undefined=undefined after serialization in jQuery's internals.
And that gets ignored by the $.ajax(), so it looks like it's not sending in your vars but it's ignoring them because they're undefined.
If you concatenate a string with the values and make it a query string parameter yourself it should work.
I assume you want to send something like ?var[]=something&var[]=somethingelse to the server, so it ends up in PHP as an array?
Than you'll have to build up the string yourself in the getSelectedMessages function.
Hope it helps,
PM5544

Categories