I am desperately trying to submit multiple POST variables via AJAX, but just cant get manage to get the formatting right... Problem is that I have both a hardcoded / written action=problem_lookup variable and a dynamic field input as $(this).val and just cant manage to get both into one data string...
this works well:
data: 'problem=' + $(this).val(),
This does not:
data: { action: 'problem_lookup' , problem: $("problem").val() },
data: { action: 'problem_lookup' , problem: $(this).val() },
data: { action: problem_lookup, problem: $(this).val() },
I tried numerous formats from other threads and looked at the official jquery manual, but cant seem to get this figured out. Any help is appreciated.
EDIT:
full script below, tried the solutions posted so far but no success. $("problem") is a <select> field (with Select2 running) hence shouldnt cause me so much frustration, especially since the original approach with data: 'problem=' + $(this).val(), works fine.
$(function () {
$('#problem').change(function () { // on change in field "problem"
var data = {
action: 'problem_lookup',
problem: $("problem").val()
}
$.ajax({ // launch AJAX connection
type: 'POST', // via protocol POST
url: 'ajax.php',
//data: 'problem=' + $(this).val(), // send $_POST string
//data:"{'action':'"+action+"','problem':'"+$(this).val()+"'}",
//data:"{'action':'problem_lookup','problem':'"+$(this).val()+"'}",
//data: { action: 'problem_lookup' , problem: $("problem").val() },
//data : data_string,
data: $.param(data),
dataType: 'json', // encode with JSON
success: function (data)
{
// do something
},
});
});
});
An issue is in the
$("problem")
Jquery call.
If.problem is a css class try with
$(".problem")
if problem is a css id try with
$("#problem")
For posting arrays of object you can build data as an object containing arrays, changing a little bit your structure. Something like this
Var obj={};
obj.postData=[];
obj.postData.push(/*your first object here*/);
...
obj.postData.push(/*your n-th object here*/);
$.ajax({
.....
data:obj;
......
});
Try the FormData() FormData.
var data = new FormData();
data.append('action', value);
...
You need to specify your data variable first like this:
var data = {
action: 'problem_lookup',
problem: $("problem").val()
}
In AJAX serialize your data using $.param,
data: $.param(data),
Note: Twice check if $("problem").val() is correct. If problem is a class, you need to specify like this $(".problem").val() or if it is ID, $("#problem").val()
Related
My client has a jobs board whose API data I'm pulling via Ajax. I can parse the "jobs" data but cannot seem to pull any thing else. For instance, this works to pull the names of job listings to a select box:
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/jobs/',
type:'GET',
data: 'q=' + "",
dataType: 'json',
success: function( json ) {
$.each(json.jobs, function(i, value) {
$('#myselect').append($('<option>').text(value.title).attr('value', value.title));
});
}
});
But when I change "json.jobs" to anything else like "json.offices" or "json.locations" nothing is pulled. How do I go about accurately targeting these data strings to cull together for a complete careers page? Appreciate any guidance whatsoever thanks.
This is the JSON if you need to take a look:
https://api.greenhouse.io/v1/boards/roivantsciences/jobs/
try pull location.name for all jobs $.each(json.jobs, function(i, value) { $('#myselect').append($('<option>').text(value.location.name).attr('value', value.location.name)); });
Ive done a small test:
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/jobs/',
type:'GET',
data: 'q=' + "",
dataType: 'json',
success: function( json ) {
console.log(json)
}
});
What I got back from console is that your json object only has 'jobs' as the top attribute in it.
You have to go through it like this to get locations:
$.each(json.jobs, function(i, value) {
console.log(value.location);
});
then you have the location object inside this you got the attribute 'name'
so u can get the names with value.location.name
$(".content-short").click(function() {
$(".content-full").empty();
var contentid=$(this).parent().find(".content-full").attr('data-id');
var content=$(this).parent().find(".content-full");
alert(contentid);
var collegename = $(this).attr('data-id');
$.ajax({
type: "post",
url: "contenthome.php",
data: 'collegename=' + collegename,
dataType: "text",
success: function(response) {
$content.html(response);
}
});
});
here the alert displays the specific data-id but
content=$(this).parent().find(".content-full");
this didn't displays data in content-full div with that specific data-id
anything wrong in the code or something else?
the query displays data if i use(."content-full"); instead of
$(this).parent().find(".content-full");
Inside the ajax callback you are using $content, but you declare your variable as content. May that be the problem?
Your question is not clear. What are you trying to achieve?
$('#data').change(function () {
$.ajax({
url: 'richiesta.php',
type: 'POST',
dataType: 'json',
data: {
value: this.value
},
}).done(function (data) {
$('#textfield').val(JSON.stringify(data));
$('#results').val('Descrizione codice: ' + data[0].descrizione_codice);
});
});
richiesta.php is just a file that triggers some functions to get the JSON.
#textfield is correctly populated with the raw JSON, so everything is working properly.
I can't figure out how to output the first item of the JSON identified by the name descrizione_codice in #results.
The JSON is valid, here's an example selecting one option (truncated):
{
"data":[
{
"codice_comparto":"PRO",
"descrizione_codice":"Competenze fisse per il personale a tempo indeterminato",
"codice_siope":"1101",
"descrizione_ente":"",
"ricerca":false,
"idtable":"000717409-1101",
"cod_ente":"000717409",
"anno":"2014",
"periodo":"12",
"codice_gestionale":"1101",
"imp_uscite_att":"756",
"importo_2013":"37718576",
"importo_2014":"32810124",
"importo_2015":null
}
],
"cosa":false
}
I'm doing something wrong is that data(0).descrizione_codice as Firebug tells me "data is not a function"..
I'm not using $.parseJSON because jQuery already parses data correctly thanks to the datatype.
I put up a test page here. You can request the JSON response selecting an option from the dropdown menu.
According to your JSON structure you should be able to access array as data.data
.done(function (data) {
console.log(data.data[0].descrizione_codice);
});
$('#results').val('Descrizione codice: ' + data.data[0].descrizione_codice);
First data is your actual js variable
Second data is your array inside JSON named "data" where we access first element's property named "descrizione_codice"
Hope it clarifies
I have created a good html/javascript program in displaying ajax in my jqgrid. But just recently, I noticed that when I try to save large or many data to save to my table line, it will return http:error.
I really don't understand whats wrong when I can successfully saved small numbers of lines. Someone told me that it was my html/javascript that has a problem since when I try to trace it with delphi(the one I used to create my webservice), it doesn't go into my code (when saving many lines), and will go into my code if only less than 10 line data that i will save (there's no error in tracing). Here's a data that I am sending to my webservice/html request:
{
"SessionID":"66KuzRH1w1sWCM188q4k8BTJb5ijG81v",
"operation":"add",
"transaction_date":"7/27/2011",
"supplier_id":"10000000108",
"wood_specie_id":"1",
"lines":[
{"plank_number":"1","thickness":"4","width":"6","length_t":"8","quantity":"1","board_foot":"16.00","wood_classification_id":"1","price":"15"},
{"plank_number":"2","thickness":"45","width":"6","length_t":"8","quantity":"1","board_foot":"180.00","wood_classification_id":"1","price":"15"},
.
.
.
.
{"plank_number":"22","thickness":"3","width":"6","length_t":"8","quantity":"1","board_foot":"12.00","wood_classification_id":"1","price":"15"},
{"plank_number":"23","thickness":"4","width":"6","length_t":"7","quantity":"1","board_foot":"14.00","wood_classification_id":"1","price":"15"}
],
"scaled_by":"JAYSON","tallied_by":"TALLIED BY","checked_by":"CKECKED BY","total_bdft":"582.84","final":""
}
here's the code in adding my line data:
function tallyAddData(){
var datas = {
"SessionID": $.cookie("SessionID"),
"operation": "add",
//"transaction_num":$('#tallyNo').val(),
"transaction_date":$('#tallyDate').val(),
"supplier_id":$('#supplierInput').attr("name"),
"wood_specie_id":$('#woodSpecie').attr("name"),
"lines":plank_data,
"scaled_by":$('#tallyScaled').val().toUpperCase(),
"tallied_by":$('#tallyTallied').val().toUpperCase(),
"checked_by":$('#tallyChecked').val().toUpperCase(),
"total_bdft":$('#tallyTotal').val(),
"final":"",
};
alert(JSON.stringify(datas));
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'update/tallyHdr',json:JSON.stringify(datas)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$('#tblTallyHdr').trigger('reloadGrid');
}
}
});
}
your are using the Query string to pass the data - the Query string size is limited (http://en.wikipedia.org/wiki/Query_string)
I recommend on passing the data as post:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
you can also read about Jquery post (http://api.jquery.com/jQuery.post/)
Hi Am new to Jquery/ajax and need help with the final (I think) piece of code.
I have a draggable item (JQuery ui.draggable) that when placed in a drop zone updates a mysql table - that works, with this:
function addlist(param)
{
$.ajax({
type: "POST",
url: "ajax/addtocart.php",
data: 'img='+encodeURIComponent(param),
dataType: 'json',
beforeSend: function(x){$('#ajax-loader').css('visibility','visible');}
});
}
but what I cannot get it to do is "reload" another page/same page to display the updated results.
In simple terms I want to
Drag & drop
Update the database
Show loading gif
Display list from DB table with the updated post (i.e. from the drag & drop)
The are many ways of doing it. What I would probably do is have the PHP script output the content that needs to be displayed. This could be done either through JSON (which is basically data encoded in JavaScript syntax) or through raw HTML.
If you were to use raw HTML:
function addlist(param)
{
$.ajax(
{
type: 'POST',
url: 'ajax/addtocart.php',
data: 'img=' + encodeURIComponent(param),
dataType: 'html',
beforeSend: function()
{
$('#ajax-loader').css('visibility','visible');
},
success: function(data, status)
{
// Process the returned HTML and append it to some part of the page.
var elements = $(data);
$('#some-element').append(elements);
},
error: function()
{
// Handle errors here.
},
complete: function()
{
// Hide the loading GIF.
}
});
}
If using JSON, the process would essentially be the same, except you'd have to construct the new HTML elements yourself in the JavaScript (and the output from the PHP script would have to be encoded using json_encode, obviously). Your success callback might then look like this:
function(data, status)
{
// Get some properties from the JSON structure and build a list item.
var item = $('<li />');
$('<div id="div-1" />').text(data.foo).appendTo(item);
$('<div id="div-2" />').text(data.bar).appendTo(item);
// Append the item to some other element that already exists.
$('#some-element').append(item);
}
I don't know PHP but what you want is addtocart.php to give back some kind of response (echo?)
that you will take care of.
$.ajax({
type: "POST",
url: "ajax/addtocart.php",
data: 'img='+encodeURIComponent(param),
dataType: 'json',
beforeSend: function(x){$('#ajax-loader').css('visibility','visible');
success: function(response){ /* use the response to update your html*/} });