I have the following code which pass data formatted as JSON to PHP through Ajax, but the PHP code doesn't print out the result.
var array_str_idnum = [];
for (var i=0;i<2;i++) {
array_str_idnum[i] = [];
}
$('#movetoset').click(function() {
if ($('#selectsett').val() === 'General') {
}
for(j=0;j< (array_str_idnum[0]).length;j++) {
if((document.getElementById('check' + array_str_idnum[0][j]).checked) && (array_str_idnum[1][j] != "moved")) {
document.getElementById('imagediv' + array_str_idnum[0][j]).style.display = 'none';
array_str_idnum[1][j] = "moved";
index = ((array_str_idnum[0]).length - 1 - j) + '';
var str = $("#complicated").serialize() + "&myindex=" + encodeURIComponent(index) ;
var desc_str = document.getElementById('textarea' + array_str_idnum[0][j]).value;
str = str + "&mydescription=" + encodeURIComponent(desc_str);
$.ajax({
type: "POST",
url: "addtoset.php",
data: str,
cache: false,
success: function(msg) {
$("#formstatus").ajaxComplete(function(){$(this).fadeIn("slow").html(msg + '<br /><br />')});
$("#formstatus").append(msg);
}
});
}
}
mydata = JSON.stringify(array_str_idnum);
$.ajax({
type: 'post',
cache: false,
url: 'parser.php',
data: {myJson: mydata},
success: function(msg) {
$("#formstatus").ajaxComplete(function() { $(this).fadeIn("slow").html(msg) });
}
});
});
Here is my PHP code:
$decoded = json_decode($_POST['myJson'],true);
// do something with data here
echo "decoded = $decoded[1][0]";
What's wrong with the code?
I think you want to fix your PHP code like others suggested, like so:
<?php
if ( !empty($_POST['myJson']) && strlen($_POST['myJson']) > 0 )
{
$decoded = json_decode( $_POST['myJson'], true );
// Echo out the JSON onject as a JavaScript variable.
echo "decoded = {$decoded[1][0]};";
}
else
{
// Echo out the JSON onject as a JavaScript variable.
echo "decoded = null;";
}
?>
Here is your JavaScript code with some minor suggestions:
<script type="text/javascript">
$( document ).ready(function()
{
var array_str_idnum = [];
// Init the array with two elemsnts that contain empty literal arrays.
for ( var i = 0; i < 2; i++ )
{
array_str_idnum[ i ] = [];
}
$( "#movetoset" ).click(function()
{
var $checkbox, str, desc_str, elementSuffix;
// I believe the code in here was removed for privacy reasons.
// I also believe it populats 'array_str_idnum' with some values of some kind.
if ( $("#selectsett").val() === "General" )
{
// ...
}
for ( var i = 0; i < (array_str_idnum[0]).length; i++ )
{
elementSuffix = array_str_idnum[ 0 ][ i ];
// Grab the checkbox.
$checkbox = $( "#check" + elementSuffix );
if ( $checkbox.checked && (array_str_idnum[1][i] != "moved") )
{
// Hide the image.
$( "#imagediv" + elementSuffix ).css({ "display": "none" });
// Indicate that this one is now moved, so do NOT process it again.
array_str_idnum[ 1 ][ i ] = "moved";
index = ( (array_str_idnum[0]).length - 1 - i ) + '';
// Setting str here will reinitialize it
str = $( "#complicated" ).serialize() + "&myindex=" + encodeURIComponent( index );
desc_str = $( "#textarea" + elementSuffix ).value;
str = str + "&mydescription=" + encodeURIComponent( desc_str );
// Bad idea to put ajax call in a loop.
$.ajax({
"type": "POST",
"url": "addtoset.php",
"data": str,
"cache": false,
"success": function( msg )
{
$( "#formstatus" ).ajaxComplete(function()
{
$( this ).fadeIn( "slow" ).html( msg + "<br /><br />" );
});
$( "#formstatus" ).append( msg );
}
});
}
}
mydata = JSON.stringify( array_str_idnum );
$.ajax({
"type": "POST",
"cache": false,
"url": "parser.php",
"data": { myJson: mydata },
"success": function( msg )
{
$( "#formstatus" ).ajaxComplete(function()
{
$( this ).fadeIn( "slow" ).html( msg )
});
}
});
});
});
</script>
Maybe your only problem is the echo statement. You'll have to change that to
echo "decoded = ".$decoded[1][0];
or
echo "decoded = {$decoded[1][0]}"; //
This is because PHP only notices "normal" variables in double-quoted strings. For array elements (or object properties) you'll have to use curly braces around the variable or use string concatenation.
Related
I want autocomplete value from two columns of MySql database table, One column have multiple similar values, In autocomplete window in case of similarity it should only display one of the similar values. And after select it should not be suggested in autocomplete window in next row.
HTML
<tr>
<td><input type="text" data-type="aTeam" id="team_1" class="team"></td>
<td><input type="text" id="score_1" ></td>
</tr>
<button type="button" id="addRow">Add Row</button>
JS
$(document).on('focus','.team',function(){
var type = $(this).data('type');
if(type ==='aTeam' )autoTypeNo= 0;
$(this).autocomplete({
source: function( request, response ) {
$.ajax({
url : 'fetch.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: type
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item.aTeam,
value: item.aTeam,
data : item
};
}));
}
});
},
autoFocus: true,
minLength: 1,
select: function( event, ui ) {
id_arr = $(this).attr('id');
id = id_arr.split("_");
$('#team_'+id[1]).val(ui.item.data.aTeam);
$('#score_'+id[1]).val(ui.item.data.score);
}
});
});
//add row
var i=$('table tr').length;
$("#addRow").on('click',function(){
html = '<tr>';
html += '<td><input type="text" data-type="aTeam" id="team_'+i+'" class="team"></td>';
html += '<td><input type="text" id="score_'+i+'"></td>';
html += '</tr>';
$('table').append(html);
i++;
});
PHP
<?php
require_once("config.php");
if(!empty($_POST['type'])){
$type = $_POST['type'];
$name = $_POST['name_startsWith'];
$query = $db->prepare("SELECT aTeam, bTeam FROM teams where UPPER($type) LIKE '".strtoupper($name)."%' limit 10 ");
$query->execute();
$data= array();
$i = 0;
while ($row = $query->fetch(PDO:: FETCH_ASSOC)) {
$data[$i]['aTeam'] = $row['aTeam'];
$data[$i]['bTeam'] = $row['bTeam'];
$data[$i]['score'] = $row['score'];
++$i;
}
echo json_encode($data);
}
Try this: (read the // {comment here} and just compare the code with yours to see what changed)
$(document).on('focus','.team',function(){
let type = $(this).data('type');
// `autoTypeNo` isn't used anywhere, so I commented out this.
//if(type ==='aTeam' )autoTypeNo= 0;
$(this).autocomplete({
source: function( request, response ) {
$.ajax({
url : 'fetch.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: type
},
success: function( data ) {
let selected = [],
uniques = [],
choices = [];
$('tr .team[id^="team_"]').each(function(){
let value = this.value.trim().toLowerCase();
if (value && selected.indexOf(value) < 0) {
selected.push(value);
}
});
data.forEach(item => {
let value = item.aTeam.trim().toLowerCase(),
value2 = item.bTeam.trim().toLowerCase();
if (uniques.indexOf(value) < 0 && selected.indexOf(value) < 0) {
choices.push({
label: item.aTeam,
value: item.aTeam,
data: item,
type: 'aTeam'
});
uniques.push(value);
}
if (uniques.indexOf(value2) < 0 && selected.indexOf(value2) < 0) {
choices.push({
label: item.bTeam,
value: item.bTeam,
data: item,
type: 'bTeam'
});
uniques.push(value2);
}
});
response(choices);
}
});
},
autoFocus: true,
minLength: 1,
select: function( event, ui ) {
// Strips the 'team_' part, leaving just the number.
let id_num = $(this).attr('id').substring(5);
$(this).val(ui.item.value);
$('#score_' + id_num).val(ui.item.data.score);
$(this).attr('data-type', ui.item.type); // Change to the correct type?
// Cancels default action, so that the above `jQuery.val()` call works.
return false;
}
});
});
//add row
// 'i' is too generic, so I renamed it to 'row_num'.
var row_num=$('table tr').length;
$("#addRow").on('click',function(){
// Increment before used.
row_num++;
let html = '<tr>';
html += '<td><input type="text" data-type="aTeam" id="team_' + row_num + '" class="team"></td>';
html += '<td><input type="text" id="score_' + row_num + '"></td>';
html += '</tr>';
$('table').append(html);
// Optional, but I like to focus on the `input` in the row that was just added.
$('#team_' + row_num).select();
});
UPDATE
I updated the JS code (above).
And note that for the PHP part, I changed the $query from:
$query = $db->prepare("SELECT aTeam, bTeam FROM teams where UPPER($type) LIKE '".strtoupper($name)."%' limit 10 ");
to:
$query = $db->prepare("SELECT aTeam, bTeam, score FROM teams where ( aTeam LIKE '".$name."%' OR bTeam LIKE '".$name."%' ) limit 10 ");
because without the OR bTeam LIKE '".$name."%', for example if you typed "d" and there were no aTeam starting with "d", then you know what would happen..
I wrote a php script which accept POST request from ajax and give the response back. All working fine. But the receiving string split letter by letter I can't understand what is the reason.
Here is my AJAX code,
$("#btn").click(function(){
console.log($("#search_bar").val());
var dataV;
var htmlText = '';
var containerbootsrap = '';
var filename = '';
var index_no;
$.ajax({
type: "POST",
crossDomain: true,
url: "http://localhost:8090/ontology/setText",
data: $("#search_bar").val(),
contentType: 'text/plain',
// dataType: "json",
success: function( data, textStatus, jQxhr ){
console.log('data');
console.log(data);
for( var item in data) {
console.log ("item: " + item);
console.log ("data: " + data[item]);
index_no = data[item];
// htmlText += '<div class="div-conatiner">';
// htmlText += '<p class="p-name"> Name: ' + data[item] + '</p>';
// htmlText += '<img class="imageload" src="' + data[item] + '" />';
// htmlText += '</div>';
// filename = data[item].replace(/^.*[\\\/]/, '')
$.ajax({
data: 'index_no=' + index_no,
url: 'retrivedata.php',
method: 'POST', // or GET
dataType: 'json',
success: function(msg) {
console.log(msg);
for(var item in msg){
console.log ("item: " + item);
console.log ("data: " + msg[item]);
}
$('#home').hide();
containerbootsrap += '<div class = "container" id="search_container">';
containerbootsrap += '<div class = "row homepage">';
containerbootsrap += '<div class = "col-md-5 col-md-offset-3">';
containerbootsrap += '<a href="#" class="thumbnail">';
containerbootsrap += '<img class="imageload" src="' + msg + '" />';
containerbootsrap += '<h3 id="video_name"> ' + filename + ' </h3>'
containerbootsrap += '</a>';
containerbootsrap += '</div>';
containerbootsrap += '</div>';
containerbootsrap += '</div>';
$('body').append(containerbootsrap);
}
});
// $.post('retrivedata.php', { num: 5 }, function(result) {
// alert(result);
// });
// $('#home').hide();
}
// $('body').append(containerbootsrap);
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( jqXhr );
alert(jqXhr)
}
});
});
php code is below
<?php
$index_no = $_POST["index_no"];
// echo $index_no * 2;
include('dbConnection.php');
$query = mysql_query("SELECT * FROM video_data WHERE index_no = $index_no");
while ($row = mysql_fetch_assoc($query)) {
$imagePath = $row['thumbnail_url'];
$videoPath = $row['video_url'];
// echo $imagePath;
// echo $videoPath;
echo json_encode($imagePath);
}
?>
I need the output as : 'imagepath'
but it is giving the output as split letter by letter.
here is the real output
Output
but i need the output in one line. like /video_frames/bb/frame136.jpg
please help me to figure out where I am going wrong.
Well, in the php code where you're returning the value you need to specify an array not an string. The variable there $imagePath seems to be a string. You can do something like this.
echo json_encode(array('result' => $imagePath));
This will give you your result in the 'result' key. You can parse it and use it.
You need to parse the returned JSON string into an array. One way to do it is by adding data = $.parseJSON(data) in the ajax success callback (highlighted below). I was able to recreate the same thing you're seeing and adding this line fixed it. Hope this helps. parseJSON()
...
success: function( data, textStatus, jQxhr ){
console.log('data');
console.log(data);
data = $.parseJSON(data);
for( var item in data) {
console.log ("item: " + item);
console.log ("data: " + data[item]);
index_no = data[item];
...
Better way to check the type of value in variable you are getting first like
data = '{"name": "Bhushan"}' //string value
data = {name: "Bhushan"} //object value
//for testing you can use either, this will make it unbreakable for this context
if(typeof(data) == 'string')
{
data = JSON.parse(data)
}
//rest of code
This will give your module good stability otherwise you may get json parse unexpected token o.
I have this ajax request that iterates through a store and deletes all selected records.
code
Ext.Ajax.request({
url: 'system/index.php',
method: 'POST',
params: {
class: 'LicenseFeatures',
method: 'delete',
data: Ext.encode({
feature_id: ( function(){
var e = "";
var sel = Ext.getCmp('featureGrid').getSelection();
var c = 0;
for( var i in sel ) {
var x = ( c == 0 ) ? e = sel[i].data.feature_id : e += "," + sel[i].data.feature_id;
c++;
}
return e;
})()
})
},
success: function( response ){
Ext.MessageBox.alert( 'Status', 'Record(s) has been deleted.' );
Ext.getStore('LicenseFeaturesStore').reload();
},
failure: function(){
Ext.MessageBox.alert( 'Status', 'Failed to delete records.' );
}
});
Currently the code retrieves 1 id from the grid and deletes it. What I need to do is get two Id's from the grid as I need to run a specific sql to the database. The sql needs two inputs, here is the sql
public function delete( $vars ){
$sql = "DELETE FROM `LicenseFeatures` WHERE feature_id in({$vars->data->feature_id}) AND license_id in({$vars->data->license_id})";
if( $result = $vars->db->query( $sql ) ) {
echo json_encode( array( "success" => true,"sql"=>$sql ) );
} else {
echo json_encode( array( "success" => false ) );
}
}
Try and change the data property to this.
data: Ext.encode(( function(){
var feature_id,
licence_id;
var sel = Ext.getCmp('featureGrid').getSelection();
var c = 0;
for( var i in sel ) {
if (c == 0) {
feature_id = sel[i].data.feature_id;
licence_id = sel[i].data.licence_id;
} else {
feature_id += "," + sel[i].data.feature_id;
licence_id += "," + sel[i].data.licence_id;
}
c++;
}
return {
feature_id: feature_id,
licence_id: licence_id
};
})())
I'm new Jquery and AJAX and I've really been struggling with the syntax I've been trying to use other tutorials as reference but nothing seems to work. I feel I have the right idea but syntax is wrong somewhere please help.
Here is the Ajax side
var var_numdatacheck = <?php echo $datacheck; ?>;
var var_numcheck = parseInt(var_numdatacheck);
function activitycheck(){
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var json = eval('(' + data + ')');
$('#datacheck').html(json['0']);
var var_numcheck = parseInt(msg);
//setTimeout('activitycheck()',1000)},
error:function(msg) {
console.log(msg);
}
});
}
$(document).ready(function() {
activitycheck();
});
Here is the php the AJAX calls
<?php
require "dbc.php";
$function = $_POST['function'];
$datacheck = $_POST['datacheck'];
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$update= mysql_fetch_array($request);
$updateid = $update['id'];
$updatecheck = mysql_num_rows($request);
$data = array();
if ($function == $datacheck){
echo $updatecheck;
echo $datacheck;
}
if ($function == "3test" && $updatecheck > $datacheck ) {
$updatesearch="SELECT * FROM Feedtest WHERE id = '$updateid' ORDER BY id DESC";
$updatequery = mysql_query($updatesearch);
$data['id'] = $updateid;
while ($row = mysql_fetch_array($updatequery))
{
?>
<?php $data[]= $row['First Name']; ?>
<?php
}
echo json_encode($data);
}
?>
</div>
</ul>
first of all ,always use JSON.parse(data) instead of eval.It is considereda a good practice.
second thing is always try to debug your code by checking it in console or alerting.In your context,this is what is happening-:
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var data = eval('(' + data + ')');
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i=0;i< data.length;i++)
{
alldata += "<li>"+data[i][0]+"<li><hr>";
}
$('#datacheck').html(alldata);
});
}
For JSON.parse:
success: function(data) {
var data = JSON.parse(data);
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i in data)
{
alldata += "<li>"+data[i].First Name+"<li><hr>";
}
$('#datacheck').html(alldata);
});
I need to extract the URL's from the php datas, how can i achieve this?
PHP
$query = 'SELECT * FROM picture LIMIT 3';
$result = mysql_query($query);
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url.=$rec['pic_location'].";";
}
echo json_encode($url);
Ajax
<script type="text/javascript">
$(document).ready(function() {
$(".goButton").click(function() {
var dir = $(this).attr("id");
var imId = $(".theImage").attr("id");
$.ajax({
url: "viewnew.php",
data: {
current_image: imId,
direction : dir
},
success: function(ret){
console.log(ret);
var arr = ret;
alert("first: " + arr[0] + ", second: " + arr[1]);
alert(arr[0]);
$(".theImage").attr("src", +arr[0]);
if ('prev' == dir) {
imId ++;
} else {
imId --;
}
$("#theImage").attr("id", imId);
}
});
});
});
</script>
the alert message isn't working its just printing H T ( i think these are http://... )
You're returning a string which is not parsed as JSON.
Just add dataType: "json" to the ajax settings.
And since you're reading it as an array in your javascript you should return it like so:
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url[] = $rec['pic_location'];
}
You are sending a string in your PHP and expecting an array as response in javascript. Change you PHP to
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url[] = $rec['pic_location'];
}
And javascript to
$.ajax({
url: "viewnew.php",
dataType: "JSON",
data: {
current_image: imId,
direction : dir
},
success: function(ret){
console.log(ret[0]);
var arr = ret;
alert(arr);
alert("first: " + arr[0] + ", second: " + arr[1]); // THIS IS NOT WORKING!!!!
if ('prev' == dir) {
imId ++;
} else {
imId --;
}
$("#theImage").attr("id", imId);
}
});