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");
});
Related
I am trying to pass an array into a GET URL BUT it is coming as add_cart?ids=1,2,3,4,5 as opposed to sending it properly.
This is my jquery code where it adds the array to the URL and directs the user to the next page:
$(document).on("click", 'button.btn_checkout', function(){
var cart = <?php echo json_encode($carts); ?>;
window.location.href = "addcart.php?cart=" + cart;
});
And then on the addcart.php page I am unable to get these values.
Ideally on this page, I want the values in the form 1,2,3,4,5
This is the code for that page:
<?php
session_start();
$cart = isset($_GET['cart']) ? $_GET['cart'] : "";
$cart = explode(",", $_GET['cart']);
for($i = 0; $i<$cart.size; $i++){
echo $cart[$i];
}
?>
Where am I going wrong?
You are using the jQuery GET request a little wrongly. You will use
window.location.href
when you are trying to change the location of your current webpage.
Try this instead:
$(document).on("click", 'button.btn_checkout', function(){
var result = <?php echo json_encode($carts); ?>;
$.get( "addcart.php", { cart: result } );
});
I'm assuming by ARRAY you mean to include the braces {}?
If so, your problem is actually the php part. json_encode is creating a proper json object. Which then is being added onto the url AS the object itself, and NOT a string. You actually want it to be a string.
this line: var cart = <?php echo json_encode($carts); ?>; is the main issue.
convert it to something like: var cart = "<?php echo json_encode($carts); ?>";
Use $.param() function to convert params to get query string.
You are directly initialising Json to param but not converting to query string.
Above function will convert Json to query string
Try to use the javascript function JSON.stringify() to convert to json.
Note: Don't sent long data over a URL. There is a limit for sending data via url and it will end up in a corrupted data if exceeded the limit. For large data, use POST method.
Greetings Stackoverflow
How do I set the php $_GET[] array from Jquery? I have a string looking simmilar to this: $sample_string = "Hi there, this text contains space and the character: &";. I also have a variable containing the name of the destination: $saveAs = "SomeVariable";. In PHP it would look following: $_GET["$SomeVariable"] = $sample_string;.
How do I do this in Jquery?
Thanks in advance, Rasmus
If you're using jQuery, you'll have to set up an AJAX request on the client side that sends a GET request to the server. You can then pull the data you supplied in the request from the $_GET[] array on the server side.
$(function() {
var data = {
sample_string: "hi",
saveAs: "something"
};
$.get('/path/to/script.php', data, function(response) {
alert(response); // should alert "some response"
});
});
And in script.php:
<?php
$sample = $_GET['sample_string']; // == "hi"
$saveAs = $_GET['saveAs']; // == "something"
// do work
echo "some response";
?>
Can't tell if you're looking to grab a GET param from javascript or set a GET param from jQuery. If it's the former, I like to use this code (stolen a while back from I can't remember where):
var urlParams = {};
(function () {
var match,
pl = /\+/g, // Regex for replacing addition symbol with a space
search = /([^&=]+)=?([^&]*)/g,
decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); },
query = window.location.search.substring(1);
while (match = search.exec(query))
urlParams[decode(match[1])] = decode(match[2]);
})();
Then you can call
var cake = urlParams['cake'];
To get the $_GET param specified by http://someurl.com?cake=delicious
If you want to send a $_GET parameter, you can use either jQuery's $.get() or $.ajax() functions. The $.get function is more straightforward and there's documentation on it here http://api.jquery.com/jQuery.get/
For $.ajax you would do something like this:
var trickystring = "Hi there, this text contains space and the character: &";
$.ajax({
url:'path/to/your/php/script.php',
data: {
'getParam1':trickystring,
'getParam2':'pie!'
},
type:'GET'
});
Now in PHP you should be able to get these by:
$trickystring = $_GET['getParam1'];
$pie = $_GET['getParam2'];
Hope these examples GET what you're looking for. (Get it?)
if $sample_string is what you want in jquery, you can do
var sample_str = '<?php echo $sample_string; ?>'; and then use the js variable sample_str wherever you want.
Now, if you want to do set $_GET in jquery, an ajax function would be way to go.
$.ajax({
url:'path/to/your/php_script.php',
data: {
'param1': 'pqr',
'param2': 'abc'
},
type:'GET'
});
Do you mean that would look like $_GET[$saveAs] = $sample_string y think.
$_GET is a variable for sending information from a page to another by URL. Its nosense to do it in jQuery that is not server side. If you want to dynamically set the $_GET variable to send it to another page you must include it in the URL like:
/index.php?'+javascriptVariable_name+'='+javascriptVariable_value+';
$_GET is just a URL parameter. So you can access get like /index.php?id=1:
echo $_GET['id'];
Look at this article, it shows all the ways to load stuff with ajax:
http://net.tutsplus.com/tutorials/javascript-ajax/5-ways-to-make-ajax-calls-with-jquery/
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 communicate AJAX, JSON to PHP and then PHP returns some data and I'm trying to parse it with Javascrpt.
From the php, server I return,
echo json_encode($data);
// it outputs ["123","something","and more something"]
and then in client-side,
success : function(data){
//I want the data as following
// data[0] = 123
// data[1] = something
// data[3] = and more something
}
But, it gives as;
data[0] = [
data[1] = "
data[2] = 1
It is reading each character but I want strings from the array, not individual characters. What is happening here? Thanks in advance, I am new to Javascript and JSON, AJAX.
JSON.parse(data) should do the trick.
Set the dataType property of the ajax call to json. Then jQuery will automatically convert your response to object representation.
$.ajax({
url : ...,
data : ...,
dataType : "json",
success : function(json) {
console.log(json);
}
});
Another option is to set headers in PHP so that JQuery understand that you send a JSON object.
header("Content-Type: application/json");
echo json_encode($data);
Check this one... Should Work
success : function(data){
var result = data;
result=result.replace("[","");
result=result.replace("]","");
var arr = new Array();
arr=result.split(",")
alert(arr[0]); //123
alert(arr[1]); //something
alert(arr[2]); //......
}
You did not shown function in which you parse data. But you shoud use
JSON.parse
and if broser does not support JSON then use json polyfill from https://github.com/douglascrockford/JSON-js
dataArray = JSON.parse(dataFomXHR);
I'm not sure if this is what you want but why don't you want php to return it in this format:
{'item1':'123','item2':'something','item3':'and more something'}
Well to achieve this, you'll need to make sure the array you json_encode() is associative.
It should be in the form below
array("item1"=>123,"item2"=>"something","item3"=>"more something");
You could even go ahead to do a stripslashes() in the event that some of the values in the array could be URLs
You could then do a JSON.parse() on the JSON string and access the values
Hop this helps!
hello frieds this is how i usually post a variable using Jquery..
$.post("include/save_legatee.inc.php", { legatee_name: legatee_name_string,
legatee_relationship:legatee_relationship_string,
}, function(response){
alert(response);
});
Can anybody explain how to post an array using Jquery..
var all_legattee_list= new Array();
all_legattee_list[1]="mohit";
all_legattee_list[2]="jain";
this is my array... How can post this using jquery???
$.post(
'include/save_legatee.inc.php',
{ all_legattee_list: ['mohit', 'jain'] },
function(data) {
}
);
Post this as a string separated with some delimiter.
use .join() to join the array
var strJoinedArray = all_legattee_list.join(',');
and in your php code split the string using , and retrieve the values.
you have to use all_legattee_list[] as name of your parameter, something like this:
$.post("...", "all_legattee_list[]=mohit&all_legattee_list[]=jain", ...);
For example, like this: Serializing to JSON in jQuery. Of course the server would have to support JSON deserialization, but many server-side languages already do.