This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Passing JavaScript Array To PHP Through JQuery $.ajax
Can I pass an array to a php file through JavaScript using AJAX? In my application code
JavaScript builds the parameters based on user input, and then an AJAX call is made to a processing script.
For example, if the processing script url was process_this.php the call made from JavaScript would be process_this.php?handler=some_handler¶m1=p1¶m2=p2¶m3=p3
Could I do something like this?:
process_this.php?handler=some_handler¶m1=[array]
Thanks.
using JQUERY you could do something like this
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var jsarr = new Array('param1', 'param2', 'param3');
$.post("process_this.php", { params: jsarr}, function(data) {
alert(data);
});
});
</script>
php script
<?php print_r($_POST['params']); ?>
output would be
Array ( [0] => param1 [1] => param2 [2] => param3 )
What about sending an JSON Object via Post to your PHP-Script?
Have a look at this PHP JSON Functions
You can use JSON to encode the array to a string, send the string via HTTP request to PHP, and decode it there. You can do it also with objects.
In Javascript you do:
var my_array = [p1, p2, p3];
var my_object = {"param1": p1, "param2": p2, "param3": p3};
var json_array = JSON.stringify(my_array);
var json_object = JSON.stringify(my_object);
var URL = "process_this.php?handler=some_handler" +
"&my_array=" + json_array + "&my_object=" + json_object;
In PHP you do:
$my_array = json_decode($_POST['my_array']));
$my_object = json_decode($_POST['my_object']));
You can send a json object to your php , thats the standard approach
Related
I am trying to pass the values of a Javascript array to a PHP URL through Ajax. Here is script array
<script>"Talent_Percentile.php?"+globalArray"</script>
Where globalArray is my Javascript array. When I alert this, I get
Talent_Percentile.php?eqt_param1=4.00,eqt_param2=4.00,eqt_param3=4.00
I know about string replace but I don't know how to use it on an array. I need an output like
Talent_Percentile.php?eqt_param1=4.00&eqt_param2=4.00&eqt_param3=4.00
Can someone help me?
I'd recommend encoding your array to JSON:
<script>
var url = "Talent_Percentile.php?" + JSON.stringify(globalArray);
</script>
On the server side, use json_decode to decode the data.
var mystring = globalArray.join("&");
var url = "Talent_Percentile.php?" + mystring;
Generally, to apply a function to all elements of an array you should use map:
globalArray = globalArray.map(function(v) {
return v.replace("old", "new");
});
I have an array being passed from php which looks like:
$resultsArr[123]['A']='q';
$resultsArr[123]['B']='d';
$resultsArr[113]['C']='s';
$resultsArr[113]['A']='ss';
$resultsArr[113]['B']='sd';
$resultsArr[111]['C']='sds';
$resultsArr[111]['A']='vv';
$resultsArr[111]['B']='vv';
i need to access certain values frmo this array using jquery.
i am trying to access it like
keyVal = 123; //dynamically generated
var pri = '~$results['keyVal']['B']`'
but i am getting a blank value in variable 'pri'
How can this be solved?
Could you not convert it to a JSON Array and then use it directly in Javascript, rather than picking out individual elements of the array?
<script>
var myArray = <?php echo json_encode($resultsArr); ?>;
</script>
Then use jQuery each to read the array.
This would give you greater flexibility in the long term of what was available to javascript for reading and manipulation.
EDIT
You can read a specific element like so, this will alert "vv":
<script>
var myVar = myArray[111].A;
alert(myVar);
</script>
In php use :
$ResultsArr = json_encode($resultsArr);
$this->jsonResultsArr = $ResultsArr; //its seems u r using smarty.
In javascript
jsonResultsArr = "~$jsonResultsArr`";
requireValue = jsonResultsArr[111].A;
I'm trying to deserialize an array from an URL I've sent from a JQuery Ajax call to a PHP script in the server.
What I have done
I've been sending variables with values to the server successfully with jQuery Ajax this way:
// A simple text from an HTML element:
var price = $("#price option:selected").val();
// Yet another simple text:
var term1 = $('#term1').val();
Then I prepare the data to be sent via Ajax this way:
var data = 'price=' + price + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString
And send it with jQuery Ajax like this:
$.ajax({
url: "script.php",
type: "GET",
data: data,
cache: false,
dataType:'html',
success: function (html) {
// Do something successful
}
});
Then I get it in the server this way:
$price = (isset($_GET['price'])) ? $_GET['price'] : null;
$term1 = (isset($_GET['term1'])) ? $_GET['term1'] : null;
And I'm able to use my variables easily as I need. However, I need to do this with an array.
Main question
Reading a lot, I've managed to learn the professional way to send an array to the server: serialize it! I've learnt this way to do it with jQuery:
var array_selected = [];
// This is used to get all options in a listbox, no problems here:
$('#SelectIt option:not(:selected), #SelectIt option:selected').each(function() {
array_selected.push({ name: $(this).val(), value: $(this).html().substring($(this).html().indexOf(' '))});
});
var array_serialized = jQuery.param(array_selected);
// If I alert this I get my array serialized successfully with in the form of number=string:
//Ex. 123=stringOne&321=StringTwo
This seems to be right. I add this to the data as before:
var data = 'price=' + price + '&' + array_selected + '&term1=' + term1;
//if I alert it, I get this: price=priceString&term1=termString&123=stringOne&321=StringTwo
How do I reconstruct (unserialize) my array in the server? I've tried the same as before:
$array_serialized = (isset($_GET['array_serialized'])) ? $_GET['array_serialized'] : null;
with no success! Any ideas why? How can I get my serialized array passed this way in the server as another array which PHP can handle so I can use it?
Or am I complicating my life myself needlessly? All I want is to send an array to the server.
If you name a variable with [] in the end of it, it will create an array out of the values passed with that name.
For example, http://www.example.com/?data[]=hello&data[]=world&data[]=test, will result in the array $_GET["data"] == array('hello', 'world', 'test'); created in PHP.
In the same way, you can create an associative array in PHP: http://www.example.com/?data[first]=foo&data[second]=bar will result in $_GET["data"] == array("first" => "foo", "second" => "bar");
BTW, you might be interested in using jQuery's .serialize() or .serializeArray(), if those fit your client side serializing needs.
I'm not too knowledgeable with PHP, but I think you may have overlooked something pretty simple, <?--php unserialize($string) ?>.
If I want to send an array from PHP to JavaScript, I do something like this with PHP:
<?php
$json=array();
$json['datetime']="Something";
$json['timestamp']="Something else"
$encoded=json_encode($json);
die($encoded);
?>
And this on jQuery/JavaScript (using Ajax):
...
success: function(response){
var chat = jQuery.parseJSON(response);
datetime=chat['datetime'];
timestamp=chat['timestamp'];
...
I was about wondering about doing the opposite.
In jQuery i have this array:
data_send['username']=$(".chat_username").val();
data_send['message']=$(".chat_message").val();
I want to encode this array as a JSON object, send this object via Ajax, and then take this object from $_POST/$_GET and decode it to an array.
How can I do this?
If you want to encode an array into JSON from Javascript you can use JSON.stringify(myarray).
However, you shouldn't do that to send it to a PHP script.
jQuery has built in support for passing a map of key-value pairs in a POST method - just pass it as the data parameter in $.ajax() or as the second parameter to $.post().
jQuery will then correctly URI encode any unsafe characters that appear (whether in keys, or values), so in your case you can use:
var data_send = {
username: $(".chat_username").val(),
message: $(".chat_message").val()
};
$.post(url, data_send, success_handler);
// or $.ajax({url: url, data: data_send, ... });
PHP then has built in support for reading that map - it's $_POST:
<?php
$username = $_POST['username'];
$message = $_POST['message'];
?>
i am trying to use the Jquery ajax function to call a php page to run a query and return xm the only problem is i dont know how to read the Jquery API page
http://api.jquery.com/jQuery.ajax/
it gives this example
$.ajax({ url: "test.html", context: document.body, success: function(){
$(this).addClass("done");
}});
is there a better example to call a php page to run a sql query and return a json i can encode
See http://api.jquery.com/jQuery.getJSON/ . For example...
The PHP...
<?php
// users.php
$some_users = array(
array('name' => 'Nobby Clark', 'email' => 'nobby#mailinator.com'),
array('name' => 'John Doe', 'email' => 'john#gmail.com'),
);
print json_encode($some_users);
?>
The Javascript...
$.getJSON('users.php', function(data) {
var users = "";
for ( var i = 0; i < data.length; i++ ) {
users += "<p>" + data[i].name + " (" + data[i].email + ") </p>";
}
$('.userlist').html(users);
});
You would just replace the "test.html" with a PHP script that does what you want to do - look up data in a database and return it in JSON.
This is almost a duplicate of a similar question I answered earlier that should explain how to work with PHP and JSON and such, but basically you build an array with the data you want and then run it through json_encode() and output it.
Take a look at this question: jQuery Ajax: Can i store more than one "variable" on success? it has an example of sending json requests with jquery and encoding json at server-side.
If you scroll down that page you will see a bunch of examples that should fill in the blanks for you.
As for the server side stuff, use the PHP file you call to:
Connect to, then query the database for the data you want to return.
Make sure the data you want to return to the client (JavaScript) is in a PHP array.
Output the array using json_encode().
Kill the script.
Something like this:
// Query DB into an array
$data = array(
array('foo' => 'we got this from the DB'),
array('bar' => 'new row')
);
// Output as JSON
print json_encode($data);
die;