user1821499
user1821499

Reputation: 311

PHP array returns null

I have a html form with a button on which there is a onclick event

    <form id = "abc" action = "xyz.php" method = "post">
      <input type="button" name="submitButton" value="Submit" 
            id="submitButton" onclick = "Function()">
     </form>

In the JS code, I am trying to post a value of a textbox and trying to get the array from the PHP through json_encode.

var valueToSend = $('#textbox').val();
var imagesReturned = new Array();
$.ajax({
        url: "xyz.php",
        type: "POST",
        data: valueToSend,
        dataType:"json",
        success: function(result) {        
            var data = jQuery.parseJSON(result);
            alert(data);
        }
    });

And here is my PHP code,

        if(isset($_POST['valueToSend'])) 
        {
            $searchValues = explode(' ',$_POST['valueToSend']);
           // Some processing here
            echo (json_encode($responseArray));

        }

When I alert the data, I get null, What am I missing?

Thanks!

Upvotes: 3

Views: 915

Answers (4)

user1821499
user1821499

Reputation: 311

The problem was in the PHP code.

I removed the check, if(isset($_POST['valueToSend'])) and its working...

Upvotes: 0

Manoj Purohit
Manoj Purohit

Reputation: 3453

data field of yours look suspicious to me

   $.ajax({
            url: "xyz.php",
            type: "POST",
            data:{valueToSend:valueToSend},
            dataType:"json",
            success: function(result) {        
                alert(result);
            }
        });

Upvotes: 1

Joshua Burns
Joshua Burns

Reputation: 8582

The problem is within your Ajax request, the data key expects a key/value pair, not just a value.

What you're looking for is something similar to the following:

var valueToSend = {
  'valueToSend': $('#textbox').val()
}

In addition, you're setting the dataType key to json, so there is no need to pass the data variable through parseJSON. As such, the success function only needs to be declared as follows:

'success': function(result) {
  alert(result);
}

Upvotes: 3

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

var valueToSend = $('#textbox').val();
var imagesReturned = new Array();
$.ajax({
        url: "xyz.php",
        type: "POST",
        data: {"valueToSend":valueToSend},
        dataType:"json",
        success: function(result) {        
            var data = jQuery.parseJSON(result);
            alert(data);
        }
    });

correct the format of data in ajax

Upvotes: 1

Related Questions