How to pass multiple variables between jQuery and PHP files using JSON? - php

How can I pass multiple variables between PHP files using jquery with json?
Ex:
$.post("example.php", {asdf:asdf, sdfg:sdfg}, function(data){
$('section').html(data);
});
But instead of just using the .html function I want to retrieve multiple variables from the PHP file and then use them for .html on my page. I can't just use data because that only outputs whatever PHP returns so to my understanding php can only return one thing in a form of an echo(), but how can I make it retrieve more than just that one variable? I think I have to use JSON but I have never used JSON before so I would appreciate it if someone could help me out.
Thanks.

You can return a JSON object from php ( Returning JSON from PHP to JavaScript? ). And then in your jquery you can acees it like this,
$.post("example.php", {asdf:asdf, sdfg:sdfg}, function(data){
$('section1').html(data.Variable1);
$('section2').html(data.Variable2);
});

You could have the php script output javascript code creating your variables and then just eval() it.

See the jQuery post() documentation here. Check out the dataType parameter, which tells jQuery what kind of data to expect back from the server.
See the json_encode() and json_decode() PHP functions here. Use json_encode() to prepare your populated data structure for echo()'ing back to the client.

Related

html object to call php and return string

I want to call a php script (with args) from HTML and to process the returned data
I tried various flavours of :
<object id=test1 data="object.php" type="text/plain">
where object.php just returns a string, like
<?php print "firstText:Hello World";?>
I can't work out how to retrieve the returned string.
I was hoping to find it in something like
document.getElementById("test1").firstText
But no joy
Why am I doing this, you ask?
I'd like to get the page working interactively between the user and the server, avoiding the repainting of the browser window that comes with re-submitting with POST/GET.
Thanks for your responses.
I'm not happy using JQuery - another layer beyond my control
I have eventually found the returned text in
document.getElementById("test1").contentDocument.body.firstChild.textContent
which I can then work with.
Thanks
Use AJAX. Here's an example using jQuery:
$.get('yourpage.php', function(response){
// response contains the string returned by your PHP page.
});
PaulPros idea is probably your best method. Don't forget to include jQuery.
Is there any reason you could not just make the .HTML a .php file and include your script?

Passing jQuery Value to PHP

I am calculating the distance between two places using jQuery and I want to pass this value (pickup_distance) for use in PHP.
I am wanting to send this value to tariff.fare.controller.php for use in the following function:
private static function getFare($int_terminate) {
// Function
if pickup_distance(<-- jQuery Value) > 5 {
// Do Something
}
}
How could I go about doing this? I'm aware I can do this via AJAX but being quite new to programming I'm not quite sure how I can do this.
Any help would be much appreciated!
using Jquery it's quite easy:
var your_var_value=1200;
$.post("your_php_script.php", {var_value: your_var_value}, function(data){
alert("data sent and received: "+data);
});
then in your PHP script you get the variable like this:
$distance=$_POST['var_value'];
And what you echo in "your_php_script.php" is returned as the data variable.
As jQuery is client side code and PHP is Server side code, the variables must somehow be passed to the server.
There are a few decent ways of doing this, by far the most common is GET and POST variables.
then you can pick them up in php and do whatever you wish with it.
A very simple example is to have an iframe/php image whatever and just load the src with JavaScript or jquery file.php?EEEE=YYY then fetch that variable $_GET['EEEE']
Best way to do it is to use jQueries built in Ajax functionality. Either use .ajax or .post and send in your required parameters to your PHP script.

A clean way of obtaining values from inputs and sending them to php file

