Empty Array AJAX - javascript

So I have searched around a bit in hopes of finding a solution to my problem, but have had no luck.
I am basically trying to pass data into the ajax function, but when it passes it to my php file it only returns an empty array (Yes there are a few topics on this, couldn't find any to fit my needs) , here is the console output: Array ()
Its odd because just before the ajax function I log the data, and it prints out each section with no problems.The posting URL is accurate, works fine straight from my form. I have tried to use response instead of data passed through the function, but no luck their either.
Thanks in advance!
Here is the JS file
$(document).ready(function() {
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = [];
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
console.log(data); /////THIS LINE HERE ACTUALLY PRINTS DATA
$.ajax({
url: url,
type: type,
data: data,
success: function(data) {
console.log(data);
}
});
return false;
});
});
And here is my PHP
<?php //removed the issets and other checkers for ease of readability
print_r($_POST);
?>
UPDATE: I have tried to add method:"POST" to my ajax function and it still seems to be printing out blank arrays... Maybe I should convert everything to GET?

jQuery ajax() uses GET as default method. You need to mention method: POST for POST requests.
method (default: 'GET')
$.ajax({
url: url,
method: "POST",
type: type,
data: data,
success: function(data) {
console.log(data);
}
});
Or you can also use post().

EUREKA!!! Wow, the mistake was much simpler than I thought, figured it out solo! Thank you everyone for the tips! Finally got it
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {}; // THIS NEEDS TO BE CHANGED TO BRACKETS!!

Related

Writing specific value from database to HTML via AJAX/jQuery

First time question, hoping for some advice:
Code on webpage:
<form id="inbound" action="javascript:validateinbound();">
<input type="submit" value="Go!" id="inbound">
<script>
function validateinbound() {
$('#inbound:input').each(function () {
var iv = $(this).val();
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
var response = JSON.stringify(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+response);
}
});
});
});
};
</script>
</form>
This returns a string that I would like to work with that looks like this:
Answer:
[{"id":"1","answer":"Pull logging","question_id":"5","feature_id":"1","answer_id":"9"}]
Ideally what I would like to do is only select the 'value' to the maxmail_answer 'key' (hopefully those are the right terms?) to the webpage instead. Right now there is only one value but there will be more in the future so something that could parse this string for a specific key and only output those values.
Visually I would see:
Answer: Pull logging ( and then another Answer: for each value I pull out )
First time ever using this site and these languages so total noob and would appreciate some guidance.
Thanks!
You do not to stringify the JSON response, you can get the value of the key you want using the object notation . as follows:
function validateinbound() {
$('#inbound:input').each(function () {
var iv = $(this).val();
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
//var response = JSON.stringify(data); // no need for this line
$('#response').delay(3600).fadeIn(600);
// catch the answer here
// your result returns within an array so you need to catch the first index
$('#response').append("<p>Answer: </p>"+response[0].answer);
}
});
});
});
};
Besides, ids are unique, you can only access a single element via id selector #, you do not need a .each
What you are receiving from your server is an array of objects in the JSON format. The sample that you have put has the length of "1" and therefore, if want to reach the "id" of the first array, it would be like this:
// var response = JSON.stringify(data); (// don't stringify it!
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+data[0].id);
You need here a loop to go through your array of results and display each result
success: function(data) {
var response = JSON.stringify(data);
$('#response').delay(3600).fadeIn(600);
$.each(response,function(index,value){//the each loop
$('#response').append("<p>Answer: </p>"+value.answer);//get the answer using . notation
});
}
Json.stringify() returns your javascript object as json data, but i think in your case your response is a json data which you need to manipulate. Json.parse() does this for you and you can access your answer as a property of the javascript object.
success: function(data) {
var response = JSON.parse(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+response[0].answer);
}
if your json data has multiple result and you need to work through all of them use a loop.
$.each(response,function(index, object){
var response = JSON.parse(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+object.answer);
});
First of all. Thank you to everyone who commented on this to help me get started in the right direction. I was able to get what I needed working!! Here is the solution:
<form id="inbound" action="javascript:validateinbound();">
<input type="submit" value="Go!" id="inbound">
<script>
function validateinbound() {
$('#controlpanel:input').each(function () {
var iv = $(this).val();
$('#response').html("");
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
var newdata = JSON.stringify(data);
var response = JSON.parse(newdata);
$('#response').delay(3600).fadeIn(600);
$.each(response, function(array, object) {
$('#response').append("<p>Answer: </p>"+object.answer);
});
}
});
});
});
};
</script>
</form>
I needed to parse the data correctly. So I used JSON.stringify to get the data into a string that JSON.parse could use to manipulate the data. But function(index,object) wouldn't work because my output was not an index, but an array. So when changing to function(array,object) this allowed me to get my data just the way that I needed.
Again thanks to everyone for their help!

