Hi i have post form in jquery with php , the form call other page and get the result with json from jquery , for example when i use jquery and call to this page in php i get this for read json from jquery :
<?php
print '{"login":"datos_fails_lock"}';
?>
The problem in this case it´s i can only show this and no include other text in the results , if include more os this code the script no works , i like json detect this code but also i want show html and at the moment i can´t do this
It´s posible when i call other page from form of jquery i can include other informations as html and works json from this page
Sorry i explain the best i can
Regards !
Instead of printing your own json text layout, why not use PHP json_encode to do it for you. that way you can have the array you want including html and have that function encode it.
Example:
<?php
print json_encode(array('login' => 'datos_fails_lock'));
?>
At the PHP side:
<?php
// compute html
$html = '<div><p>...</p></div>';
// compute json
$json = '{"login":"datos_fails_lock"}';
$response = array('html' => $html, 'json' => $json);
print json_encode($response);
?>
At the JavaScript side:
var response = JSON.parse( xhr.responseText );
// append html to a div
$( '#response' ).html( response.html );
// parse json response
var jsonObj = JSON.parse( response.json );
To the best I can understand,
if you are looking to get json encoded values from your php file and show with jquery that called the file you do something like:
In you php file:
<?
echo json_encode(array(
'login' => 'datos_fails_lock',
'something_else' => 'Other thing'
));
?>
and from jQuery if it is post submission, you can use some thing like:
$.post('ajax/process.php', function(data) {
$('.result').html(data.login);
$('.other_thing').html(data.something_else);
});
The best inline solution:
<?php
$myObjectOrArray = (object) array('test' => array('test' => array('test' => 'testValue')));
$javascriptGateway = rawurlencode(json_encode(myObjectOrArray));
?>
<script type="text/javascript">
//<!--
var myObjectOrArray = JSON.stringify(unescape('<?php echo $javascriptGateway;?>'));
alert(myObjectOrArray.test.test.test); //result: testValue
//-->
</script>
I use this solution so I can pass my php object containing special char into a javascript object.
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.
I'm using Dynatree for the first time and wrote a PHP script that returns a properly formatted JSON array.
I've read the Dynatree documentation, but can't figure out how to pass in the JSON array from my PHP script so its contents can be loaded as the tree structure.
At the top of my HTML file, I'm using <?php include('tree.php') ?> which automatically returns the formatted JSON array (named $categories). I'd also be fine with calling a function from JavaScript to retrieve the tree if that makes it easier.
Can someone show me how to deliver my array to Dynatree?
You can use a data- attribute, like this:
<?php
$dynaConfig = array('children'=>array(
array('title' => 'Alice'),
array('title' => 'Bob')
));
$dynaConfigJSON = json_encode($dynaConfig);
// HTML head goes here
echo '<div id="tree" data-dyna="' . htmlspecialchars($dynaConfigJSON) . '">';
?>
<script>
$(function() {
var dtConfig = $.parseJSON($('#tree').attr('data-dyna'));
$('#tree').dynatree(dtConfig);
});
Here's a live example, and the corresponding full source code.
You can also separate the code of php in a file like tree.php and then call it in javascript.
<div id="tree"> </div>
<script type="text/javascript">
$(function(){
$("#tree").dynatree({
initAjax: {
url: "tree.php"
}
}
}
</script>
This JavaScript code was in a PHP file, and I need to put this JS code into a .js file.
<script>
$j(".fresh").click(function(){
$j(this).html('<span><?php echo $this->lang_arr['my_new_func']; ?></span>');
$j.post( "<?= site_url('website/func_resh') ?>",
{ id : "<?= $webfun_one_arr[id] ?>",
website_id : "<?= $web_one_arr[id] ?>"
}
);
})
</script>
I know this code <?php echo $this->lang_arr['my_new_func']; ?> in the JavaScript format is {$this->lang_arr['my_new_func'];}
But I don't know how I change <?= site_url('website/func_resh') ?> and <?= $webfun_one_arr[id] ?> into JS format.
Thanks for any answer.
Interpolating PHP and JavaScript is a big can of worms that you should avoid opening. IMO the best way to deal with this is to use PHP to output a JSON object, which it has built-in support for, and then use the object in your JavaScript. This way you only have to put one tiny snippet of PHP in a <script> tag and you don't have to try to make the server parse .js files as PHP. Something like this:
In your PHP:
<?php $my_vals = array(
'myNewFunc' => $this->lang_arr['my_new_func'],
'postUrl' => site_url('website/func_resh'),
'postId' => $webfun_one_arr['id'],
'postWebsiteId' => $web_one_arr['id']
);
?>
<script>
$j.getScript('/path/to/your_script.js', function() {
myFunc(<%= json_encode($my_vals); %>); // turns your PHP array into a
}); // JavaScript object automatically
</script>
Then, in your_script.js:
// Look, Ma, no PHP!
function myFunc(someJson) {
$j(".fresh").click(function(){
$j(this).html('<span>' + someJson.myNewFunc + '</span>');
$j.post( someJson.postUrl,
{ id : someJson.postId,
website_id : someJson.postWebsiteId
}
);
});
}
Don't. Make it a .js.php file that returns a content type of text/javascript, and includes the other relevant PHP scripts.
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;
I have a PHP script that retrieves names (strings) from database. I would like to pass this array to Javascript using $.ajax().
I cannot understand how should I encode the array in PHP and then decode it in Javascript.
Could someone give an example code for this ?
Thanks a lot !!
<?php // test.php
$myArray = array(1, 2, 3);
echo json_encode($myArray);
?>
HTML File:
$(function() {
$.getJSON('http://localhost/test.php', function(data) {
$(data).each(function(key, value) {
// Will alert 1, 2 and 3
alert(value);
});
});
});
u can use json_encode
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
?>
full example you can read at :
http://www.prodevtips.com/2008/08/15/jquery-json-with-php-json_encode-and-json_decode/
or
http://www.prodevtips.com/2009/12/09/multiple-select-lists-with-jquery-and-json/
<?php
echo json_encode(array('key' => 'value', 'cool' => 'ice'));
?>
json is a javascript object. So there is no need to "decode" it. However, it looks like you are using jquery. There is a nifty function for retrieving json data:
jQuery.getJSON(url, senddata, function(returndata){alert(returndata.cool);})
or
jQuery.getJSON(url, senddata, function(returndata){mybigfunction(returndata);})
mybigfunction(data)
{
myvar = data.cool;
alert(myvar);
}
http://api.jquery.com/jQuery.getJSON/
or you could also do it with $.ajax as you mentioned:
jQuery.ajax({
url: url,
dataType: 'json',
data: senddata,
success: function(data){mybigfunction(data)}
});
mybigfunction(data)
{
myvar = data.cool;
alert(myvar);
}
http://api.jquery.com/jQuery.ajax/
The "callback" is a function that gets called and passed the json data returned from the url.
You will 'ice' baby... ermm... sorry for the corn.
The getJSON method is rather short and handy. Have a look at the links for more details.
This is Php File Code
<?php
$array = array(1, 2, 3);
echo json_encode($array);
?>
Then you can parse $array in your $.ajax() like this
success: function (data) {
var x = JSON.parse(data);
console.log(x);
}
To do this, you'll just have to echo out a script into the PHP page that contains your data, which you can then access from any other Javascript on the page, including jQuery and .ajax().
Again, if you just want to pass it via an AJAX call, just use json_encode():
<?php
echo json_encode(
array(
'groupidlist'=>$groupids,
'groupnamelist'=>$groupnames,
'serverurl'=>$serverurl,
'uid'=>$curuser->getID()
)
);
?>
And then process it with the callback functions from .ajax() or, probably better, .getJSON(), which is built for just this use.
I promise I don't just spam my blog here, but I wrote a post on passing variables between Javascript and PHP, because I did it often enough that I came up with a simple/reliable/clean and reusable way to do so. If you're regularly passing data from PHP to Javascript and don't need AJAX, I'll paste the essentials here:
At the top of each external js file, I add comments as to which PHP variables are required, so I can keep track of what I need when I include it (this is optional, of course, but nice):
/* This script depends on the following variables in phpvars:
groupidlist
groupnamelist
serverurl
uid
*/
Then, in the PHP file, I pass the needed variables with a single line of Javascript, assigning a JSON Array with all the needed values. Examples in PHP, directly from my code:
<script type="text/javascript">
var phpvars = <?php
echo json_encode(
array(
'groupidlist'=>$groupids,
'groupnamelist'=>$groupnames,
'serverurl'=>$serverurl,
'uid'=>$curuser->getID()
)
);
?>;
</script>
Once that is set up, I can then simply access whatever PHP Variables I need in the Javascript through the phpvars array. For example, if I needed to set an image source using my serverurl, I could do as follows:
imgElement.src = phpvars.serverurl + '/images/example.png';
Because it uses JSON, there is no worrying about making sure that you don't screw anything up in your Javascript by trying to insert the PHP variables. The encoding/decoding of the variables is handled on both ends by built-in JSON functions, so it is very hard to break it, and brainless to pass variables - you pass them like you would any other PHP array. In my fiddling that led to this, I had problems with both of these, and this solution takes care of them nicely.