1

I have created an addarticle.php file that inserts a new entry into my database, based on form data from a separate index.php file.

My question is, how I can return json_encode($success); to my previous page?

I hope to achieve something similar to what is described here, but with a 'success status'

I know that I can use include('addarticle.php'); in my index.php file, and use the $success variable.

Is there another way to return the transaction status? Thank you!

addarticle.php

<?php
$servername = "example.something.com";
$username = "edwin";
$password = "123456";
$dbname = "testdb";

$success;

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$title = mysqli_real_escape_string($conn, $_POST['title']);
//$title = $_POST['title'];
$article = mysqli_real_escape_string($conn, $_POST['article']);
$imageurl1 = $_POST['imageurl1'];
$imageurl2 = $_POST['imageurl2'];
$imageurl3 = $_POST['imageurl3'];

$sql = "INSERT INTO Articles (Title, TextBody, ImageURL1,ImageURL2,ImageURL3)
VALUES ('$title','$article','$imageurl1','$imageurl2','$imageurl3')";

if ($conn->query($sql) === TRUE) {
    $success = true;
} else {
    $success = false;
}

echo json_encode($success);

$conn->close();

?>

index.php

<form action="addpost.php" method="post" style="left:0">
Title: <input name="title" type="text" /><br />
Article Body:<br /> <textarea cols="50" name="article" rows="4"></textarea><br /> 
Image URL1: <input name="imageurl1" type="text" /><br /> 
Image URL2: <input name="imageurl2" type="text" /><br /> 
Image URL3: <input name="imageurl3" type="text" /><br /> 
<input type="submit" value="Submit" />
</form>
Community
  • 1
  • 1
Edwin Chua
  • 658
  • 1
  • 8
  • 20

2 Answers2

1

Looking at the code you provided: First of all, why do you json_encode a boolean value? There is no real need for it, in this context. Giving you that, you could easily send that boolean value to any page using a $_GET request.

Like this:

$url = "anypage.php?status=" + $status;
header("Location: " + $url);

And at anypage.php

if(isset($_GET["status"])){
  $status = $_GET["status"]; // either true or false
}

OR, you could go the AJAX way and implement that.

If you are using jQuery: http://www.w3schools.com/jquery/ajax_ajax.asp

Gerrit Luimstra
  • 522
  • 6
  • 23
-1

Get your json response using ajax as below

$.ajax({ url: 'addarticle.php',
    cache: false,
    type: 'post'
}).done(function(response) {
    console.log(response);
});
Scott Weldon
  • 9,673
  • 6
  • 48
  • 67
user3040610
  • 750
  • 4
  • 15
  • 2
    Although this might solve the problem, it is recommended to add an explanation to the code. – BDL Nov 16 '16 at 14:05
  • **Flaggers / reviewers:** [For code-only answers such as this one, downvote, don't delete!](//meta.stackoverflow.com/a/260413/2747593) – Scott Weldon Nov 17 '16 at 02:25