I am looking for a really simple way of getting all the values from all input elements (and some dividers as well) and then quickly sending them to a PHP file with an already prepared submit function.
I have came up with a very crude solution but it needs to be heavily optimized.
For now when I click submit button I call a function
function $('#submit').click(function(){
var $divValues = new Array();
$divValues[0] = $('#divName').html();
$divtValues[1] = $('#divImgName').html();
var $values;
$values = $(':input').serializeArray();
$fileName = "php.php?firstVal=\""+$divValues[0]+"\"&secondVal=\""+$divtValues[1]+"\"&thirdVal=\""+$values['firstValName']+"\"&ect..."
//then i simply call the ajax function which will send the information to the php file
fetch($fileName);
});
maybe i could use the fact that the names of values in my associative array and the names of variables retrieved in my php file match and instead of setting my filename to ..."&thirdVal=\"" ... I would instead use the name of the $values['firstValName'] which in this example would be third value (although i have no idea how to do that)
or maybe there is an even easier way to accomplish what im trying to.
Any ideas on how to implement this piece of code in a nice manner??
Update:
For now I don't have a form element in my html but I can easily add one as soon as I see a solution that requires it to make the code simpler...
I know I can use serialize() function but my questions is about a nice way of dealing with the array that gets returned. (or maybe using 2 arrays one with name other with value or a 2 dimensional array)
Either way I just wish to see what is an easy way of both getting the data and creating the $fileName with correct values for the PHP file
I would appreciate some code or pseudocode in the answer that shows a simple way of creating the fileName with all the values
If anybody doesn't understand what I am asking or needs some clarification then they should feel free post a comment below so I can try to make myself clear.
Since you're using jQuery, you could use its AJAX methods with serialize() applied to the entire form. You can read documentation about it by clicking here. Also you can read documentation about jQuery's AJAX methods by clicking here, here and here.
In response to your request, here is a really simple example:
$.post("test.php", $("#testform").serialize());
You could really get the rest of what you need on how to use $.post or $.get functions from the documentation I referenced.
Serialize also takes care of urlencoding all the variables so you don't have to worry about that.
EDIT:
It's not really necessary to have a form. You could just do what you are trying to do with serializeArray() above, except (a) $(':input') does not select anything and (b) you should use serialize() and not serializeArray(). So without a form, the code would look as follows:
$.post("test.php", $("input,select,textarea").serialize());
This will properly request the script with the data encoded correctly and you can then read it in PHP script from $_POST or $_GET depending on whether you used $.post or $.get to request the script.

JQuery .GET call/function

