If I have a variable that needs to be posted to a PHP script without refreshing the page.
Is this possible? And if so, how?
My attempt using jQuery:
$.ajax({
url: "myphpfile.php",
type: "post",
data: json/array/whatever,
success: function(){ // trigger when request was successfull
window.location.href = 'somewhere'
}
})
How would I receive an array passed in my php script?
Use GM_xmlhttpRequest() to allow for cross-domain posts (which it will be in most scenarios).
Greasemonkey Script:
// ==UserScript==
// #name _Sending arbitrary data, demo
// #include http://YOUR_SERVER.COM/YOUR_PATH/*
// #grant GM_xmlhttpRequest
// ==/UserScript==
var someArray = [1, 2, 3];
var serializedData = JSON.stringify (someArray);
GM_xmlhttpRequest ( {
method: "POST",
url: "http://SERVER.COM/PATH/ShowJSON_PostedData.php",
data: serializedData,
headers: {"Content-Type": "application/json"},
onload: function (response) {
console.log (response.responseText);
}
} );
ShowJSON_PostedData.php:
<?php
echo '<title>JSON data</title>';
echo '<h2>JSON post data:</h2><pre>';
$jsonData = json_decode($HTTP_RAW_POST_DATA);
print_r ($jsonData);
echo '</pre>';
?>
The console. will show:
<title>JSON data</title><h2>JSON post data:</h2><pre>Array
(
[0] => 1
[1] => 2
[2] => 3
)
</pre>
The accepted answer of this thread may be really useful since it shows a simple case : using jquery $.ajax to call a PHP function
My suggestion is : make something that works, then progressively add complexity until you reach your custom case. This way you feel much safer and you are aware of potential problems as they get in.
To pass an array from php to the client side, you may use echo json_encode($myArray); in your php script.
Hope this helps
Related
I'm pretty unfamiliar with JSON, as I haven't used it too much and I'm trying to learn some of it.
So I have an ajax request that gives me this: [{"palvelu_id":"1","palvelu_nimi":"Meikkikoulutus","palvelu_kuvaus":"Kuvaus","palvelu_hinta":"10"}]
And I'm trying to use jQuery.parseJSON to use it on a page.
var palveluData = $.parseJSON(d);
$("#ajanvarausInfo").html(palveluData.palvelu_kuvaus+"<br>"+palveluData.palvelu_hinta);
But I get undefined as answer, what am I doing wrong here?
You should get the first element of the array:
$("#ajanvarausInfo").html(palveluData[0].palvelu_kuvaus+"<br>...");
If the array has more than 1 element you should iterate through the array, you can use jQuery $.each() utility function.
EDIT::
Wow, looks like ive kept the window open for to long before replying -.-
You have an outter array there, so you need to take that into account ( your php side might be not correct )
$("#ajanvarausInfo").html(palveluData[0].palvelu_kuvaus+"<br>"+palveluData[0].palvelu_hinta);
Usually you not need that when properly setting everything up
$.ajax ({
url: 'myurl',
type: 'POST',
data: { key_value pairs here },
dataType: 'json',
success: function(response){
$("#ajanvarausInfo").html(response.palvelu_kuvaus+"<br>"+response.palvelu_hinta);
});
});
On the php side
$response = array(
"palvelu_id" => "1",
"palvelu_nimi" => "Meikkikoulutus",
"palvelu_kuvaus" => "Kuvaus",
"palvelu_hinta" => "10"
);
echo json_encode($response);
I want to manipulate a PHParray in javascript. This is the code i'm using.
Array.php
<?php
$sentido[1]="ver";
$sentido[2]="tocar";
$sentido[3]="oir";
$sentido[4]="gustar";
$sentido[5]="oler";
?>
fx_funciones.js
/*Pre-sentences*/
var js_array=new Array();
$.ajax({
type: "POST",
url: "array.php",
success: function(response) {
js_array=response
}
});
This is what I want to do but it's not working.
I think , the answer for above question is already addressed in below link. please check them out.
Get data from php array - AJAX - jQuery
I hope it will help you
Try this:
<?php
$sentido[1]="ver";
$sentido[2]="tocar";
$sentido[3]="oir";
$sentido[4]="gustar";
$sentido[5]="oler";
echo json_encode($sentido);
And:
$.getJSON('array.php', function(sentido) {
console.log(sentido);
});
You'll need to return the array from your PHP code as JSON, using the json_encode function. Then, in your jQuery code, specify a json dataType so that it's implicitly converted and passed to the callback function as an array:
var js_array=new Array();
$.ajax({
type: "POST",
url: "array.php",
success: function(response) {
js_array=response
},
dataType: 'json'
});
Use the standard JSON notation. It serializes objects and arrays. Then print it, fetch it on the client and parse it.
On the server:
echo json_encode($sentido);
For more on PHP's json_encode: http://php.net/manual/de/function.json-encode.php
On the client, this is specially easy if you use the jQuery function for ajax that expect JSON-encoded objects, and parses them for you:
$.getJSON('address/to/your/php/file.php', function(sentidos) {
alert(sentidos[0]); // It will alert "ver"
alert(sentidos[1]); // It will alert "tocar"
});
It uses GET but this most probably what you need.
For more on jQuery's $.getJSON: http://api.jquery.com/jQuery.getJSON/
Ok seriously struggling here. I am having some problems trying to send a multdimensional array to PHP via ajax. Here's what I have been trying:
To simplify rather than copy paste a wall of code:
peoplearray[0] = [name] => 'john'
[age] => '28'
[sex] => 'Male'
peoplearray[1] = [name] => 'julie'
[age] => '20'
[sex] => 'Female'
main_array['item'] = 'x';
main_array['something'] = 'x';
main_array['another'] = 'x';
I want to get this to php via post. I figured I may aswell just join them together as I am multidimensional anyway thus :
main_array['peoplearray'] = peoplearray;
now to do the ajax:
// var data = JSON.stringify(main_array);
var send = $.ajax({
type: "POST",
cache: false,
url: "theurl",
data: {data:main_array} //I do change this `main_array` when using the above stringify!
});
send.done(function(msg) {
console.log(msg);
})
in PHP I am just doing the following right now:
$data= $_POST['data'];
print_r($data);
in firebug: (an empty string)
when I have the var data = JSON.stringify(main_array); uncommented I get the following: [][
if i add $data = json_decode($_POST['data']); to the php I get:
Array ( )
Basically the main_array I realise does not need to be an array and so I can get that stuff across no problem but what I need to do is get the peoplearray over so that I can do some foreach etc... with it in php. Any help would be much appreciated I am sure I am just being stupid!
EDIT: The reasoning behind this is that peoplearray could have 0 or 100 entries so I just need to get it to php so I can foreach it to do the DB inputs. If there is a better approach I would be very grateful to hear it as I am still pretty new to this.
EDIT: Thanks to Nicola's answer everything is passing fine except the important part which is mainarry.peoplearray - it is not appearing in the the return console.log and I cant access it in PHP. Any solutions on this or do I have to put the foreach intelligence in the javascript and just send everything individually?
First of all main_array is not an array but an object because in javascript there are no associative arrays and for this reason
main_array['peoplearray'] = peoplearray;
is equivalent to
main_array.peoplearray = peoplearray;
and you should declare main_array like this
var main_array = {};
then try to change your function like this:
var send = $.ajax({
type: "POST",
dataType: "json",
cache: false,
url: "theurl",
data: {data:main_array}
});
and server side
header('Content-type: application/json');
$data= $_POST['data'];
echo json_encode($data);
I got it to work by keeping the peoplearray seperate.
So I did as Nicola said and created mainarray as an object ie. declaring with curlies: {}
The peoplearray I left as an array ie declaring with [], however then name,age&sex fields I created as an object ie. {} and then .push() them into the the peoplearray.
Then the ajax looked as follows:
var send = $.ajax({
type: "POST",
dataType: "json",
cache: false,
url: "theurl",
data: {data:main_array, people:peoplearray}
});
then with the PHP everything is available in the $_POST, and if you
echo json_encode($people); //or whatever var name it is stored as in the php
the objects ie name,age,sex properties are shown in the
send.done(function(msg) {
console.log(msg);
})
I have the following object that gets created in my javascript application.
poll_data[active_question] = {
'question': $('div.question_wrap textarea').attr('value'),
'answers': [
$('div.answer_wrap input#0').attr('value'),
$('div.answer_wrap input#1').attr('value'),
$('div.answer_wrap input#2').attr('value'),
$('div.answer_wrap input#3').attr('value'),
$('div.answer_wrap input#4').attr('value'),
$('div.answer_wrap input#5').attr('value')
]
};
active_question is set to 'poll', 0, 1, 2, 3, 4, or 5 depending on the question being worked on at the moment. I am trying to post this object to a php script using the following JS code.
$.ajax({
url: '/somewebsite/poll/create?json=show',
type: 'POST',
// dataType: 'json',
data: poll_data,
contentType: 'application/json; charset=utf-8',
success: function(data) {
alert(data);
}
});
My PHP code is very simple.
echo json_encode($_POST); exit;
When I run the script and click the button that triggers the submission of the data, I receive the alert (so the actual ajax code works), but the result from my PHP script is just an empty array. I think that this is an issue with the way the object is constructed, but I am not sure, and have not been able to find a work around.
Thanks in advance.
Okay, a few things:
poll_data is not a valid JSON object. You would have to use poll_data[active_question], which IS a valid JSON object. jQuery should serialize this correctly. Remove the contentType -- I am pretty sure that is for php (not positive) but your code wouldn't work for me until I removed it. Finally, the appending of json=show to the query string doesn't do anything..it will just be ignored.
A couple minor things too: you can use .val() instead of .attr('value'), and have you looked into .serialize() to create your post data for you?
do this on server
$data;
$data->question=$_POST['question']
$data->answer=$_POST['answers']
echo json_encode($data);
do this for ajax request
$.ajax({
url: '/somewebsite/poll/create?json=show',
type:'POST',
//modified data proprty
data:poll_data[active_question],
success: function(data) {
alert(data);
}
});
If someone could assist me please. I'm doing a jquery Ajax post, for some reason the Json object isn't working so just returning a php array instead
$.post
(
"classes/RegisterUser.php",
$("#frmRegistration").serialize(),
function(data)
{
alert(data);
}
);
The data is returned to Javascript 100% as
array
(
[key]=>value
[Name] => SomeOneName
[Surname] => SomeOneSurName
)
How would i go about getting the value of Surname in Javascript?
Thanks for your assistance?
Regards
Expanding on The MYYN's answer, after you get your script to return JSON, you must specify that you're receiving JSON and act accordingly. You can do this with .ajax():
$.ajax({
type: 'post',
url: 'classes/RegisterUser.php',
data: $("#frmRegistration").serialize(),
dataType: 'json',
success: function(obj) {
// This alerts SomeOneSurName
alert(obj.Surname);
}
});
Maybe your PHP script should return json (right now it seem to return something like var_dump($some_ary);. A proper way to do this is via php's json_encode.