3

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); 
Griffith
  • 3,229
  • 1
  • 17
  • 30
PHP Scrub
  • 171
  • 3
  • 17

3 Answers3

1

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

Community
  • 1
  • 1
Michael Doye
  • 8,063
  • 5
  • 40
  • 56
  • Hello M.Doye, I feel like I'm making a lot of progress, however I still unable to get the echo message from PHP to show up in HTML like you did on your example on jsfiddle. Here is what I've done so far: (not very good at using jsfiddle yet) https://jsfiddle.net/mdoye/gxok5dux/4/ – PHP Scrub Oct 28 '15 at 17:54
  • @PHPScrub Use the network inspector in your browser developer console to make sure the request is being sent as you expect it to - also, you will need to update the fiddle. (the one you posted is the same one I posted) – Michael Doye Oct 28 '15 at 17:59
  • Ive tried it. Request is being sent. But it redirects me to the PHP file regardless of what I try. – PHP Scrub Oct 28 '15 at 18:11
  • Sounds like it could be the form, try it this way, without the actual form - https://jsfiddle.net/mdoye/gxok5dux/6/ – Michael Doye Oct 28 '15 at 18:19
  • @PHPScrub I left out a semi-colon after the ajax call, that could have been causing your issue, have updated the Fiddle and answer – Michael Doye Oct 28 '15 at 18:23
  • It doesnt work on my webbrowser, only on Jsfiddle unfortunately. I've also tried replacing "/echo/json/" with the php file name but it still doesnt work... – PHP Scrub Oct 28 '15 at 19:58
  • When I follow this example my "data" becomes a string I think and not an object, data.work gives "undefined". I have to do "var object = JSON.parse(data)" and then "object.work". Why is that? – Paintoshi May 19 '17 at 09:36
  • @David would need to see your code to answer accurately, perhaps best if you [ask a question](http://stackoverflow.com/questions/ask) specific to your issue – Michael Doye May 19 '17 at 11:17
0

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.

Aaron Gong
  • 977
  • 7
  • 18
0

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*/});
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28