I want to send an array constructed in javascript with the selected values of a multiple select. Is there a way to send this array to a php script using ajax?
You might do that with $.post method of jQuery (for example) :
var myJavascriptArray = new Array('jj', 'kk', 'oo');
$.post('urltocallinajax', {'myphpvariable[]': myJavascriptArray }, function(data){
// do something with received data!
});
Php will receive an array which will be name myphpvariable and it will contain the myJavascriptArray values.
Is it that ?
You can post back to your server with XML or JSON. Your javascript will have to construct the post, which in the case of XML would require you to create it in javascript. JSON is not only lighterweight but easier to make in javascript. Check out JSON-PHP for parsing JSON.
You might want to take a look at Creating JSON Data in PHP
IIRC, if PHP sees a query string that looks like http://blah.com/test.php?var[]=foo&var[]=bar&var[]=baz, it will automatically make an array called $var that contains foo, bar and baz. I think you can even specify the array index in the square brackets of the query string and it will stick the value in that index. You may need to URL encode the brackets... The usual way this feature is used is in creating an HTML input field with the name "var[]", so just do whatever the browser normally does there. There's a section in the PHP documentation on array variables through the request.
You may be looking for a way to Serialize (jQuery version) the data.
jQuery 1.4 was updated to use the PHP syntax for sending arrays. You can switch it into the old style by using:
here is the synatax:
jQuery.ajaxSetting.traditional = true;
here is the example
$.ajax({
traditional: true,
type: "post",
url: myURL,
dataType: "text",
data: dataToSend, //this will be an array eg.
success: function(request) {
$('#results').html(request);
} // End success
}); // End ajax method
You can create an array and send it, as Meador recommended:
(following code is Mootooled, but similar in other libraries / plain old JS)
myArray.each(function(item, index) myObject.set('arrayItems['+index+']', item);
myAjax.send(myObject.toQueryString());
That will send to php an array called arrayItems, which can be accessed through $_POST['arrayItems']
echo $_POST['arrayItems'] ;
will echo something like: array=>{[0]=>'first thing', [1]=> second thing}
Related
i have a form that fetches all the data from database and in order to update the datas that is fetched i need to serialize the data.
alert($("form").serialize());
and this is the output
tid=1&tname=T+Cap&tsize=XS&quantity=1&tprice=1200&tid=2&tname=Super&tsize=XS&quantity=1&tprice=2800&tid=3&tname=Dota+Tees&tsize=XS&quantity=1&tprice=700
how to retrieve this data in php in order for me to update the database?
You have to combine functions $.submit() and $.post() or $.ajax():
$('form').submit(function() {
$.ajax({
type: "POST",
url: $(this).attr("action"),
data: $(this).serialize(), // serializes the form's elements.
success: function(data) {
console.log(data); // show response from the php script
}
});
return false;
});
Then in your PHP script you have to read your data from $_POST array. E.g.
$tid = $_POST['tid'];
To debug your incoming $_POST array use var_dump() or print_r().
If you want to send response to your javascript just pack whatever you want into variable and then just use die(json_encode());. E.g.:
$output = array('status' => true, 'message' => 'Success');
die(json_encode($output));
It also will be required to add to $.post() method attribute:
dataType : 'json'
In your PHP, at the top write this and you'll see what's happening.
//If method = GET
var_dump($_GET);
//If method = POST
var_dump($_POST);
exit();
This will show all variables that are being passed and stop the script so you can review on the page. Then just have your jquery put the response data in a div that you can view.
The problem seems to be that you are redefining your $_POST vars. They can not contain the same names/keys as you are sending them over currently. Essentially its like redefining a variable, it will no longer contain its previous value.
tid=1&tname=T+Cap&tsize=XS&quantity=1&tprice=1200&tid=2&tname=Super&tsize=XS&quantity=1&tprice=2800&tid=3&tname=Dota+Tees&tsize=XS&quantity=1&tprice=700
Notice how you have called tid and the other keys multiple times? Instead you would want to give them separate names,or pass an array of values to your PHP.
Example:
tid=1&tname=T+Cap&tsize=XS&quantity=1&tprice=1200&tid2=2&tname2=Super&tsize2=XS&quantity2=1&tprice2=2800&tid3**=3&tname3=Dota+Tees&tsize3=XS&quantity3=1&tprice3=700
Of course there are other ways of doing this as well.
Each key must have a unique identifier, other wise it will overwrite the previously defined $_POST value.
Instead of:
tid=1&
tid=2&
tid=3&
You would want:
tid1=1&
tid2=2&
tid3=3&
Looks like a job for PHP's parse_str() function. http://php.net/manual/en/function.parse-str.php
I have a JQuery script which dynamically generates HTML elements on button click.
I am connecting to a mysql database using PDO and PHP but am wondering how you can target dynamically generated variables in an external JS file directly from PHP.
I have tried using AJAX but as far as i can understand it seems to only get data from PHP pages and not the opposite.
The JQuery code is like this...
//Where i want to use indexes from a lookup table to populate the select element
$("#main").append('<select><option value=""></option></select>');
I tried AJAX in this way
function getData(dataToPass)
{
$.ajax({
type: "POST",
url: "getData.php",
data: dataToPass,
success: function (returnedData)
{
$("#main").html(returnedData);
}
});
}
But you cant pass variables this way can you?
Im very new to PHP and JQuery and would appreciate the help.
First off, PHP has nothing to do with JavaScript. They are totally different languages, in their own separate domain. They co-work however if you want to. PHP can generate JavaScript code, which will then run on the client browser. The client browser though has no idea that the JavaScript code that is running was generated by PHP. Neither does PHP have any idea how to work with a browser. PHP doesn't even have any idea about HTML.
Thus, you can't pass to PHP a complex JavaScript object, the same way as you can't pass an object from PHP to JavaScript. However you CAN pass values and data structures (arrays, data objects).
In this case, you can either get the inner HTML code of the jQuery object in your JavaScript, by running
dataToPass = {html: $("#main").html()}; //it will be a string
or by constructing an object that will have just the data you need, for example:
dataToPass = {elements: [
{node: "select", options: [{node: "option", value: ""}]},
{node: "input", value: "someValue", type: "text"},
]};
As you have this JavaScript, it will send this data via the script you already have, to the server. On the server side you will have to intercept the $_POST superglobal, and ask for either the HTML string, which will be $_POST['html'] if you chose the first example, or access an array of elements by $_POST['elements'] if you used the second example.
In an earlier post today the answer has led me down the route of using a JSON feed to populate elements in my page.
Something new to learn!!
the JSON data is created from a PHP script which retrieves the data from a Mysql database. The php script retrieves a specific record which I need to pass to the php script with the getJson call.
I've had success with creating the url with the parameters added as a GET method but I can't find an example of a POST method - the parameters should go as an optional parameter. here's what I have so far...
function loadData(index) {
alert(index);//debug
$.getJSON('loadJSONholeData.php' ,
{hole: index} ,
function(data) {
I've found examples for a twitter feed which shows a parameter like option: "cat", but can't find an option where the value is in a variable.
I don't understand how to use the parameters - where am I going wrong. Appreciate this is probably a fundamental issue but I'm learning.
Thanks
Update:
I've revised the code per the responses below and used both suggestions to pass the POST parameter, but the receiving PHP code is not reading the POST parameter and just returns the default query values.
I even used as static value of 1 both as a value and as a string but no joy.
Here's my receiving PHP code which accesses the POST values:
$hole = 3;
if (isset($_POST['hole'])) {
$hole = $_POST['hole'];
}
I'm missing something basic here. The value in 'index' definitely exists as it shows in the debug and JSON data is being returned )(but the default). I can go back to my GET method but want to see this work!!
Thanks
Update: Success!!
I played around further with the revised code. I removed the content type parameter from the code and it all works now, the PHP is returning the correct query.
I assume then that by specifying the JSON type in contentType it passes the POST parameter in a different way to PHP which expects it in anpther way?
Onwards and upwards - thanks
The $.getJSON() method does an HTTP GET and not POST. Try something like this -
$.ajax({
url: 'loadJSONholeData.php',
data: JSON.stringify({hole: index }),
type: 'POST',
contentType: 'application/json;',
dataType: 'json',
success: function (result) {
//(result.d) has your data.
}
});
Each key/value pair in the arguments object will represent a parameter in the HTTP POST. You can use variables as values, but I believe they will be converted to strings, so it's better to do the conversion yourself (so you can make sure they have the correct format). A simple example:
var dynamicValue = foo();
$.post('my/url', { var1:"static value", var2:dynamicValue }, function(data) {
// Your callback; the format of "data" will depend on the 4th parameter to post...
}, "json"); // ...in this case, json
Now, in case your server is expecting a json encoded object/list, you can pass it by using JSON.stringify:
function foo() {
return JSON.stringify({ my:"object" });
}
JSON should be available in most modern browsers, in case it's not, you can get it here (json2.js, under "JavaScript").
In a simple ajax post example:
$.post('ajax/test.php', function(data) {
$('.result').html(data);
});
Is there any way to separate the result data to do two different things? ie:
$.post('ajax/test.php', function(data) {
$('.result').html(data.partone);
$('.other-result').html(data.parttwo);
});
I run an ajax request when the page is loaded and I'm trying to get everything I need in one POST. If this is possible, how do you define the different data parts on the PHP side? (ie: data.partone and data.parttwo)
You can return the data as JSON encoded string, using json_encode() on an associative array, for example: echo json_encode(array("partone" => "data1", "parttwo" => "data2"));
That way you could access it as data.partone and data.parttwo. Also worth mentioning, you should define the dataType in the $.post() to be read as JSON. For that, you need to add another parameter to it, specifying the type of data you are returning - JSON.
For example: $.post('ajax/test.php', function(data) { ... }, "JSON");
Also worth mentioning, that you should return ONLY this json_encode() output back from the ajax script, else jQuery won't be able to parse it right.
An AJAX call only returns one response, which is stored in that data variable. However, what your server-side code returns as that response is up to you, and what you do with it in your Javascript is also up to you.
Assuming you're returning some HTML that you want to make the contents of some elements on your page, what you could do is separate the two parts in a way you can distinguish with Javascript. Perhaps something along the lines of:
/* part one here */|parttwo|/* part two here */
Then you just need to split data on the '|parttwo|' string, and use the elements of the resulting array to set the contents of your different elements.
So I'm building a web application and I have an ajax request that pings a database (or database cache) and echos back a big thing of json. I'm totally new to json, and when the php pulls from the database I echo json_encode($databaseResults), then it shows up in my html page as a long string. My question is, how do I convert it and pull out the pieces I need into a nice format?
Thanks!
The Json result that was in the page looks like:
"[{\"currentcall\":\"1\",\"timecalled\":\"15:30\",\"etaTime\":\"15:35\",\"departmentID\":\"1\",\"memberID\":\"1\",\"callinnum\":\"1\",\"location\":\"Fire House\",\"billed\":\"N\",\"date\":\"2\\/12\\/11\",\"firstName\":\"Phil\",\"lastName\":\"asdf\",\"email\":\"pasdf#gmail.com\",\"homephone\":\"+19111111111\",\"cellphone\":\"+11234567891\",\"cellphone2\":null,\"workphone\":null,\"phonenumber5\":null,\"phonenumber6\":null,\"streetAddress\":\"10 asdfnt Dr\",\"city\":\"\",\"username\":\"pgsdfg\",\"password\":\"0623ab6b6b7dsasd3834799fbf2a08529d\",\"admin\":\"Y\",\"qualifications\":\"Interior\",\"rank\":null,\"cpr\":null,\"emt\":null,\"training\":null,\"datejoined\":null,\"dateactive\":null,\"state\":\"DE\",\"zip\":\"51264\",\"pending\":\"NO\",\"defaultETA\":\"7\",\"apparatus\":\"asdKE-286\"}]"
There can be multiple results... this is only one result
EDIT:
Basically, I'm trying to pass a bunch of rows in an array into an html file, and take out only the data I need and format it. I don't know if json is the best way to do this or not, just one solution I came up with. So if anyone has a better solution that would be awesome.
Edit2:
This is the jquery I have that makes the request, the php just has echo json_encode ($DBResults);
function getResponder(){
var responders = $.ajax({
type : "POST",
url: "/index.php/callresponse/get_responders",
success: function(html){
$("#ajaxDiv").html(html);
}
});
setTimeout("getResponder()", 10000);
}
As you flagged this as jquery I assume that you're using jQuery. If you're only going to get the one string you can skip the json part and use jQuery .load() like this $('#result').load('ajax/test.php'); that will load the contents from ajax/test.php into #result
However if you want to use json you can take a look over at getJSON on the jQuery documentation. You can also use the jQuery parseJSON function which will return the json an javascript object containing the jsonData.
Here's an example how you can use parseJSON
var object = $.praseJSON(jsonString); //jsonString is the string containing your actual json data
alert(object.location) //Will alert "Fire House" with the given json string
Here's an example of how you can use getJSON in the same way
$.getJSON('ajax/test.php', function(object) {
alert(object.location); //Will alert "Fire House" with the given json string
});
If you want to pass parameters as well you can do it like this
$.getJSON('ajax/test.php',
{
Param1 : "Value1",
Param2 : "value2"
},
function(object) {
alert(object.location); //Will alert "Fire House" with the given json string
}
);
If you are trying to send json from javascript to php you can use
$jsonArray = jsonDecode($_GET['key']);
Of course if you're using post you'll write $_POST instead.
You have to parse the data into a JSON object, then you can use properties of the object as you wish.
Without seeing the specifics, I can tell you that you'll need to use the JSON object to parse the text. See more here: http://www.json.org
var obj = JSON.parse(ajaxResponseText);
You should use php function json_decode which will give you an object or array with all the properties.
Then you should iterate recursively through this object and add the content of the properties to a string, which should be your final HTML.
Normally to display JSON response in an html element after jquery(for example) by web request, try this:
$("#box-content-selector").append(
"<pre>"+
JSON.stringify(JSON.parse(data), null, 4)+
"</pre>"
)