Error to pass to PHP Papa Parse object using AJAX - javascript

I would like to extract a CSV local file in PHP using AJAX.
To do that I tried to use Papa Parse and it works great. The problem is to pass the results with AJAX. I tried with JSON.stringify, I tried to pass only the first field; I tried also to create a JSON object and then add the results to this object but, I don't know why, when I extract in PHP I got only the values of the original object.
values = {};
values['row_1'] = 'value1';
values['row_2'] = 'value2';
i = 3
$("input[type=file]").parse({
config: {
delimiter: ",",
step: function(results) {
value = results.data[0]
values['row_' + i] = value
i = i + 1
}
}
});
$.ajax({
type: "POST",
url: "extract-csv.php",
data: {
id: $('#id').val(),
...
values: values
}
...
})
With this code on PHP I returned only "value1" and "value2" (if I print "values" in the console I get object with 2++ elements)

Papa Parse worked after Ajax, so the solution is to put the Ajax call in the "Complete" Papa Parse function and then everything works fine!

Related

Unable to loop through JSON reponse in JQuery with .each method

I'm unable to extract object properties using the . each() method in Jquery. I'm able to view the full response with console.log (result), but I'm unable to extract from that response. I receive an undefined or [Object object] message when I attempt to use result.snippet in the .each method. When I use the .each for other json responses I'm able to extract by using data.value, but for this response it doesn't work.
(function getArticles(){
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key': "",
'q': "obama"
});
$.ajax({
url: url,
type:"GET",
data:{
}
}).done(function(result) {
console.log(result);
$.each(result, function () {
document.write(result.snippet); // This is not working, but works with other json responses from other API's//
})
});
})();
The response you're getting is an object, not an array. You can't iterate over an object. You can iterate over the keys of an object and then reference each key. In either case, you don't need jQuery to do the iteration.
var response = {
"hello": "world",
"foo": "bar"
};
for (var key in response) {
console.log(key, response[key]);
}
In your case, to get to the snippet:
response.docs[0].snippet
You could iterate each document:
response.docs.forEach(function(doc) {
console.log(doc.snippet);
});

JQuery: parsing ajax call versus imbedded str

I am confused because I have two functions, one using ajax to get the data and the other getting it from a string.
function loadMenuData() {
$.ajax({
url: "./shoulders.json",
success: function(data) {
dataObj = $.parseJSON(data);
$.each(dataObj, function( key, value) {
$(document).find("#dropDownDest").append($('<option></option>').val(value.id).html(value.name));
});
}
});
}
function loadMenuDataX() {
var str = '[{"id":"A","name":"Bart"},{"id":"B", "name":"Joe"},{"id":"C", "name":"Gomer"}]';
dataObj = $.parseJSON(str);
$.each(dataObj, function( key, value) {
$(document).find("#dropDownDest").append($('<option></option>').val(value.id).html(value.name));
});
}
I created the file shoulders.json buy pasting the str between the single quotes ' into the file. If I call loadMenuX, it fills in the <select></select> correctly. If I call loadMenu, it doesn't fill anything in.
I have tried JSON.parse instead of the above and get the same behavior.
I was unable to use $("#dropDownDest") and had to use $(document).find. Why?
Hitting the DOM each loop seems to be excessive. What would be a better way to do the ajax version THAT WOULD WORK and be better?
What would be a better way to do the ajax version THAT WOULD WORK and be better?
Because you're trying to get JSON file the better way is using jQuery.getJSON(), so you will be sure that the returned result is in json format :
$.getJSON( "./shoulders.json", function( json ) {
$.each(json, function( key, value) {
$("#dropDownDest").append('<option value="+value.id+">'+value.name+'</option>');
});
});
Hope this helps.

Ajax array only returns 1 value?

