sending javascript array to external php file using POST - php

I am trying to send a javascript array to an external php page, but the only thing the php page is picking up is the fact that I am sending array, not the actual data within the array.
javascript -
var newArray = [1, 2, 3, 4, 5];
$.ajax({
type: 'POST',
url: 'array.php',
data: {'something': newArray},
success: function(){
alert("sent");
}
});
External PHP Page -
<?php
echo($_POST['something']));
?>
I know this question has been asked before, but for some reason, this isn't working for me. I have spent the last couple days trying to figure this out as well. Can someone please point me in the right direction.
current output (from php page) -
Array (thats all the page outputs)

You should use var_dump in stead of echo.
Echo is only for strings, integers, floats and it will print 1 if a boolean is TRUE, and Array for an array.

You could also use print_r() which is a little more readable.

Y don't you convert array into string with some special character as separator and explode it into php?

Related

Is possible this json output as array in jquery?

I have a php file wich searches in a DB, then builds and array with results and it ends and shows the result like this:
{"1":"1","2":"2","15":"15","25":"25"}
That means in position 0 there is no result, position 1 has value 1, and so on. (as far as I /know this result is a valid json output)
In jquery side I have this
$.ajax({
type: 'POST',
url: 'diahoracierre.php',
dataType: 'json',
cache: false,
success: function(result) {
alert(result);
},
});
What I need is to "parse" result to an array and be able to play which the content using index of array, like
alert(result[X]);
on result[1] it shows 1, any other attempt shows undefined and there are at least 4 results.
You have two options either you loop through result and create an array by yourself(a tedious task) or you access elements like below, please note quotes around index is required as here though we are saying index but in reality we are looking for key name.
result["index"]
e.g.
result["5"]
Also I tried your jsFiddle and it worked:
var json = '{"0":"-1","1":"1","2":"2","15":"15","3":"-1","25":"25","4":"-1","5":"-1","6":"-1","7":"-1","8":"-","9":"-1","10":"-1","11":"-1","12":"-1","13":"-1","14":"-1","16":"-1","17":"-1","18":"-1","19":"-1","20":"-1","21":"-1","22":"-1","23":"-1","24":"-1","26":"-1"}';
json = JSON.parse(json);
alert(json["25"]);
Since you've used dataType: 'json'. Then it's no longer require you to parse the json result.
Also note that your parameter is named result in success function.So you can use:
alert(result[1]);
instead of:
alert(myArray[1]);

Split an array within an array (Mysql, PHP and Ajax)