Ok so trying to get a page together that needs to connect to our SQL database. So on the javascript page I have functions that will autocomplete a textbox with data out of our mysql DB and then I need to send it to other functions and classes so that it will then look in our SQL DB and return some data. The problem I have is trying to get the .GET call to call in the php page, with the function that calls the class in which I need to get into for the SQL call. I have it setup somewhat but trying to figure out how to send the data through with it as well as just get clarification on how to work the .GET function.
Javascript page:
$.get("dsl_validate.php", calldsl(job));
Php Page
function calldsl($job){
var $dsljob = $job
hasfunctioncode($dsljob);
}
The hasfunctioncode function is in my DSL class page that will return the info I need. Any help on if I am in the right direction or not?
It looks like you're trying to physically call the PHP function calldsl() from the JavaScript. This... isn't right. (I'm assuming the $.get() you're using is from jQuery, please correct me if that assumption is incorrect.)
What $.get() does is simply call a resource on the web server. It doesn't have any knowledge of the server-side code (nor should it, for a number of reasons). From the perspective of the server-side code, there's no difference between a page being called via $.get() vs. one that's just loaded in a web browser.
What you essentially need to do is create a PHP page which accepts arguments either as a form post or query string (if you're using $.get() then the query string is the way to go), does its server-side logic, and then simply outputs the results to the "page." In the case of calling the page via AJAX as you are here, it's a good idea to render the page content using JSON notation. (Don't forget to set the content-type header to "application/json" as well.)
Then what you're getting on the client-side from the $.get() call is the response body, which would be that JSON data. It's really just a "page" like any other, the only difference is the content-type telling the browser that it's JSON data and that it doesn't have HTML, just JavaScript objects. The success callback on the $.get() call (the function you pass it, or create in-line) would receive that response data as an argument and can do what you need to with it.
The way I understand jQuery.get(), the second argument is the "callback" (http://api.jquery.com/jQuery.get/). The callback will hand the results from your server therefore should be a function. Currently your code actually executes the function "calldsl" where you should be only passing a reference like so...
Javascript:
$.get("dsl_validate.php", function(response){
alert("yay I haz ajax! "+response)
});
PHP: "dsl_validate.php"
echo "this is some data from the server";
No, your are not in the right direction. The first parameter of the get method have to br the complete URL of the page, not just the script (this works if the script resides on the same directory of the javascript file, though). The .php file shall return somehting "usable" for you javascript (JSON, or HTML, or text, or... whatever). The "calldsl" function will be called AFTER the data has been returned from the call. Something like that:
$.get('dsl_validate.php?value=somevalue', function(data) {
alert("Data returned from dsl_Validate: " + data)
});
i think you are better off passing the function as a param to your php page
$.get("dsl_validate.php?calldsl="+job, function(data) {
$response = $(data);// create a jquery object from the response
});
`
and in your php file
create a switch statement that call the function based on the parameter
Mmm I think you are wrong, the second argument on your get function is the javascript function that will process de data returned by "dsl_validate.php". I mean, if that page returns "foo", job will contain "foo".
But in my experience is better to use the autocomplete plugin from Jquery UI
jquery autocomplete plugin

What's the best way to send JavaScript array to PHP script using GET?

I have an interactive web application powered by jQuery where users can manipulate visual objects on the screen. When done, the "state" of JavaScript objects should be sent to PHP to store into database. I'd prefer to use GET for this, but solution that uses POST to submit the data is also viable.
I'm currently thinking to serialize all JS objects using something like base64 encoding and just use something like:
var str = encode_objects();
document.location = 'result.php?result='+str;
However, something tells me there has to be some, more elegant, way than writing my own base64 encoding function in JavaScript. Isn't there something already built into JavaScript that can do the job?
Update: decoding in PHP is not the problem. I know how to decode base64, JSON, whatever in PHP. The problem is how to encode data on JavaScript side.
AJAX is out of the question. It has to be a clean GET or POST with page reload.
json_decode() should serve you well here.
If you simply append a string containing the JSON representation of your javascript object to your HTTP request, you can json_decode() it in PHP and have a PHP object ready to go.
Edit: I should mention that this page has a link to a Javascript JSON stringifier, which will convert your JS objects into the necessary JSON.
first of all, if you're updating the objects state, it should be a POST. try to keep all your GET idempotent.
second, even if you don't want to do any AJAX, JSON is still your friend. the easiest way would be to serialize your objects into JSON and send the resulting string in the POST dataload. there are many ways to decode JSON in PHP, and you're all set.
You can use this serialize function, and then unserialize it on the PHP end.
GET or POST will probably depend on the size of your data : there is a limit on the amout of data you can pass through GET (something like 2000 bytes ; more, depending on the browser).
There is also an other thing to take into account : if you are modifying data, you should use POST ; not GET, which is used to... get... data.
About the format, I would really not go for anything like a custom function doing any kind of stuff like base64 : I would definitly go for JSON, which is a native Javascript notation.
You can for instance have a look at :
wikipedia
http://www.json.org/
There are many JS libraries that can generate JSON (probably every JS Framework can ; and there are standlone libraries like this one) ; and since PHP 5.2 there are functions in PHP to encode/decode it (see json_encode and json_decode)
If it's just a simple flat array you don't need to do anything fancy, as PHP has a built in feature to parse array syntax from GET/POST variable names. Rough example below.
Javascript side:
// Do the parameter-building however you want, I picked the short/messy way
var arrayvalues = [1, 2, 'a'];
var querystring = "var[]=" + arrayvalues.join("&var[]=");
querystring += "&var[something]=abcdef";
// querystring is now "var[]=1&var[]=2&var[]=a&var[something]=abcdef"
PHP side:
var_dump($_POST);
// Remember to validate the data properly!
if ( is_array($_POST['var']) ) {
count($_POST['var']);
echo $_POST['var']['something'];
array_map('do_something_interesting', $_POST['var']);
}
I've used Jquery/JSON.
var jsonArray = $.toJSON(jsArray);
Then sent it via JQuery/Ajax

Categories