-3

I have this PHP file:

JSONtest.php

<?php
$a=5;
echo json_encode($a);
//This converts PHP variable to JSON.
?>

I want to alert this variable's value using Ajax and JSON, and for that I've written this script:

learningJSON.php

$(document).ready(function(){
    $("button").click(function(){
    $.ajax({
        url: 'JSONtest.php',
        type: 'POST',
        data: data,
        dataType: 'json',
        success: function(result){
            alert(result);
            },
        error: function(){
            alert("Error");
            }
        });
    });
});

But when I click the button, I get this error message: learningJSON.php:14 Uncaught ReferenceError: data is not defined

What wrong I'm doing? How can I fix this?

Vikas Kumar
  • 689
  • 3
  • 7
  • 18
  • you need to define data variable within your ajax request. or at least put some dummy json there: `data: { param: 1 }` – mitkosoft Mar 25 '16 at 07:49
  • [JSON](https://en.wikipedia.org/wiki/JSON) (JavaScript **Object** Notation) is for data **objects**. Scalar data (like number `5` in your example) are not JSON. – hindmost Mar 25 '16 at 07:53

3 Answers3

2
<?php
$a=5;
echo json_encode($a);
//This converts PHP variable to JSON.
?>

Nope, it doesn't. Whats the point in converting a simple number to JSON? It stays the number 5

Now the real problem. Yes your data variable is not defined anywhere in your JavaScript code. If you have no data to send, remove that parameter.

However if you still want to pass some data, define it accordingly then. For example

data: { fname: "John", lname: "Doe" }

Now let's say on your next exercise you want to post form data you can use this nice function named serialize(). This will take all the postable fields from your form and send them along with this request.

data : $("#formID").serialize()
Hanky Panky
  • 46,730
  • 8
  • 72
  • 95
1

Data variable is not defined, you can delete that

Php file

<?php
$a = $_REQUEST['number'];
echo json_encode($a);
//This converts PHP variable to JSON.
?>

Javascript file

$(document).ready(function(){
    $("button").click(function(){
    $.ajax({
        url: 'JSONtest.php',
        type: 'POST',
        //data: {'number' : 10}, //this is when you need send parameters to the call, uncomment to send it parameters
        dataType: 'json',
        success: function(result){
            alert(result);
            },
        error: function(){
            alert("Error");
            }
        });
    });
});
Mauricio Florez
  • 1,112
  • 8
  • 14
  • Thank you. It works. Now could you explain how do I send a value to same php file using same approach? – Vikas Kumar Mar 25 '16 at 07:54
  • could you please tell me what's wrong in my Ajax method? Here's my question: http://stackoverflow.com/questions/36201036/why-isnt-the-image-not-copied-to-the-folder – Vikas Kumar Mar 25 '16 at 08:00
0

I think this one should be perfect for you. We need 3 files

  1. index.php
  2. login.js
  3. login.php

That mean when user submit [index.php] script js file [login.js] running ajax process script [json] in login.js by collect all data from form input [index.php] and send and run script login.php ... This is powerful script of ajax & json

check code below

index.php

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="login.js" type="text/javascript" charset="utf-8">  </script>
</head>
    <body>      

        <form method="post" id="login" name="login">
            Email: <input type="email" id="log-mail" name="log-mail"  > <br />
            Password: <input type="password" id="log-pass" name="log-pass" > <br />
            <button type="submit" >Log in</button>
        </form>

    </body>
</html>

login.js

$(document).ready(function(){

    // #login = login is the name of our login form
    $('#login').submit(function(e) {
        $.ajax({
            type: "POST",
            url: "login.php",
            data: $('#login').serialize(),
            dataType: "json",
            success: function(msg){

                if(parseInt(msg.status)==1)
                {
                    window.location=msg.txt;
                }
                else if(parseInt(msg.status)==0)
                {
                    window.location=msg.txt;
                }                               
            }
        });
        e.preventDefault();

    });


});

login.php

<?php


    if(isset($_POST['log-mail']) && $_POST['log-mail'] != ''  && isset($_POST['log-pass']) && $_POST['log-pass'] != '' ) {  
        $_data_ = 'index.php?user_data='.$_POST['log-mail'];
        echo msg_result(1,$_data_);
    }else{
        $msg_att = "index.php?login_attempt=1";
        echo msg_result(0,$msg_att);   

    }



    function msg_result($status,$txt) {
        return '{"status":'.$status.',"txt":"'.$txt.'"}';
    }


?>

you can see on your url if you

  1. complete all field => ...index.php?user_data=user_data@gmail.com
  2. uncomplete => ...index.php?login_attempt=1

Hope this solve your issue

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252