September 15, 2013

Sending json with php and parse it in ajax call

User2589904’s Question:

I don’t have experience using JSON with php and ajax and I need your help.

I have a php page that validates user input… Before using json, I used to store them in an array. I was able to parse the json when I store my values in an array like this
$data = array(“success”=>true, “msg”=>”my masg”);
json_decode($data);

and then in my ajax call on success function I data.success and data.msg

How do I store multipe msgs or errors in my array and parse them in my ajax call?
here is my code

here I want to validate user input and I would like to validate many fields

    if(isset($_POST['txt_username']) &&($_POST['txt_username']!=""))
    {
        $username =trim( $_POST['txt_username']);
        $username  = filter_input(INPUT_POST, 'txt_username',
                    FILTER_SANITIZE_STRING);
    }
    else
    {

             }

So how do I do it in the else statement?

here is my ajax call

 $.ajax({       
            type: "POST",
            dataType: "json",
            cache: false,
            data: {txt_username:$("#username").val(), txt_password:$("#password").val()},

            beforeSend: function(x) {

                if(x && x.overrideMimeType) {

                    x.overrideMimeType("application/json;charset=UTF-8");
                }

            },

            url: 'proccessing_forms/admin_login.php',

            success: function(data) {

                // parse the data
            }
    });


    }

You can use multidimensional arrays for this:

$msg = array("success" => array(), "error" => array());

// ... DO you processing on if and else

//When you need to add to an success do
$msg['success'][] = "My Success";

//When you need to add to an error do
$msg['error'][] = "My error";


echo json_encode($msg); exit;

On the ajax’s success event, you can access both of these variables individually.

success: function(data) {
    var errors = data.error;
    var succesess = data.success

    //Process each msg
    $.each(errors, function(index, msg) {
         console.log(msg);
    });
}
August 4, 2012

Parsing JSON array of objects with jQuery

Question by Christopher Buono

What I am trying to do is parse this JSON: http://www.theunjust.com/test/container.php

And just get it to show at this point…

Here is my current code(its all jacked up)

$(document).ready(function(){
    var jsonurl = "container.php";
  $.getJSON(jsonurl, function(data) {         
    $.each(data.encompass,function(i,valu){
    var content,
    cont = '',
    tainers = valu.containers;

  $.each(tainers, function (i) {
    var tid = tainers[i].TID,
    top = tainers[i].Top,
    cat = tainers[i].Category,
    date = tainers[i].Date,
    icon = tainers[i].Icon,
    clink = tainers[i].ContainerLink,
    uid = tainers[i].UniqueID;

        cont += '<a href="' + clink + '">' + uid + '</a> ';
        $('ul').append('<li>' + tid + ' - ' + top + ' - ' + cat + ' - ' + date + ' - ' + icon + ' - ' + clink + ' - ' + uid + ' (' + cont + ')</li>');
    }); 
  }); 
}); 
});

I know that the code doesn’t make sense, this is more of a learning experience for me rather than a functioning tool. The issue may be in the JSON data itself, if that is the case, what stackoverflow web service post would you recommend?

What I eventually aim to do is run multiple web services and combine them… So that container.php loads and has all of the information that is required for a wrapping div, then entries.php loads and fills the divs that was generated by containers..

I’m currently learning jQuery and Honestly, I’m not to this level yet, but I am getting there pretty quick.

I really appreciate the help, and would like if you could point me in the direction to become a JSON parsing pro!

Answer by Starx

containers contain single node. So simply use

$.each(tainers, function (i, v) {
    var tid = v.TID,
    top = v.Top,
    cat = v.Category,
    date = v.Date,
    icon = v.Icon,
    clink = v.ContainerLink,
    uid = v.UniqueID;

    cont += '<a href="' + clink + '">' + uid + '</a> ';
    $('ul').append('<li>' + tid + ' - ' + top + ' - ' + cat + ' - ' + date + ' - ' + icon + ' - ' + clink + ' - ' + uid + ' (' + cont + ')</li>');
});
March 30, 2012

read name and value from every define('NAME','VALUE'); inside a .php file

Question by elcodedocle

I’m implementing a php interface to process a .php file containing a bunch of define sentences defining constants with text values to translate by somebody.

The input is parsed sentence by sentence and shown in the interface to the translator who will input the translation in a html textarea and send it to the server

By the end of the process an output file would be generated, identical to the input .php file, only with the define values translated.

E.g. processing an input file ‘eng.php’ like this:

<?php
define ("SENTENCE_1", "A sentence to translate");
?>

would give the translated output file ‘spa.php’ like this:

<?php
define ("SENTENCE_1", "The same sentence translated to spanish");
?>

For this I would like to know:

1) What is the best way to parse the input file to get the constant names and values in an array? (Something like $var[0][‘name’] would be “SENTENCE_1” and $var[0][‘value’] would be “A sentence to translate”)

2) Would it be possible to get the translation from google translator shown in the input textarea as a suggestion to edit for the person who is translating it? How? (I read google translator api v1 is no longer available and v2 is only available as a paid service. Are there any free alternatives?)

Answer by Starx

Use get_defined_constants() to get the list of all the defined constants.

To get userdefined constant specially

$allconstants = get_defined_constants(true);
print_r($allconstants['user']);
March 10, 2012

Convert dot syntax like "this.that.other" to multi-dimensional array in PHP

Question by Bryan Potts

Just as the title implies, I am trying to create a parser and trying to find the optimal solution to convert something from dot namespace into a multidimensional array such that

s1.t1.column.1 = size:33%

would be the same as

$source['s1']['t1']['column']['1'] = 'size:33%';

Answer by Starx

Although pasrse_ini_file() can also bring out multidimensional array, I will present a different solution. Zend_Config_Ini()

$conf = new Zend_COnfig_Ini("path/to/file.ini");
echo $conf -> one -> two -> three; // This is how easy it is to do so
//prints one.two.three
...

Please fill the form - I will response as fast as I can!