3

I have a form that collect user info. I encode those info into JSON and send to php to be sent to mysql db via AJAX. Below is the script I placed before </body>.

The problem now is, the result is not being alerted as it supposed to be. SO I believe ajax request was not made properly? Can anyone help on this please?Thanks.

<script>
    $(document).ready(function() {
    $("#submit").click(function() {
        var param2 = <?php echo $param = json_encode($_POST); ?>;
        if (param2 && typeof param2 !== 'undefined')
        {
            $.ajax({
                type: "POST",
                url: "ajaxsubmit.php",
                data: param2,
                cache: false,
                success: function(result) {
                    alert(result);
                }
            });
        }
    });
});
</script>

ajaxsubmit.php

<?php
$phpArray = json_decode($param2);
print_r($phpArray);
?>
yergo
  • 4,761
  • 2
  • 19
  • 41
sweety
  • 195
  • 1
  • 11
  • What is `dataString` over here – Narendrasingh Sisodia Apr 22 '15 at 07:19
  • 1
    What is `dataString`? Also you can check the network tab in dev tools to see if the request went through. – ankr Apr 22 '15 at 07:19
  • Can you elaborate on "*the result is not being alerted as it supposed to be*"? – Wai Ha Lee Apr 22 '15 at 07:25
  • @NarendraSisodia, sorry I changed it to param2 now, the data to be decoded in php. – sweety Apr 22 '15 at 07:28
  • @WaiHaLee, in my ajax script I wrote alert(result); I expect whatever the result from php file to appear in alert box. – sweety Apr 22 '15 at 07:29
  • Try adding `dataType: 'json'` to your AJAX request? – SubjectCurio Apr 22 '15 at 07:30
  • Is `json_encode($_POST)` correct? or should it be like `json_encode($_POST['YourFormName'])`? – Sandeep Nayak Apr 22 '15 at 07:32
  • @MLeFevre, I'll try that, thanks...but can you also take a look at my php code.. I guess something wrong here,$phpArray = json_decode($jsonData); – sweety Apr 22 '15 at 07:33
  • @MLeFevre Wouldn't that also not work because `ajaxsubmit.php` does *not* return json? – filpa Apr 22 '15 at 07:33
  • @SandeepNayak, I did try including but the same result. I guess something wrong with ajaxsubmit.php file....Can you spot anything there..$phpArray = json_decode($param2); – sweety Apr 22 '15 at 07:36
  • Your JS and PHP are both wrong. [This is how you send a JSON request](http://stackoverflow.com/a/6587249/19068). [This is how you process a JSON request](http://stackoverflow.com/a/19007851/19068). – Quentin Apr 22 '15 at 09:02
  • @Quentin, Thanks for ur reference. I noticed that in php file must decode like this=> $json = file_get_contents('php://input'); $obj = json_decode($json); Can explain this part please(('php://input'); – sweety Apr 22 '15 at 09:07
  • @sweety — That's the location you read the data from to get the body of the request. – Quentin Apr 22 '15 at 12:23

5 Answers5

0

You'll need to add quotes surrounding your JSON string.

var param2 = '<?php echo $param = json_encode($_POST); ?>';
vdwijngaert
  • 1,515
  • 11
  • 24
0

As far as I am able to understand, you are doing it all wrong.

Suppose you have a form which id is "someForm"

Then

$(document).ready(function () {
    $("#submit").click(function () {
        $.ajax({
            type: "POST",
            url: "ajaxsubmit.php",
            data: $('#someForm').serialize(),
            cache: false,
            success: function (result) {
                alert(result);
            }
        });
    }
    });
});

In PHP, you will have something like this

$str = "first=myName&arr[]=foo+bar&arr[]=baz";

to decode

parse_str($str, $output);
echo $output['first'];  // myName

For JSON Output

echo json_encode($output);
Murtaza Khursheed Hussain
  • 15,176
  • 7
  • 58
  • 83
  • @Muztaza I agree with you, I also guessed the same , I'm doing it all wrong but just not sure which. from your answer I'll get my ajax part right but how about encoding and decoding in json? I want to send all user input to the php file ,thats why using json_encode($_POST). – sweety Apr 22 '15 at 07:43
  • you dont need json for this. just follow the above code, you fill have the expected result back – Murtaza Khursheed Hussain Apr 22 '15 at 07:44
  • @Muztaza OK but I don't understand this part => $str = "first=myName&arr[]=foo+bar&arr[]=baz"; & this part=> parse_str($str, $output); echo $output['first']; – sweety Apr 22 '15 at 08:18
  • `$('#someForm').serialize(),` using this will convert you form inputs into `first=myName&arr[]=foo+bar&arr[]=baz"` and this will be passed to server, in ajaxsubmit.php you'll need to parse the result by use `parse_str` – Murtaza Khursheed Hussain Apr 22 '15 at 08:19
  • @Muztaza, serialize will convert to smtg like this :first=myName&arr[]=foo+bar&arr[]=baz, Okay I understand..But in ajaxsubmit.php I will need to parse_str($str, $output);....Where do i get the $str and $output please? – sweety Apr 22 '15 at 08:29
  • :) , `$str = $_POST['data']` here you will get data – Murtaza Khursheed Hussain Apr 22 '15 at 08:54
0

If you are returning JSON as a ajax response then firstly you have define the data type of the response in AJAX.

try it.

 <script>
        $(document).ready(function(){  
$("#submit").click(function(){
      var param2 = <?php echo $param = json_encode($_POST); ?>
            if( param2  && typeof param2 !== 'undefined' )
                     {
                  $.ajax({
            type: "POST",
            url: "ajaxsubmit.php",
            data: dataString,
            cache: false,
            dataType: "json",
            success: function(result){
            alert(result);
            }
              });}
            });
});
    </script>
