Take Multiple values from the php file using AJAX - php

I have a Jquery AJAX function which sends values to PHP file and the date from the PHP file is appended to the div content.
$( document ).ready(function() {
var valueSelected = $( "#sort_id option:selected" ).val();
var arr = Array();
var arr = <?php echo json_encode($details); ?>;
var details = JSON.stringify(arr);
var wash = <?php echo json_encode($_GET['wash']); ?>;
var params = Array();
var params = <?php echo json_encode($params); ?>;
var params = JSON.stringify(params);
$.ajax({
type: 'post',
url: 'sort.php',
data: {
data : details,
wash : wash,
params :params},
error : function(data){console.warn(xhr.responseText)},
success: function (data) {
$('#content').html(data).fadeIn("slow");
var jsonText = httpObject.responseText;
var jsonObject= eval('('+jsonText+')');
var count_array=jsonObject.count_array;
var count_array=jsonObject.count_sorted_array;
jQuery("label[for='private_count']").html(count_array);
jQuery("label[for='sorted_count']").html(count_sorted_array);
}
});
Now, I need to take some computed value from the PHP script and use it in the PHP file which is calling this AJAX function.
If I give the datatype:"JSON" in the above code, it is not displaying the results in the content div.
My PHP file contains the following code to be taken into jquery variable along with the content to be displayed in content division.
$count_array = sizeof($sorted_array);
$data = array(
'count_array' => $count_array,
'count_sorted_array' => $count_sorted_array,
);
echo json_encode($data);

You can create an array at PHP level where you put the HTML in a cell within it indexed by html and keep the other data:
$data = array(
'html' => '<p>....</p>',
'count_array' => $count_array,
'count_sorted_array' => $count_sorted_array,
);
Then make the AJAX as datatype:"JSON" and catch the html with data.html in order to put it in the content div

Related

don't retrieve object on php page which passed from ajax call

Hi i don't get retrieve Ajax Data to PhP page its throwing error. i pass data as json object.
The error i'm getting is
Edit.php
$('#regForm').on('submit', function (e) {
var url = document.URL; // Get current url
var id = url.substring(url.lastIndexOf('=') + 1);
var data1 = $("#regForm").serialize();
data = {data:data1,id:id};
console.log(data)
$.ajax({
method:"POST",
url: 'update.php',
dataType : 'json',
data: data,
success: function () {
alert('form was submitted');
}
});
});
update.php
if(isset($_POST["submit"]))
{
print_r($_POST['data']);
// Error::: Undefined index:data in
pass Id using hidden input field and then form data serialize then after you can use by name wise on php page.
$_POST['name'];
Read my comment, then look at this:
JavaScript may look like this
$('#regForm').on('submit', function(e){
var s = location.search.split('&'), serialId = s[s.length-1], idArray = serialId.split('=');
if(idArray.length === 2 && idArray[1].trim() !== '' && idArray[0].match(/^id$/i)){
var serialData = $(this).serialize()+'&'+serialId;
$.ajax({
method:'POST', url:'update.php', dataType:'json', data:serialData},
success:function(jsonObj){
console.log(jsonObj);
}
});
}
e.preventDefault();
});
PHP may look like this
<?php
if($_POST['id']){
// each property as $_POST[propertyHere]
// sending back to JavaScript
$c = new stdClass; $c->someProp = 'some value';
echo json_encode($c); // dataType is json so you should get Object as result
}
?>

Accessing an array in PHP from Javascript/jQuery

I have all my html, php and javascript/jquery code in a single file. I have an array $arr in php (json_encode($arr)) which when printed shows the data in php. How do I access it in javascript. The array contains all the rows from the resultset of a query execution. I have looked up jsonParse and var json_obj = but have not got any results. I am newbie so any help is appreciated. My code so far in php :
$result_again = $conn->query($sql_again);
if ($result_again->num_rows > 0)
{
$resultarray = array();
while($row_again = $result_again->fetch_assoc())
{
$resultarray[] = $row_again;
}
}
echo json_encode($resultarray);
My code in the .js file :
$( document ).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: "secondform.php",
success: function(data) {
alert("Result: " + data);
}
});
});
Step 1:
Render json_encode($arr) into javascript string variable.
var json = '<?= json_encode($arr) ?>';
Step 2:
Parse JSON string into javascript object.
var obj = JSON.parse(json);
Or if you're using jQuery:
var obj = jQuery.parseJSON(json);
You now have a javascript object which you can access properties of like below :)
alert(obj.title); // show object title
alert(obj[0].id); // grab first row of array and show 'id' column
Edit -- in reply to slugspeeds update
Ok, so looks like you're doing this the AJAX way using jQuery. Since your PHP script is using json_encode() the jQuery $.ajax() should return an javascript array object.
$( document ).ready(function() {
$.ajax({
type: "GET",
dataType: "json",
url: "secondform.php",
success: function(arr) {
console.log(arr); // show array in console (to view right-click inspect element somewhere on screen, then click console tab)
$.each(arr, function( index, row ) { // loop through our array with jQuery
console.log('array row #'+index, row); // show the array row we are up to
// you can do what you want with 'row' here
});
}
});
});
For reference:
https://developer.chrome.com/devtools/docs/console

