Jquery ajax return null - php

I am using the Jquery function,
function ajax_fun(id,val)
{
$.ajax({
type: "GET",
url: "data.php",
dataType: "json",
data: { pid: 1, cart_id: id, val: val },
success: function (returndata){
console.log(returndata);
}
});
}
Call
ajax_fun(1,100);
data.php
<?php
if(isset($_GET['pid']) && $_GET['pid']==1)
{
$cart_id = $_GET['cart_id'];
$val = $_GET['val']+0.06;
$arr = array('cart_id'=> $cart_id, 'total' => $val);
json_encode($arr);
}
?>
Console returns 'null' . It didn't return cart_id and total.
Can anyone help?
.

json_encode($arr);
shoule be
echo json_encode($arr);
You forget to echo the result.
Full code:
<?php
if(isset($_GET['pid']) && $_GET['pid']==1) {
$cart_id = $_GET['cart_id'];
$val = $_GET['val']+0.06;
$arr = array('cart_id'=> $cart_id, 'total' => $val);
echo json_encode($arr); // write echo before json_encode($arr)
}
?>

RE-Write this line as...
echo json_encode($arr);

You need to add 'echo' before json_encode which return the data
<?php
if(isset($_GET['pid']) && $_GET['pid']==1)
{
$cart_id = $_GET['cart_id'];
$val = $_GET['val']+0.06;
$arr = array('cart_id'=> $cart_id, 'total' => $val);
echo json_encode($arr);
}
?>

Related

Beforeunload Function is Not working And not updating the records after unload

Here is my code
function myfoo() {
$.ajax({
type: "POST",
url: "update.php",
dataType: 'json',
async: false,
data: {
Eventid: 1,
Seats: 'Seats'
},
success: function(r) {}
});
}
$(window).on('beforeunload', function() {
return 'Are you sure you want to leave?';
});
$(window).on('unload', function() {
console.log('calling ajax');
myfoo();
});
update.php code
<?php
session_start();
include 'conn.php';
if(isset($_SESSION['Seats'])) {
$seatS=$_SESSION['Seats'];
$Eventid=$_SESSION['Eventid'];
$cats = explode(" ", $seatS);
$cats = preg_split('/,/', $seatS, -1, PREG_SPLIT_NO_EMPTY);
foreach($cats as $key => $cat ) {
$cat = mysql_real_escape_string($cats[$key]);
$cat = trim($cat);
if($cat !=NULL) {
$stmt = $con->prepare('UPDATE fistevent SET `Status`=" " where `Event_Id`=? AND `seats`="'.$cat.'" AND `Status`="Hold" ');
$stmt->bind_param("s", $_SESSION['Eventid']);
$stmt->execute();
session_destroy();
}
}
}
?>
The AJAX data: parameters are put in $_POST, not $_SESSION.
You can't use mysql_real_escape_string if you're using mysqli. You don't need to escape parameters when you're using bind_param(). And you can use explode() instead of preg_split(), since there's no regular expression pattern in your delimiter; array_filter() can be used to remove blank entries.
<?php
include 'conn.php';
if(isset($_POST['Seats'])) {
$seatS=$_POST['Seats'];
$_SESSION['Seats'] = $seatS;
$Eventid=$_POST['Eventid'];
$_SESSION['Eventid'] = $Eventid;
$cats = array_filter(array_map('trim', explode(',', $seatS)));
$stmt = $con->prepare('UPDATE fistevent SET `Status`=" " where `Event_Id`=? AND `seats`= ? AND `Status`="Hold" ') or die($con->error);
$stmt->bind_param("ss", $_POST['Eventid'], $cat);
foreach($cats as $key => $cat ) {
$stmt->execute();
}
}
?>

Passed array to php from jquery with ajax value just shows Array not actual array value

Please can someone tell me where I'm going wrong
js file:
//Checkboxid is an array which is populated using .push();
$.ajax({
type: "POST",
url: "test.php",
dataType: 'html',
data: { data: Checkboxid },
success: function (data) {
console.log(data);
}
});
test.php:
<?php
$test = $_POST['data'];
for ($i = 0; $i < count($test); ++$i) {
echo $test[$i];
}
foreach($test as $val) {
echo $val;
}
?>
console.log displays:
ArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArrayArray
Your $test variable is a two-dimensional array. Try this
<?php
$test = $_POST['data'];
foreach($test as $arr) {
foreach($arr as $val){
echo $val;
}
}
?>

Send data with AJAX and receive in PHP

