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);
?>
13
  • What is dataString over here Commented Apr 22, 2015 at 7:19
  • 1
    What is dataString? Also you can check the network tab in dev tools to see if the request went through. Commented Apr 22, 2015 at 7:19
  • Can you elaborate on "the result is not being alerted as it supposed to be"? Commented Apr 22, 2015 at 7:25
  • @NarendraSisodia, sorry I changed it to param2 now, the data to be decoded in php. Commented Apr 22, 2015 at 7:28
  • @WaiHaLee, in my ajax script I wrote alert(result); I expect whatever the result from php file to appear in alert box. Commented Apr 22, 2015 at 7:29

5 Answers 5

0

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

var param2 = '<?php echo $param = json_encode($_POST); ?>';
Sign up to request clarification or add additional context in comments.

10 Comments

Thanks!...Now at least it's showing the alert box. But not echoing the php file result.. For testing reason I just echo"hi"; in php file to no avail
What do you see when you inspect the XHR request in your Chrome devtools?
I sa this : Uncaught SyntaxError: Unexpected token if
Show us the code of your PHP file. Does it start with <?php?
My php I showed above(ajaxsubmit.php). NowI tried again, it says XHR loaded. And in the alert box it states Notice: undefined varibale named param2
|
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);

6 Comments

@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).
you dont need json for this. just follow the above code, you fill have the expected result back
@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'];
$('#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
@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?
|
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>

1 Comment

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
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; ?>

12 Comments

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.
Hey, I've edited my answer please check it and see if the answer is correct. :-) Cheers!
Your variable names are misleading. You aren't sending JSON to the PHP at all. Why do you have crossDomain:true,?
@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?
@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!
|
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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.