Send javascript array to php using json

This question might be repetitive but i got confused reading all posts relating to this.(sincere apologies!) Basically, I want to send a javascript array to a php file and inturn write the array to a text file . I learnt the best way to go about it is using JSON and AJAX. My code is displays "success" for the ajax part, and also creates a file (php code),but an empty text file.
$('#tabletomodify').on('change','.street',
function (event)
{
event.preventDefault();
var row=( $(this).closest('tr').prop('rowIndex') );
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
var ideSelected= this.id;
var values = [valueSelected];
for ($i=3;$i<row;$i++)
{
var dv="selectstate"+$i;
var dv1=document.getElementById(dv).value;
var sl="selectstreet"+$i;
var sl1=document.getElementById(sl).value;
var po="selectbuilding"+$i;
var po1=document.getElementById(po).value;
var concat=dv1+sl1+po1;
values.push(concat);
}
JSON = JSON.stringify(values);
$.ajax({
url: "get_buildings.php",
type: 'POST',
data: JSON ,
success: function(){
alert("Success!")
}
});
PHP Code:-
<?php
$json = $_POST['JSON'];
$p = json_decode(JSON);
$file = fopen('test.txt','w+');
fwrite($file, $p);
fclose($file);
echo 'success?';
?>
Two flaws:
a) You're not sending your data correctly - it's lacking a field name:
data: {data: JSON}
^^^^---this will be the key in PHP's $_POSt
b) You're using invalid constants in PHP and not even decoding what MIGHT have been the passed in data. You should have:
$p = json_decode($_POST['data']);
^^^^--matching what you have in the `data` field in Javascript.

Get json value on any php page

I am creating json object but can't access its value in php.I am trying to access json object in php and assign that object to php variable.My js code is
var arr= [];
var data={ "tab" : 'system' };
jObjArr = arr.push(data);
var JSONstr = JSON.stringify(jObjArr);
what i am missing ?
I try to get tab value on that page in php.
Try to pass simple object rather than sending an array:
function send_me() {
//var arr = [];
var data = { "tab": 'system' };
//jObjArr = arr.push(data);
//var JSONstr = JSON.stringify(data);
$.ajax({
url: "a_blank.php",
type:"post",
data: data,
success: function (response) {
alert(response);
}
});
}
On php page side simply get as:
if($_SERVER["REQUEST_METHOD"]=="POST")
{
print_r($_POST['tab']);
die();
}

jquery passing variables to php file

acctually i am not familier much with jquery.. i got this jquery script this is passing variables to the file which is showing data in json format.. but here i'm unable to show that data..plz see this piece of code
$(document).ready(function() {
var globalRequest = 0;
$('#search').bind('keyup', function(event) {
if (event.keyCode == 13) {
searchAction();
}
});
$('#search-link').bind('click', function(event) {
searchAction();
});
var searchAction = function() {
var value = $('#search').val();
var cat = $('#category').val();
var country = $('#country').val();
var page = $('#page').val();
var resultContainer = $('#results');
if (value.length < 3 && globalRequest == 1) {
return;
}
_gaq.push(['_trackEvent', 'Search', 'Execute', 'Page Search', value]);
globalRequest = 1;
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: "q="+value+"&category="+cat+"&country="+country+"&page="+page,
success: function(data){
globalRequest = 0;
resultContainer.fadeOut('fast', function() {
resultContainer.html('');
console.log(data.length);
for (var x in data) {
if (!data[x].price)
data[x].price = 'kA';
if (!data[x].img)
data[x].img = 'assets/images/no.gif';
var html = '<div class="res-container">';
html += '<h2>'+data[x].Title+'</h2>';
html += '<img src="'+data[x].img+'">';
html += '<h3>Price: '+data[x].price+'</h3>';
html += '</div>';
resultContainer.append(html);
}
resultContainer.fadeIn('fast');
});
}
});
};
});
in search.php data is in simple echo.. how to get data from search.php and show here..
sorry for bad english
First,
you shouldn't concatenate your parameters but use a hashmap:
$.ajax({
url: "search.php",
dataType: 'json',
type: 'GET',
data: {
q : value,
category : cat,
country : country,
page : page }
As your method is (type: 'GET'), just use the ($_GET[param] method) in the php file
<?php
$value = htmlentities($_GET['q']);
$category = htmlentities($_GET['category ']);
$country = htmlentities($_GET['country ']);
In the js callback function, this is how you log the whole response ('something' is a tag) :
success: function(data){
var $xml = $(data);
console.log($xml); // show the whole response
console.log($xml.find('something')); // show a part of the response : <something>value</something>
});
It is a bit hard to understand what your problem is but my guess is that you need to json encode the data before echoing it back in search.php.
simplified example......
eg.
<?php
$somevar = $_GET['a']
$anothervar = $_GET['b']
//Do whatever
$prepare = array('a'=>$result1,'b'=>$result2) //etc..
$json = json_encode($prepare);
echo $json;
exit();
?>
Then you can access the results in the javascript with:
success: function(data){
var obj = $.parseJSON(data);
alert(data.a);
$("#some_element").html(data.b);
}

Categories