PHP Scrub
PHP Scrub

Reputation: 171

Trying to display PHP echo in HTML with JSON

I'm trying to display two PHP echo messages from a seperate PHP file onto my HTML body page. Whenever you click the submit button the echo message should popup in the HTML page without redirecting me to the PHP page.

I need to connect to my two files through Javascript so I wrote a script attemtping to connect the HTML file with the PHP file.

My HTML:

<div id="formdiv">        
<form action="phpfile.php" method="get" name="fillinform" id="fillinform" class="js-php">
      <input id="fillintext" name="fill" type="text" />
            <input type="submit" id="submit1" name="submit1">
            </form>
</div>

phpfile.php:

 $q = $_GET['fill'];
$y = 2; 
$work = $q * $y;
$bork = $work * $q;

echo json_encode($work) ."<br>"; 

echo  json_encode($bork); 

Javascript:

 $(".js-php").submit(function()
    var data = {
    "fill"
    };
    data = $(this).serialize() + $.param(data); 

        $.ajax({
        type:"GET",
        datatype:"json",
        url:"phpfile.php",
        data: data,
        success: function (data){
        $(".formdiv").html(
        ""
        "Your input: ")
        }

Upvotes: 2

Views: 1499

Answers (4)

Kristian Vitozev
Kristian Vitozev

Reputation: 5971

You attached your logic to .submit() event and if you don't prevent default action, the form will be submitted to server. You can prevent it that way:

$(".js-php").submit(function(e) {
    // your code goes here
    e.preventDefault();
});

Upvotes: 3

Arpita
Arpita

Reputation: 1398

  1. Add curly braces after $(".js-php").submit(function(e) and close it after your ajax ends.
  2. Add e.preventDefault() before you call ajax so it will not redirect you to phpfile.php
  3. Add alert(data) inside your function called at success of ajax.
  4. there is a syntax error n line $(".formdiv").html("""Your input: ");

Your updated code should look like.

$(".js-php").submit(function(e){
    var data = {
    "fill"
    };
    data = $(this).serialize() + $.param(data); 
    $.ajax({
        type:"GET",
        datatype:"json",
        url:"phpfile.php",
        data: data,
        success: function (data){
            alert(data);
    }
}

Upvotes: 1

Nivs
Nivs

Reputation: 374

As per your html you should try this below code : If you want to replace the whole html inside the div having id="formdiv"

 success: function (data){
    $("#formdiv").html("Your input: "+data)
}

or

 success: function (data){
    $("#formdiv").text("Your input: "+data)
}

If you want to append data to the div having id="formdiv"

 success: function (data){
    $("#formdiv").append("Your input: "+data)
}

Upvotes: 1

Jeroen Bellemans
Jeroen Bellemans

Reputation: 2035

You'll have to append the data to your div like this:

success: function (data) {
    $(".formDiv").append("Your input: " + data);
}

Upvotes: 1

Related Questions