How to iterate with javascript a json response from symfony2

i want to itarate a json response from symfony and put it in a table td>
my action :
$search = $this->getDoctrine->...;
$serializer = $this->get('serializer');
foreach ($search as $key => $value) {
$search[$key] = $serializer->serialize($value, "json");
}
$reponse = new JsonResponse($search);
return $reponse;
this is what i have in my twig ( i examine it with Firebug ):
i have a to display at least something but sometimes i have undefined or nothing ... this my javascript function
$(document).ready(function () {
var dataString = $("form").serialize();
var typerequest = $("form").find('input[name="typerequest"]').val();
$('#filtreperseance').ajaxForm({
type: "POST",
url: Routing.generate('myroute'),
data: dataString,
success: function (response) {
$.each(response, function (cle, valeur) {
$("#test").html(valeur);
});
}
});
});
EDIT 1 : Console.log
EDIT 2 :
I'd try to cut down the problem. First make sure, the JSON is valid and looks the way you expect. Don't use jQuery at this point. Call the symfony controller in your browser directly. Then check the json. http://jsonviewer.stack.hu might be of use.
Once you verfified that the JSON itself is valid and contains what you need, we can look at the jQuery part. Then we'd need the code and the errors you get.
i have done a mistake when i returned the JSOn from Controller . its Ok now

javascript, array of string as JSON

I'm having problems with passing two arrays of strings as arguments in JSON format to invoke ASMX Web Service method via jQuery's "POST".
My Web Method is:
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public List<string> CreateCollection(string[] names, string[] lastnames)
{
this.collection = new List<string>();
for (int i = 0; i < names.Length; i++)
{
this.collection.Add(names[i] + " " + lastnames[i]);
}
return this.collection;
}
Now, the js:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: dataS,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
GetJSONData() is my helper method creating two arrays from column in a table. Here's the code:
function GetJSONData() {
//take names
var firstnames = $('#data_table td:nth-child(1)').map(function () {
return $(this).text();
}).get(); //["One","Two","Three"]
//take surnames
var surnames = $('#data_table td:nth-child(2)').map(function () {
return $(this).text();
}).get(); //["Surname1","Surname2","Surname3"]
//create JSON data
var dataToSend = {
names: JSON.stringify(firstnames),
lastnames: JSON.stringify(surnames)
};
return dataToSend;
}
Now, when I try to execude the code by clicking button that invokes CreateArray() I get the error:
ExceptionType: "System.ArgumentException" Message: "Incorrect first
JSON element: names."
I don't know, why is it incorrect? I've ready many posts about it and I don't know why it doesn't work, what's wrong with that dataS?
EDIT:
Here's dataToSend from debugger for
var dataToSend = {
names: firstnames,
lastnames: surnames,
};
as it's been suggested for me to do.
EDIT2:
There's something with those "" and '' as #Vijay Dev mentioned, because when I've tried to pass data as data: "{names:['Jan','Arek'],lastnames:['Karol','Basia']}", it worked.
So, stringify() is not the best choice here, is there any other method that could help me to do it fast?
Try sending like this:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: {names: dataS.firstnames,lastnames: dataS.surnames} ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
This should work..
I think since you are already JSON.stringifying values for dataToSend property, jQuery might be trying to sending it as serialize data. Trying removing JSON.stringify from here:
//create JSON data
var dataToSend = {
names : firstnames,
lastnames : surnames
};
jQuery will stringify the data when this is set dataType: "json".
Good luck, have fun!
Altough, none of the answer was correct, it led me to find the correct way to do this. To make it work, I've made the following change:
//create JSON data
var dataToSend = JSON.stringify({ "names": firstnames, "lastnames": surnames });
So this is the idea proposed by #Oluwafemi, yet he suggested making Users class. Unfortunately, after that, the app wouldn't work in a way it was presented. So I guess if I wanted to pass a custom object I would need to pass it in a different way.
EDIT:
I haven't tried it yet, but I think that if I wanted to pass a custom object like this suggested by #Oluwafemi, I would need to write in a script:
var user1 = {
name: "One",
lastname:"OneOne"
}
and later pass the data as:
data = JSON.stringify({ user: user1 });
and for an array of custom object, by analogy:
data = JSON.stringify({ user: [user1, user2] });
I'll check that one later when I will have an opportunity to.