I'm having a script which is generating a JSON array, based values user have selected. These values are sent as a JSON with AJAX to a PHP script which should receive this values and process it.
What could be wrong?
JSON (That is sent):
[{
"Pages":
{"name":" Page Name 1",
"id":"252456436636644"}
},
{
"Pages":{
"name":" Page Name 2",
"id":"345345435435232"
}
}]
Jquery:
var json_pages = JSON.stringify(publish);
$.ajax({
url: "post.php",
type: "post",
data: { PublishToPages: json_pages },
success: function(){},
error: function(){}
});
Problem is that the JSON I recieve from PHP isn't getting the data,
if($_POST['PublishToPages']) {
$json = $_POST['PublishToPages'];
$array = json_decode($json, true);
foreach($array as $item) {
$page_id = $item['Pages']['id'];
echo $page_id;
}
}
If I manually put in the JSON in the PHP script like this it Works,
if ($_POST['PublishToPages']) {
$json = '[{"Pages":{"name":" Page Name","id":"234545355345435"}},{"Pages":{"name":" Page Name 2","id":"345345435435435435"}}]';
$array = json_decode($json, true);
foreach($array as $item) {
$page_id = $item['Pages']['id'];
echo $page_id;
}
}
Try using this:
if($_POST['PublishToPages']) {
$json = $_POST['PublishToPages'];
$items = array();
$array = json_decode($json, true);
foreach($array as $item) {
$page_id = $item['Pages']['id'];
$items[] = $page_id;
}
echo json_encode($items);
}
Try this
$.ajax({
url: "post.php",
type: "post",
dataType:"json",
data: { PublishToPages: json_pages },
success: function(){},
error: function(){}
});
Thanks for all input! I figured it out using the var_dump and realized it was encoding error so added stripslashes(); and it worked! :)
if ($_POST['PublishToPages']) {
$json = stripslashes($_POST['PublishToPages']);
$array = json_decode($json, true);
foreach($array as $item) {
$page_id = $item['Pages']['id'];
echo $page_id;
}
}

How to loop retrieved much data in view (codeigniter)

how to retrieve much data in view (codeigniter) using while(). if I use foreach, I can't get the desired result. this is my code:
//my view home.php
$(document).ready(function(){
$('#check').click(function(event){
event.preventDefault();
var form_data = {
name: "xxxx"
};
$.ajax({
url: 'http://localhost:8000/jqjx/index.php/cont/getname',
type: 'POST',
async : false,
data: form_data,
dataType: 'html',
success: function(resp){
$('#content').html(resp);
}
});
return false;
});
});
//my controller cont.php
public function getname()
{
$data = array();
$namex = $this->input->post('name');
if($q = $this->my_model->detail_data($namex))
{
$data['data_detail'] = $q;
$this->load->view('tamp_page', $data);
}
}
my helper page (view) tamp_page.php
<?php
if(isset($data_detail))
{
foreach ($data_detailas $row) {
echo $row['name']."<br/>";
echo $row['birthday']."<br/>";
}
}
?>
if I use :
<?php
if(isset($data_detail))
{
echo $name_data['id_transactions'] . "<br/>";
echo $name_data['goods'] . "<br/>";
}
?>
it's still work but just for 1 data result. so how I can loop more much data.. thanks..
<?php
if(isset($data_detail))
{
foreach ($data_detail as $row)
{
echo $row['name']."<br/>"; //$row['name] was not properly closed. single quote(') was missing
echo $row['birthday']."<br/>";
}
}
?>
Just basic use of foreach:
if(isset($data_detail)){
foreach ($data_detailas as $row) {
echo $row['name'] . "<br/>";
echo $row['birthday'] . "<br/>";
}
}

Ajax call keeps returning null

My js:
$('#select').change(function() {
var name = $(this).val();
$.ajax({
type: "POST",
url: "data/grab.php",
data: { type: "hops", name: name },
dataType: "json",
success: function(data) {
alert(data);
var aa = data['aa'];
$('#hops-aa').val(aa);
}
});
});
grab.php
<?php
$type = $_POST['type'];
$name = $_POST['name'];
if ($type == 'hops') {
$result = $name;
}
$result = json_encode($result);
return $result;
I added the alert() in the ajax call to double check what I'm getting back from the script, and it's always null. Anything I'm missing?
You need to actually echo or print the $result. In PHP using return from the file scope does not send the returned value to the output stream.
You use echo to print out the results in PHP, not return:
echo $result;
(As previous answers stated)
You need to echo/print the $result variable.
<?php
$type = $_POST['type'];
$name = $_POST['name'];
if ($type == 'hops') {
$result = $name;
}
$result = json_encode($result);
echo $result; // return $result;
?>

Categories