I have a database with 5 columns and multiple rows. I'm using PHP to fetch the data and echo it as JSON as an array. The way it echoes it is the data in each row is an array and the rows themselves are an array (array within an array).
Now I bring the data in using Ajax and want to split the array within an array. I can only split down the rows so far. How would I split further?
Here's the PHP:
//==== FETCH DATA
$result = mysql_query("SELECT * FROM $tableName");
//==== PUT DATA INTO ARRAY
$array = array();
while ($row = mysql_fetch_row($result)) {
$array[] = $row;
}
//==== ECHO AS JSON
echo json_encode($array);
Here's the Ajax:
$.ajax({
url: 'assets/php/results.php',
data: "",
dataType: 'json',
success: function(data){
//==== FETCH DATA FIELDS
var row1 = data[0];
var row2 = data[1];
//==== UPDATE HTML WITH DATA
$('#r-col span.row1').html(row1);
$('#r-col span.row2').html(row2);
}
});
To answer your question, let me give you a few tips on how you can achieve this in shorter steps.
First off, try using msqli_ functions instead of msql_ (in php) it has a better handling of security among other improvements, and are also the functions w3schools recommend using.
There is a function called mysqli_fetch_array() that will do exactly what you are doing with your for loop in a single command.
And to answer your question on the json, you should take a look at what a json really looks like:
var data = {"menu": {
"id": "file",
"value": "File123",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
Json objects are not arrays, they are objects. That means I can access the information like this:
data.menu.id //Which is equal to "file"<br>
or
data[0][0] //which is also equal to "file"<br>
or a combination
data[0].value //is equal to "File123"
A great way to understand the way this objects work is by using the interactive console in Chrome. It has a pretty easy to understand printing of objects. I would also advice you to read some about object oriented programming on javascript.
In a nutshell: Json objects are not arrays, but you can sort through them easily by appending . or []
A small note: Try to avoid using Select * in your statements, they take a lot of resources, just call the fields you need by name.
Also, msql_ functions are a bit deprecated right now, try using msqli_ functions instead, they have several upgrades in the security side, you can check w3schools.com for examples.
Finally, there is a function in php called msqli_fetch_array that does exactly what you're trying to do with your for loop, it will convert your query output to an array.
Happy Coding.

Pass array as an argumento from jQuery to a php handler using $.get and $.param()

I need to pass an array of numeric values from jQuery to a php file. I fill this array in my code using the following line:
Area_Array.push({name: 'A[]', value: ui.value});
Then I serialize the array to use it in an URL
$.param(Area_Array);
I can see that the array is built correctly using:
alert(decodeURIComponent($.param(Area_Array)));
which returns, for instance, the following:
A[]=0&A[]=1&A[]=2
that is fine for me, but I don't know now how to insert it inside my $.get which is also sending another parameters:
$.get("some.php", { b1 : 0, b2 : 5, b3: 20, b4 : 1},function(foo){});
But I want my built URL to have the following structure:
http://somehost/some.php?b1=0&b2=5&b3=20&b4=1&A[]=0&A[]=1&A[]=2
Could you please help me?
Thank you!!! :)
Alexandra
I suggest that you directly add the values to the array
Area_Array.push(ui.value);
and then set it as parameter:
$.get("some.php", {b1: 0, b2: 5, b3: 20, b4: 1, A: Area_Array},...);
There is no need to call $.param directly. E.g. the setup above would generate this query string (if Area_Array was [1, 2, 3]):
b1=0&b2=5&b3=20&b4=1&A[]=1&A[]=2&A[]=3
jQuery takes care of encoding arrays correctly.

PHP Array to jQuery array with JSON. ($.post, parseJSON, json_encode)

I am trying to get a php file setup to return the results of a MySQL database query from a jQuery AJAX call. The returned results will be an array. I have a very basic start where I am just getting some basic data back and forth to and from the php file, but am stuck with some basic syntax issues:
The PHP code:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
The jQuery code:
$.post("dbFile.php", str, function(theResponse){
alert('the response: ' + theResponse);
var obj = $.parseJSON(theResponse);
alert(obj.a);
I can print out obj.a, obj.b, obj.c... no problem. The problem is I will be incrementing a counter as I increment through the MySQL results. So, the array does not use letters, it uses numbers:
$arr[$i] = mysqlresults ... $i++;
So, in the JavaScript/jQuery I have an object (not an array). I can print out obj.a for example, but I can not print out obj.2 (for example). In other words, if I replace the letters with numbers in the php array, I don't know how to print them out in JavaScript/jQuery. Can I change the object that parseJSON returns into an array somehow (so that I can cycle through it)?
Use the array access syntax:
alert(obj[42]);
You can use:
alert(obj['a']);
See this question for more info.

Getting array to .ajax on success

I'm trying to return data as an array to my .ajax function on success so I can do do multiple things, but I can't get to work for anything except a single value. Like return $foo. But when I return $array, the page never loads up.
JavaScript's use & utilizing of array is different as compared to PHP's processing. So, either you need to send the data to your AJAX function as a JSON (JavaScript Object Notation), otherwise you need to send the data as a string with a common separator to your AJAX function.
In the latter case, you will need to split up the Response Text in your AJAX function, with that common separator, to make up a JS Array. Then it will be very much easy to use that array instead.
Hope it helps.
You would have to serialize your data into a string. My preference is JSON, so if your PHP version is >= 5.2.0, you'll most likely have access to a json_encode function. This will turn the PHP object into a JSON string. If you don't have access to json_encode, you can use the PECL JSON package.
Looking at the way you reference your ".ajax" function, I am assuming jQuery. So as long as you set the content type to 'json', the JSON response will result in a native JavaScript object. For example,
PHP,
return json_encode(array(1, 2, 3));
JavaScript,
$.ajax({
...
contentType: 'json',
success: function(response) {
for (var i = 0; i < response.length; i++) {
alert(response[i]);
}
});
This code should proceed to alert 1, 2, and then 3.
I haven't verified the code, but the essential parts are all there. A note to have though, a normal indexed array is turned into a JavaScript list while an associative array will be turned into a JavaScript object.
JSON is a good option to send your data array from PHP to Javascript. In PHP side just encode and return your data array as JSON string and in the Javascript side decode that JSON string and use as normal array.
Suppose your data array is like $array, in your PHP code just encode that array using json_encode($array) and return the resulted JSON string.
In your javascript code decode that JSON string using 'eval' function in the success callback function like:
$.ajax({
type: "GET",
url: "test.php",
success: function(data) {
var dataArray = eval('(' + data + ')');
}
});
I think this will help you ...
Siva

Categories