PHP Scrub
PHP Scrub

Reputation: 171

Using Ajax and JSON to display PHP echo message in HTML

Ive been trying to connect my PHP file to my HTML file using Javascript/jQuery and json. When the user inputs a number into the input box in the form and submits it, the PHP file should multiply the number by two and send it back to the user.

However when I press the submit button it takes me to the php page instead of displaying the information (processed in the php file) in HTML.

This is my HTML form:

<div id="formdiv">
    <form action="phpfile.php" method="get" name="form1" id="form1" class="js-php">
    Mata in ett nummer: <input id="fill1" name="fill1" type="text" />
    <input type="submit" id="submit1" name="submit1" value="submit">
</form>

This is my Javascript file

$(".js-php").submit(function(e){

    var data = {
        "fill1"
    };
    data = $(this).serialize() + $.param(data); 

    $.ajax({
        type:"GET",
        datatype:"json",
        url:"phpfile.php",
        data: data,
        success: function (data){
            $("#formdiv").append("Your input: "+data)
            alert (data);
        }
    })

    e.preventDefault();
});

PHP file:

$kvantitet = $_GET['fill1'];
$y = 2; 
$work = $kvantitet * $y;
$bork = $work * $kvantitet;
echo json_encode($work) ."<br>"; 
echo json_encode($bork); 

Upvotes: 3

Views: 4153

Answers (3)

Michael Doye
Michael Doye

Reputation: 8171

There are a few things you could do a bit differently here to make this work:

Currently, using both .serialize and $.param your data variable contains something like this:

someurl.php?fill1=1&0=f&1=i&2=l&3=l&4=1&5=%3D&6=1

If you use only .serialize you will get something easier to work with:

?fill1=5


On the PHP side, currently your code outputs something like this:

4<br>8

By adding your values to an array you can get a response back that you can work with:

$result    = array();
$kvantitet = $_GET['fill1']; // Lets say this is 5
$y         = 2; 
$work      = $kvantitet * $y;
$bork      = $work * $kvantitet;

//add the values to the $result array
$result = array(
    "work" => $work,
    "bork" => $bork
);

echo json_encode($result);

Which will output:

{"work":4,"bork":8}


Back on the JS side you can then handle the data in your success callback:

$(".js-php").submit(function(e){
    data = $(this).serialize(); 
    $.ajax({
        type:"GET",
        datatype:"json",
        url:"phpfile.php",
        data: data,
        success: function (data){
            // *data* is an object - {"work":4,"bork":8}
            $("#formdiv").append("Your input: "+data)
            console(data);
        }
    });
    // Use return false to prevent default form submission
    return false;
});

One way to access the properties in your object is by using dot notation:

data.work //Outputs 4
data.bork //Outputs 8

But here is a really great answer on processing / accessing objects and arrays using JavaScript.

Here is a Fiddle containing your (working) jQuery

Upvotes: 1

Mohamed-Yousef
Mohamed-Yousef

Reputation: 24001

I think you need &

data = $(this).serialize()+'&'+$.param(data); 

and as @leonardo_palma mentioned in comments maybe you need to use e.preventDefault(); in the beginning of submit function

and I prefer to use

$(document).on('submit','.js-php',function(){/*code here*/});

Upvotes: 0

Aaron Gong
Aaron Gong

Reputation: 1005

You are expecting JSON Data but what you send back is not JSON

Try output the following in your PHP File:

$data['work'] = $work;

$data['bork'] = $bork;

echo json_encode( (object)$data );

Use console.log to inspect incoming data on the AJAX call then handle it according to how you want.

Upvotes: 0

Related Questions