I am new to PHP and Ajax so please bear with me. I've searched around and found some answers but still am having trouble. I have an array of check box input values. If a user checks an item it is added to my array list. An example would be:
listOfPrograms = [chrome, firefox, sqlworkbench]
I want to send this array list to a PHP script on my server. My current Ajax script is as follows:
function ajaxPostToPhp(listOfPorgrams)
{
$.ajax
({
url: 'script.php',
type: 'post',
data: ("listOfPrograms" : listOfPrograms), // I believe this is where my issues lies as I do not know exactly that this is doing. I have read the PHP documentation. I tried converting to JSON and kept getting a 500 error.
success: function(data)
{
console.log(data);
}
});
}
My PHP script is as folllows:
$myArray = $_Request['listOfPrograms'];
echo $myArray;
This returns only 1 item from the array. I tried setting myArray = [] but I get an undefined index.
Thanks for your help! Sorry for such a noob question.
You need to fix a few things:
1- Javascript array:
var listOfPrograms = ['chrome', 'firefox', 'sqlworkbench'];
2- Ajax Data:
function ajaxPostToPhp(listOfPrograms)
{
myListData = {};
myListData['Programs'] = listOfPrograms;
$.ajax({
url: 'script.php',
type: 'post',
data: myListData,
success: function(data)
{
console.log(data);
}
});
}
3- Php Code:
$myArray = $_POST['Programs'];
var_dump($myArray);
You are passing an array as post parameter but they can only be strings. You should convert the array to a JSON string first. An easy function for that purpose is JSON.stringify()
var listOfPrograms = ["chrome", "firefox", "sqlworkbench"]
// I guess you need strings here
function ajaxPostToPhp(listOfPorgrams) {
$.ajax ({
url: 'script.php',
type: 'post',
// Convert listOfPrograms to a string first
data: ("listOfPrograms" : JSON.stringify(listOfPrograms)),
success: function(data) {
console.log(data);
}
});
}
jquery will kindly turn array values in ajax post data to an array for you. the issue is that in php you can't just echo an array. as a commenter stated, your php file needs to look like
$myArray = $_Request['listOfPrograms'];
echo json_encode($myArray);
also you should consider using $_POST over $_REQUEST

jQuery weird JSON behaviour

I'm getting a array of the selected checkboxes and push them into an array.
After that I JSON.stringify() the array and send it to my PHP script.
But the weird thing is that when I send the array variable, it returns strange things.
Here is the code:
var _items = new Array();
$('input:checkbox:checked.item').each(function () {
_items.push($(this).val());
});
$.ajax({
type: 'POST',
url: btn.data('url'),
data: {_token: token, items: JSON.stringify(_items)},
dataType: 'json',
success: function () {
//
}
})
When I console log the `_items variable I get a array back with the selected boxes like this:
["3", "4"]
In my PHP I do:
dd(json_decode(Input::get('items')));
But the strange thing is the _items variable returns an array of this in my PHP script:
0: 2
1: 0
2: 3
3: 1
4: 1
5: 4
6: 1
When I manually created the _items variable like so: var _items = ["3", "4"];
It does return the correct array..
EDIT: When I try to send it as a array it will return the same result as the strange thing above..
EDIT2: The code where I print the PHP array with. I catch the route with laravel (this is working as it should) and then I die and dump (dd) the input. Same as $_POST['items']:
Route::post('user/destroy/multiple', function () {
dd(json_decode(Input::get('items')));
});
EDIT3: Strange things is when I output Input::get('items') it does return a JSON string, but for some reason I just can't json_decode it..
What can be wrong with the code...?
From http://laravel.com/docs/4.2/requests:
Note: Some JavaScript libraries such as Backbone may send input to the
application as JSON. You may access this data via Input::get like
normal.
So in your JavaScript you should do the following:
$.ajax({
type: 'POST',
url: btn.data('url'),
data: {_token: token, items: _items},
dataType: 'json',
success: function () {
//
}
})
And in PHP you should do:
Route::post('user/destroy/multiple', function () {
dd(Input::get('items'));
});
The problem is that you are encoding the array to Json in your javascript code, you don't have to do that, just send the array itself, the Ajax call will encode it for you. By doing that you are encoding twice the array to Json ! Replace data: {_token: token, items: JSON.stringify(_items)} by data: {_token: token, items: _items},
You want to serialize object, not array
Change your code:
var _items = {};
and something like this
$('input:checkbox:checked.item').each(function (i,v) {
_items[i] = v;
});

Passing a javascript array to a php page using post method

I want to pass a javascript array to a php page using ajax POST request .How to achieve this.please help..Thanks in advance
Have a look into JSON encoding.
In PHP you can decode it using json_decode, not quite sure how you'll encode it in Javascript but it is possible
http://en.wikipedia.org/wiki/JSON
using jQuery
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
Edit
if you are creating ajax object and using it then I'll suggest to convert your data in query string send it through ajax object.
like :
var userdetails = [1,2,3,4];
var queryString = "";
for(i=0; i<userdetails.length; i++){
queryString = queryString + 'userdetails[]='+userdetails[i]+'&';
}
connect.send(queryString)
example posting with json
var array = [1,2,3,4,5,6];
$.ajax({
url: "mydomain.com/url",
type: "POST",
dataType: "json",
data: {arrayName: array},
complete: function() {
//called when complete
},
success: function() {
//called when successful
},
error: function() {
//called when there is an error
},
});
Then the json could be parsed server side.
arrays can also be sent using application/x-www-form-urlencoded - this is the default format for submitting.

Categories