1

Here is my jQuery code. I'm having problems correctly formatting the data in JSON, and the request is failing. What do I need to do to send it correctly, and be able to decode it on the server?

$(".comment_button").click(function() {

    var chkarray = [];
    $('.webInput:checked').each(function(){
        chkarray.push($(this).val());
    });

    var dataString = "content="+ chkarray;

    if(test=='')
    {
        alert("Please check checked");
    }

    $.ajax({
        type: "POST",
        url: "chkoutput.php",
        dataType:'json',
        data: dataString,
        cache: false,
        success:
            function(html)
            {
                $("#test_area").after(html);
                document.getElementById('content').value='';
                $("#flash").hide();
            }
    });

This is the server-side code:

$chk_out = $_POST["content"];
echo json_encode($chk_array);
nbrooks
  • 18,126
  • 5
  • 54
  • 66
  • Your server-side code won't work on two points: 1) A JS array is something else then a PHP array 2) Do you expect `$chk_array` to appear magically? – 11684 Sep 30 '12 at 10:21
  • as you mentioned you don't know jquery first of all check for javascript errors, in any of debuging tools like mozila firebug or any thing handy and post them so one can help better. – Rupesh Patel Sep 30 '12 at 10:25
  • *"It doesn't work"* [doesn't explain the problem](http://stuck.include-once.org/#help3) enough. You need to elaborate on your input, expected and actual outcomes, or concretise error messages. – hakre Sep 30 '12 at 10:28
  • @RupeshPatel I have rolled back your edits due to the fact that your edit actually made more errors in the question and also changed the meaning of the question also the code formatting was horrid also it introduced spelling mistakes. – Sammaye Sep 30 '12 at 11:07
  • the input is My problem is the jquery array can't send to php, and I don't know how can I echo out my jquery array in php page and ajax – user1266514 Oct 01 '12 at 14:22

3 Answers3

1
var dataString=JSON.stringify(chkarray)   ;
  $.ajax({
        type: "POST",
        url: "chkoutput.php",
        dataType:'json',
        data: {"dataString":dataString},
        cache: false,
        success:
            function(html)
            {
                $("#test_area").after(html.data);
                document.getElementById('content').value='';
                $("#flash").hide();
            }

in server-side

$chk_out = json_decode(dataString);
$data=$chk_out->data;//$data is data which you added to array or we can say
 // $chk_out["data"]
StaticVariable
  • 5,253
  • 4
  • 23
  • 45
1

try this

$.ajax({
   type: "POST",
   url: "BACKEND.php",
   timeout: 8000,
   data: "var1=" + myVar,
   dataType: "json",
   error: function(){
     $("#DIVID").html("<div class='error'>Error!</div>");
   },  
   success: function(jsonObj){
     $("#DIVID").html(jsonObj.mydata);
   }
 });


PHP Array:
$data['mydata'] = $myData;

or follow the step below

  1. Stringify your javascript object (json) with var st = JSON.stringify(your_object);

  2. Pass your POST data as "string" (maybe using jQuery: $.post('foo.php',{data:st},function(data){... });

  3. Decode your data on the server-side processing: $data = json_decode($_POST['data']);

or simple one

var array = [1,2,3,4,5,6];
$.ajax({
  url: "mydomain.com/url",
  type: "POST",
  dataType: "json",
  data: {arrayName: array},
  complete: function() {
    //called when complete
  },
  success: function() {
    //called when successful
  },
  error: function() {
    //called when there is an error
  },
});
Database_Query
  • 626
  • 4
  • 14
-1

you can give this a try if you want to pass array and post method use $.post for simlicity I have updated your code.

$(".comment_button").click(function() {

        var chkarray = [];
        $('.webInput:checked').each(function(){
        chkarray.push($(this).val());
        });
       // var dataString = "content="+ chkarray;      
    if(test=='')
    {
    alert("Please check checked");

    }
        $.post('chkoutput.php',{dataString:chkarray },function(data){

                     $("#test_area").after(html);
                     document.getElementById('content').value='';
                     $("#flash").hide();
                        });
}

as you mentioned you don't know jquery first of all check for javascript errors, in any of debuging tools like mozila firebug or any thing handy and post them so one can help better.

Edited for my dear commentators

I should admit an apology to confuse you all, I have added a comment on var dataString but even if it is not commented the code will work. because dataString in $.post argument is not representing the var dataString. it is the property name of entirely new object which is being passed to $.post method and all other things are managed by $.post function. I am really surprised no one even tried or checked before blame.

This will work for sure if you do not agree just copy and paste below code in a php(name it index.php) file and hit it then click the button, see what happens and then ask me how it works

<?php 
if(!empty($_POST))
{
  var_dump($_POST);exit;
}
?>
<!DOCTYPE html>
<html>
<body>

<h1>Please GET It</h1>


<script src="http://code.jquery.com/jquery-latest.min.js "></script>
<script>
function doSomething()
{   var test = ['I','am','an','array','wrong?', 'and posted as it was said on click']
    $.post('index.php',{test : test},function(data) {alert(data);})
}
</script>

<button onclick="doSomething()">Click me </button>

</body>

    </html>  
Rupesh Patel
  • 3,015
  • 5
  • 28
  • 49
  • You can't send a JS array as a POST parameter, because these are Strings. – 11684 Sep 30 '12 at 10:24
  • @11684 and from where you have learnt this ? check it out again and then let me know – Rupesh Patel Sep 30 '12 at 10:25
  • @RupeshPatel 11684 is right..I think you should convert into json – StaticVariable Sep 30 '12 at 10:26
  • I'd say that if you try to treat a JS array as a String it won't magically convert to JSON... – 11684 Sep 30 '12 at 10:27
  • The default array toString behavior will get rid of the quotes and brackets, so the backend won't be able to understand the input. You need to make it a JSON string – nbrooks Sep 30 '12 at 10:27
  • tbakend will get the array dataString for sure amd it is a valid syntax I use in my every day code .. just try it out – Rupesh Patel Sep 30 '12 at 10:29
  • @nbrooks dear friends first note the difference between js object and json http://stackoverflow.com/questions/3975859/what-are-the-differences-between-json-and-javascript-object... my code will generate an object and all properties will be passed in post header by mechanism of jquery – Rupesh Patel Sep 30 '12 at 10:41
  • No it won't. Your syntax is completely wrong. In fact I am not even sure how (in computer science) you can concat an array and a string...and even then you are making the resulting string (which it should be in this concatenation) be passed via POST header content. There is no object being converted to JSON in your code at all. – Sammaye Sep 30 '12 at 11:01
  • 1
    The problematic part of this isn't (necessarily) how you create the object, it's how you "create" (I use the term loosely, because you actually don't) the key. `var dataString = "content="+ chkarray;` simply comma delimits the array values and appends them to `content=`, which isn't useful. Furthermore, your object key `dataString` does not use that value at all, it will simply be stringified to "dataString". I suspect that parts of this code might be useful and work exactly as you intend, but when you simply copy and paste code from the question into your answer you end up with broken code. – nbrooks Sep 30 '12 at 11:43
  • @sammaye Concatenaing an array and a string is perfectly legal in JS, as with most (*all*?) other objects; the interpreter simply uses the default `toString` method of the object. Also the post data does not explicitly need to be converted to JSON, a query string will work too -- it will be converted to the necessary format before sending. What doesn't work is a combination of both approaches in a single solution... – nbrooks Sep 30 '12 at 11:50
  • @nbrooks The `toString` will not work here at all since it outputs a comma delimited version of the arrays elements, also POST still must transmit post fields in array syntax not JSON syntax as such the object would not be converted to JSON instead the body of the HTTP request would be: `dataString=content=el1,el2,el3` – Sammaye Sep 30 '12 at 14:01
  • @sammaye I think you missed my point. I agree that the code, as is, does not work. However the act of concatenating the array to the string does work, contrary to your previous statement. That was the crux of my argument. Regarding the body of the post, jQuery will ensure that is constructed correctly *once it understands the data*. It is equally happy with `content=["1","2","3"]` as it would be with actual JSON. This is detailed in their documentation, and is easily mocked up in code. http://jsfiddle.net/8EMqG/ – nbrooks Sep 30 '12 at 14:13
  • @nbrooks Yes but it wouldn't be happy with `content=1,2,3` which what the function outputs, the code does nothing to convert it to JSON. It will only convert if it properly formed JSON. Test it for yourself it will throw an error in the fiddle you produced. Yes I forgot about the `toString` behaviour but even in this case it still wouldn't work. – Sammaye Sep 30 '12 at 14:19
  • @nbrooks and infact this thread is invalid cos he doesn't even need to, he just needs to make sure the output of the post is AJAX, I didn't see that but yea so this entire thread is invalid. Though this code still won't work for that because he doesn't define a JSON argument for the response in the function unless he manually and explicity converts it to JSON. – Sammaye Sep 30 '12 at 14:21
  • @11684 alert a js array and it will be magically converted to string but that is totally different senario – Rupesh Patel Sep 30 '12 at 15:57
  • @Sammaye In computer science there and for specifically javascript there is a method named toString() assigned to all arrays which is being called whenever you concate a string and an array and convers array to comma separated string but this is not the point at all . one should understand closures to understand this code – Rupesh Patel Sep 30 '12 at 16:52
  • I don't think this will work still. If you check its output you will see it would return a sting from the PHP page. You want to add one more param to the `$.post` function which has a value of `"json"` – Sammaye Sep 30 '12 at 19:43
  • @Sammaye OMG god bless you ... – Rupesh Patel Oct 01 '12 at 05:31