Arrays are null after passing them with Ajax to the next page

Function:
$("#123").click(function(){
var oberpunkte = new Array();
$('input:checkbox[class=oberpunkte]:checked').each(function() {
oberpunkte.push($(this).attr('name'));
});
var unterpunkte = new Array();
$('input:checkbox[class=unterpunkte]:checked').each(function() {
unterpunkte.push($(this).attr('name'));
});
var kategorie = $("input:radio:checked[name='kategorie']").val();
$.ajax({
TYPE: 'POST',
url: 'selected.php',
data: { oberpunkte:oberpunkte, unterpunkte: unterpunkte, kategorie: kategorie},
success: function (data){
console.log(data);
$('#sumadd').html(data);
}
});
});
});
php:
$oberp = $_POST['oberpunkte'];
$unterp = $_POST['unterpunkte'];
$katid = $_POST['kategorie'];
var_dump($oberp);
var_dump($unterp);
echo($katid);
I also alerted my Arrays before the $.ajax Method. They aren't null.
If I echo the passed Arrays I get the Value null.
I also searched Stackoverflow for similar questions and didn't find a solution which solved my problem.
I bet there is an easy mistake, I just can't figure it out.
MY Div where the output will be:
echo("<div id='sumadd'></div>");
The Output:
NULL NULL
Arrays:
Console.log ->
Object's methods are case sensitive try to change "TYPE" to "type" in $.ajax() method.
Pass data to ajax as arrays:
data: { oberpunkte:[oberpunkte], unterpunkte: [unterpunkte], kategorie: [kategorie]},

jQuery post() with serialize and extra data

I'm trying to find out if it's possible to post serialize() and other data that's outside the form.
Here's what I thought would work, but it only sends 'wordlist' and not the form data.
$.post("page.php",( $('#myForm').serialize(), { 'wordlist': wordlist }));
Does anyone have any ideas?
You can use serializeArray [docs] and add the additional data:
var data = $('#myForm').serializeArray();
data.push({name: 'wordlist', value: wordlist});
$.post("page.php", data);
Try $.param
$.post("page.php",( $('#myForm').serialize()+'&'+$.param({ 'wordlist': wordlist })));
An alternative solution, in case you are needing to do this on an ajax file upload:
var data = new FormData( $('#form')[0] ).append( 'name' , value );
OR even simpler.
$('form').on('submit',function(e){
e.preventDefault();
var data = new FormData( this ).append('name', value );
// ... your ajax code here ...
return false;
});
When you want to add a javascript object to the form data, you can use the following code
var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeArray();
for (var key in data) {
if (data.hasOwnProperty(key)) {
postData.push({name:key, value:data[key]});
}
}
$.post(url, postData, function(){});
Or if you add the method serializeObject(), you can do the following
var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeObject();
$.extend(postData, data);
$.post(url, postData, function(){});
In new version of jquery, could done it via following steps:
get param array via serializeArray()
call push() or similar methods to add additional params to the array,
call $.param(arr) to get serialized string, which could be used as jquery ajax's data param.
Example code:
var paramArr = $("#loginForm").serializeArray();
paramArr.push( {name:'size', value:7} );
$.post("rest/account/login", $.param(paramArr), function(result) {
// ...
}
$.ajax({
type: 'POST',
url: 'test.php',
data:$("#Test-form").serialize(),
dataType:'json',
beforeSend:function(xhr, settings){
settings.data += '&moreinfo=MoreData';
},
success:function(data){
// json response
},
error: function(data) {
// if error occured
}
});
You can use this
var data = $("#myForm").serialize();
data += '&moreinfo='+JSON.stringify(wordlist);
You could have the form contain the additional data as hidden fields which you would set right before sending the AJAX request to the corresponding values.
Another possibility consists into using this little gem to serialize your form into a javascript object (instead of string) and add the missing data:
var data = $('#myForm').serializeObject();
// now add some additional stuff
data['wordlist'] = wordlist;
$.post('/page.php', data);
I like to keep objects as objects and not do any crazy type-shifting. Here's my way
var post_vars = $('#my-form').serializeArray();
$.ajax({
url: '//site.com/script.php',
method: 'POST',
data: post_vars,
complete: function() {
$.ajax({
url: '//site.com/script2.php',
method: 'POST',
data: post_vars.concat({
name: 'EXTRA_VAR',
value: 'WOW THIS WORKS!'
})
});
}
});
if you can't see from above I used the .concat function and passed in an object with the post variable as 'name' and the value as 'value'!
Hope this helps.

Categories

Resources