vdwijngaert
  • 1,515
  • 11
  • 24
Sujeet Kumar
  • 159
  • 6
  • I tried your way... But it's not showing the result as I believe the ajaxsubmit.php file is wrong? which variable and how I use it to decode in php please..from ajax I'm passing param2 in javascript – sweety Apr 22 '15 at 07:58
0

It's just really simple!

$(document).ready(function () {
    var jsonData = {
                    "data" : {"name" : "Randika",
                               "age" : 26,
                            "gender" : "male"
                     }
                  };
  
    $("#getButton").on('click',function(){
     console.log("Retrieve JSON");
        $.ajax({
            url : "http://your/API/Endpoint/URL",
            type: "POST",
            datatype: 'json',
            data: jsonData,
            success: function(data) {
                console.log(data);  // any response returned from the server.
            }
        });
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" value="POST JSON" id="getButton">

For your further readings and reference please follow the links bellow:

  1. Link 1 - jQuery official doc
  2. Link 2 - Various types of POSTs and AJAX uses.

In my example, code snippet PHP server side should be something like as follows:

 <?php
    $data = $_POST["data"];
    echo json_encode($data);  // To print JSON Data in PHP, sent from client  side we need to **json_encode()** it.
    // When we are going to use the JSON sent from client side as PHP Variables (arrays and integers, and strings) we need to **json_decode()** it

    if($data != null) {
       $data = json_decode($data);
       $name = $data["name"];
       $age = $data["age"]; 
       $gender = $data["gender"];
       // here you can use the JSON Data sent from the client side, name, age and gender.
    }
 ?>

Again a code snippet more related to your question.

     // May be your following line is what doing the wrong thing
    var param2 = <?php echo $param = json_encode($_POST); ?>
  
    // so let's see if param2 have the reall json encoded data which you expected by printing it into the console and also as a comment via PHP.
  
     console.log("param2 "+param2);
     <?php echo "// ".$param; ?>
Randika Vishman
  • 7,983
  • 3
  • 57
  • 80
  • Thanks for showing the code snippet... I think my code now works just one part I don't get it right is the php file. Now my ajax is submiting the request to php but php unable to decode as the varibale is undefined, so it says in the alert box. – sweety Apr 22 '15 at 08:11
  • Hey, I've edited my answer please check it and see if the answer is correct. :-) Cheers! – Randika Vishman Apr 22 '15 at 08:41
  • Your variable names are misleading. You aren't sending JSON to the PHP at all. Why do you have `crossDomain:true,`? – Quentin Apr 22 '15 at 08:42
  • @Randika, I think it doesn't involve JSON? My ajax now working , but I just need to know how to decode the json in php..which variable to use? – sweety Apr 22 '15 at 08:46
  • @Quentin please explain why do u think my variable names are misleading? I've just given an example. And you can't assume that my ajax call is not sending data to PHP or to Java API! It's at the server side implementation isn't it? Anyway as of now I've added how to decode the JSON in PHP too! Hope this helps! – Randika Vishman Apr 22 '15 at 08:53
  • @sweety hey, and did you try using a tool like FireBug console in FireFox browser? It shows you if your Request is directly sent to the intended URL or not! If the response status is 200 or not. Most probably that might be the problem. Because you have put only "ajaxsubmit.php" for the URL, normally it should be a correct url which points to your API end point. – Randika Vishman Apr 22 '15 at 08:56
  • @Randika — `jsonData` contains a JavaScript object, not JSON. Since you've not done anything to change the defaults, jQuery will encode it as form data, not JSON. (The PHP is ridiculous - you encode the array as JSON only to immediately decode it again which is utterly pointless) – Quentin Apr 22 '15 at 08:59
  • @Randika , I use chrome dev tool and the response is 200...it works fine if i simply echo "hi"; in the php file but when I want to decode is the problem.can you just help me with decoding please as to which variable I use to decode?? – sweety Apr 22 '15 at 09:03
  • @Quentin thanks for the clue. I made changes to my answer then! :-) Cheers! sweety you also check it please! And also the above last comment done by me. Did you check the response too? Isn't it giving you the response, "result" in your case! – Randika Vishman Apr 22 '15 at 09:09
  • @Randika its just not working..if Im sending in ajax like this:var param2 = '';.............Then how do I decode in php? – sweety Apr 22 '15 at 09:29
  • @sweety I suggest you to follow the second link I have posted in the above Answer! – Randika Vishman Apr 22 '15 at 12:04
  • @Randika, Thanks... I found the answer already and posted it! – sweety Apr 22 '15 at 12:29
0

After some research on the google , I found the answer which alerts the result in JSON!

Thanks for everyone for your time and effort!

<script>
$("document").ready(function(){
  $(".form").submit(function(){
    var data = {
      "action": "test"
    };
    data = $(this).serialize() + "&" + $.param(data);
    $.ajax({
      type: "POST",
      dataType: "json",
      url: "response.php", //Relative or absolute path to response.php file
      data: data,
      success: function(data) {
        $(".the-return").html(
          "<br />JSON: " + data["json"]
        );

        alert("Form submitted successfully.\nReturned json: " + data["json"]);
      }
    });
    return false;
  });
});

</script>

response.php

<?php
if (is_ajax()) {
  if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
    $action = $_POST["action"];
    switch($action) { //Switch case for value of action
      case "test": test_function(); break;
    }
  }
}

//Function to check if the request is an AJAX request
function is_ajax() {
  return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}

function test_function(){
  $return = $_POST;


  echo json_encode($return);

}
?>

Here's the reference link : http://labs.jonsuh.com/jquery-ajax-php-json/

sweety
  • 195
  • 1
  • 11