Can you please let me know how I can pass Two Values from PHP file into a jQuery Ajax script. What I have is a Ajax call as:
<script>
$(function() {
var req = $.ajax({
url: 'captcha.php',
});
req.done(function(data){
alert(data);
})
});
</script>
and my PHP (captcha.php) is like:
<?php
$number1 = rand(1,9);
$number2 = rand(1,9);
$sum = $number1 + $number2;
echo $number1;
?>
as you can see currently I am able to pass the value of the $number1 but I need to have both values($number1 and $number2). Can you please let me know how to achieve this?
Thanks
Instead of sending (invalid) HTML to the client, use a structured data format, such as JSON.
<?php
header("Content-Type: application/json");
$data = Array($number1, $number2);
print json_encode($data);
exit;
In the JavaScript, jQuery will now populate data with an array.
Why don't you make an array containing variables to return and json_encode it to parse it in JS?
echo json_encode(array($number1, $number2));
Make an array out of your values:
$array = array($number1, $number2);
Then parse it to json
$json = json_encode($array);
Then echo out the $json and you have multiple variables in your js!
<script>
$(function() {
var req = $.ajax({
url: 'captcha.php',
});
req.done(function(data){
data = data.split(",");
//Number 1
alert(data[0]);
//Number 2
alert(data[1]);
})
});
</script>
<?php
$number1 = rand(1,9);
$number2 = rand(1,9);
$sum = $number1 + $number2;
echo $number1 .",". $number2;
?>
All this does is tells the php script to echo Number1,Number2 and then the javascript splits this string into an array from the ,
First Way
You can concatenate the two values seperating them by a special character like '_' like this
PHP
echo $number1 . '_' . $number2;
And then do like this in javascript
data = data.split('_'); // get an array with the two values
Second way
You can encode as JSON in php and do a json ajax request
PHP
$result = array($number1, $number2);
echo json_encode($result);
Javascript
$.getJSON('captcha.php',function(data){
console.log(data); //
});
Related
i am working on online exam test where childArray[] contains data from each row of table and parrentArray[] contains number of childArray[]. i want to get value of each childArray from ParentArray with Index passed through ajax.
<?php
$childArray1[]=[1,question,optionA,optionB,optionC];
$childArray2[]=[1,question,optionA,optionB,optionC];
$parentArray[]=[$childArray1,$childArray2];
?>
<script>
$(document).ready(function(){
var counter=0;
$("#ButtonNext").click(function(){
$.ajax({
type:"POST",
url: "ChangeQuestionProcess.php",
data:{
MainList:"<?php echo json_encode($parentArray); ?>",
Counter:counter,
},
success: function(result){
$("#callMe").html(result);
}});
counter++;
});
});
</script>
ChangeQuestionProcess.php
<?php
$index=$_POST["Counter"];
$test[]=$_POST["MainList"];
echo test[$index];
?>
In your ChangeQuestionProcess.php, this line:
$test[]=$_POST["MainList"];
...is saying "take the contents of $_POST["MainList"] and make it the next element of the array $test"
You're doing a similar thing at the top of your first script - I think you mean this, without the [] after the variable names:
<?php
$childArray1=[1,'Question 1','Option 1A','option 1B','option 1C'];
$childArray2=[2,'Question 2','Option 2A','option 2B','option 2C'];
$parentArray=[$childArray1,$childArray2];
?>
You could even simplify this to:
<?php
$parentArray = [
[1,'Question 1','Option 1A','option 1B','option 1C'],
[2,'Question 2','Option 2A','option 2B','option 2C']
];
?>
Now back to ChangeQuestionProcess.php again - bear in mind that $_POST["MainList"] is going to be a string containing JSON-encoded data (as that's what json_encode() returns)
Therefore what I think you are trying to do is read the array of JSON-decoded data into $test, which you would do like so:
$test = json_decode( $_POST["MainList"] );
Finally, you're missing a $ when echoing your variable. But as $test[$index] is an array, you'll just see Array on your screen instead of its contents. I think you need something like print_r instead of echo:
<?php
$index = $_POST["Counter"];
$test = json_decode( $_POST["MainList"] );
print_r( $test[$index] );
?>
In my db I save the json in a custom field called usp-custom-12 like this:
[{"Mamma":["Papa"]}]
Then I try to decode that
<?php
$jsonTable = usp_get_meta(false, 'usp-custom-12');
?>
var data = <?php echo htmlspecialchars_decode($jsonTable); ?>;
But it is giving me
var data = "[{"Mamma":["Papa"]}]";
And a console log error:
Uncaught SyntaxError: Unexpected identifier
The full code:
<?php
$jsonTable = usp_get_meta(false, 'usp-custom-12');
?>
var data = "<?php echo htmlspecialchars_decode($jsonTable); ?>";
console.log(data);
data = JSON.parse (data);
data.forEach(obj => {
Object.keys(obj).forEach(key => {
$('#newTable thead tr').append($('<th>').text(key));
obj[key].forEach((e, i) => {
if(!$("#newTable tbody tr:eq("+i+")").length) $("<tr>").appendTo($("#newTable tbody"));
$("#newTable tbody tr:eq(" + i + ")").append($('<td>').text(e))
})
})
});
In this jsFiddle if you click save table you will see it generates a table identical to the top one, that's also logging in console the correct json: https://jsfiddle.net/fbh0o67o/74/
$jsonTable contains a JSON string with html entities encoded, since it's already JSON, you just have to decode the html etities and echo it as is. No JSON decoding is required, no quoting is required. Just HTML decode and echo it into your javascript.
var data = <?php echo htmlspecialchars_decode(usp_get_meta(false, 'usp-custom-12')); ?>;
data.forEach(obj => {
// Loop stuff here...
});
The issue is with the quotes inside the string "mama" you need to escape those quotes using addslashes method.
Try using the following:
var data = "<?php echo addslashes(htmlspecialchars_decode($jsonTable)); ?>";
JSON to PHP:
json_decode($string);
If you use the optional parameter $assoc as true - json_decode($string, true) will return associative array on success.
PHP to JSON:
json_encode($array);
PHP manuals:
json_encode()
json_decode()
Is this valid approach: I want to keep api key from being accessible via source code so I have been trying to keep it hidden with PHP and use Javascript to display data. (I prefer to use js syntax to display data) I've been able to display data successfully but when I look at the source code I can see the JSON response. Can anyone tell me if this is a valid approach and why not good idea to have json shown in source?
<?php
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
$json = json_decode($data,true);
?>
I then access the response like so:
<script type="text/javascript">
var data = <?php echo json_encode($json) ?>;
$('.in-theaters-soon').append('<p>' + data.movies[0].title + '</p>');
</script>
You can directly echo the values from PHP since you already have the response in $json. For example:
<div class="in-theaters-soon">
<p><?php echo $json['movies'][0]['title']; ?></p>
</div>
Always make some validation of the printed data.
<?php
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
if (is_array($data) && ! empty($data)) {
/**
* Do something.
/**/
}
You could do something like this if you have the php in a separate file.
Your php file.
<?php
// create a token check to make sure it is being called.
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
echo json_encode($data);
?>
Then query your php file something like this sending a token or something similar.
$.ajax({
url: url,
type: 'POST',
data: {token:token},
success: function(data){
var response = $.parseJSON(data);
for(var x = 0; x < response.length; x++){
$('.in-theaters-soon').append('<p>' + response[x].title + '</p>');
}
},
cache: false,
contentType: false,
processData: false
});
Hope this helps.
So I have a database pass a whole bunch of data using PHP back to jQuery through JSON.. I'm trying to access individual columns from the returned data but no luck..
My PHP:
header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
Here's my JS:
function getAll(){
jQuery.ajax({
url:'example.com/js/getAll.php',
async: true,
dataType: 'jsonp',
success:function(data){
$('.quoteList').append(data[0]);
}
});
}
Currently that appends the following to the element:
[{"id":"1","text":"The most wasted of all days is one without laughter.","author":"E.E. Cummings","status":"1"}]
So for example.. if I wanted the jQuery to go through data[0] to data[92] (the last one) and append the author of each to .quoteList, how could I do that? I've tried data[0][1] and data[0][author]
You can use $.each() to loop through the data and append the author:
$.each(data, function(i) {
$('.quoteList').append(data[i]['author']);
});
The PHP might be defective because json_encode is called twice, and this is unusual. As written this would be flattening the rows into JSON strings, but mere strings nonetheless, which then get JSON encoded again into an array of strings. This is probably not what you intended, as it would be making it possible to print the received data but not access the components of rows which will be decoded to strings and not objects.
Compare https://stackoverflow.com/a/6809069/103081 -- here the PHP echoes back a callback with a single JSON object inside parenthesis ().
I suspect the fix looks like https://stackoverflow.com/a/15511447/103081
and can be adapted as follows:
header('Content-Type: application/json');
require 'database.php';
mysql_query('SET CHARACTER SET utf8');
$myjsons = array();
$qry = 'SELECT * FROM quotes ORDER BY id';
$result = mysql_query($qry);
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
Once you have this, you should be getting back proper JSON for your array of objects and be able to use #Felix's code on the client side.
you need to use loop on your data, try this
success:function(data){
for (var i in data) {
$('.quoteList').append(data[i]);
}
}
This should work:
(upd. all code:)
function getAll(){
jQuery.ajax({
url:'example.com/js/getAll.php',
async: true,
dataType: 'jsonp',
contentType: "application/json",
success:function(data){
var str = "";
$(data).each(function(index, item){
str += item.author + " ";
});
$('.quoteList').append(str);
}
});
}
Your problem is here:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo $_GET['callback'] . '(' . json_encode($myjsons) . ')';
you need something like this:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
$myjsons['callback'] = $_GET['callback'];
echo json_encode($myjsons);
i am having a probelem with ajax multiple delete. I've sucessfully set the values of the checkbox slected in a variable.
the problem i have to solve is how to get the value of the sent array in php.
here is the ajax post code
<script>
$("#delete-btn").click(function(e){
e.preventDefault();
var id = new Array();
$(".check:checked").each(function() {
id.push($(this).attr('value'));
});
$.post("../ajax/multiDelete.php",{id:id},function(data){
alert(data);
});
});
</script>
now, the php page
<?php
if(isset($_POST['id'])){
$id = array($_POST['id']);
foreach($id as $value){
echo $value;
}
}
?>
when the data is alerted, i only get "array";
i do not know about JSON, so if there is anything i can do without it then your help is most appreciated! thanks : D
Since id is an array and in your code you are wrapping it inside an array again. Instead of that,do this :
<?php
if(isset($_POST['id'])){
// Don't use array($_POST['id']) as id is already an array
$id = $_POST['id'];
foreach($id as $value){
echo $value;
// Here you'll get the array values
}
}
?>
If you want retun array from php - user json_encode()
echo json_encode(array($_POST['id']));
P.S. JS function alert() can`t print arrays or object. Use console.log(data) and you will see result in developer console of your browser.
This is not related to your question, but I just wanted to show you a better way of getting the id values, without creating a new array variable and then pushing items into the array, by using the jQuery .map() method:-
$("#delete-btn").click(function (e) {
e.preventDefault();
// Get all the values in the array 'id' variable
var id = $(".check:checked").map(function () {
return this.value || 0;
}).get();
$.post("../ajax/multiDelete.php", { id: id }, function (data) {
alert(data);
});
});
Hope this helps!
Don't pass array variable in AJAX. Convert id array to JSON using JSON.stringify(id).
In PHP backend,use
<?php $val = json_decode($_REQUEST['id']);
foreach($val as $ids){
echo $ids;
}
use $val array to proceed further in php.
You have to access your checked value by-
<?php
if(isset($_POST['id'])){
$id = array($_POST['id']);
foreach($id as $value){
foreach($value as $value1){
echo $value1;
}
}
}
?>
Because this is an array inside array.