简体   繁体   中英

Can't able to insert data into database using jQuery & AJAX in php

I can insert data into database using pure php and mysql. But can't able to insert data into database using jQuery & AJAX in PHP. Only one error is showing from AJAX error: ie Please Check Your Network Connection. Please help me to solve this problem.

My jQuery AJAX code, PHP code, HTML code is given below.

HTML --- news.php

    <div id="error"></div>
                <form method="post" class="form-horizontal" role="form" name="newsForm">

  <div class="form-group">
    <label class="control-label col-sm-2">News Heading</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="newsHeading" name="newsHeading" placeholder="Enter News Heading">
    </div>
  </div> <!--News Heading-->

  <div class="form-group">
    <label class="control-label col-sm-2">News Source URL</label>
    <div class="col-sm-10">
      <input type="text" class="form-control" id="newsSource" name="newsSource" placeholder="Enter News Source URL">
    </div>
  </div> <!--News Source-->

  <div class="form-group">
    <label class="control-label col-sm-2">News Content</label>
    <div class="col-sm-10"> 
     <textarea class="form-control" rows="3" id="newsContent" name="newsContent" placeholder="News Content"></textarea>
    </div>
  </div><!--News Data-->

  <div class="form-group"> 
    <div class="col-sm-offset-2 col-sm-10">
      <button type="submit" id="postNews" name="postNews" class="btn bg-red">Submit</button>
    </div>
  </div> <!--Submit Button-->


</form>

If I write Simple PHP Codes in news.php it works & inserts data into database.

<?php
                 if(isset($_POST['postNews'])===true)
            {
                $heading = $_POST['newsHeading'];
                $source = $_POST['newsSource'];
                $content = $_POST['newsContent'];
                $query = mysql_query("INSERT INTO `news`(`news_heading`,`news_source`,`news_content`) VALUES('$heading','$source','$content')");

            }
?>

The below scripts only show AJAX Network connection error. Can't insert data into database.

jQuery & AJAX

<script>
      $(document).ready(function(){

        $("#postNews").click(function(){
            var newsHeading = $("#newsHeading").val();
            var newsSource = $("#newsSource").val();
            var newsContent = $("#newsContent").val();
            var dataString = 'newsHeading='+newsHeading+'&newsSource='+newsSource+'&newsContent='+newsContent;

            alert(dataString); //
            if($.trim(newsHeading).length>0 && $.trim(newsSource).length>0 && $.trim(newsContent).length>0)
            {
              $.ajax({
                   type: "POST",
                   url: "core/news-post-process.php",
                   data: dataString,
                   cache: false,
                   beforeSend: function(){ 
   $("#error").html("<div class='alert alert-primary bg-primary'><a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a><strong>Please Wait, We are processing.</strong> </div>");

  $("#postNews").html("<i class='fa fa-spinner fa-pulse'></i><span class='sr-only'>Loading...</span> Posting....");
 },
                   success: function(data){
                          if(data=="success"){
                              $("#error").html("<div class='alert alert-success bg-green'><a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a><strong>Successfully Inserted</strong> </div>");
                          }
                          else{
                                  $("#error").html("<div class='alert bg-red'><a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a><strong>Can't Insert</strong> </div>");
                          }
                   },

                   error: function(XMLHttpRequest, textStatus, errorThrown) { 
                        if (XMLHttpRequest.readyState == 4) {
            // HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)

            $("#error").html("<div class='alert bg-yellow'><a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a><strong>HTTP Request Error</strong> </div>");

        }
        else if (XMLHttpRequest.readyState == 0) {
            // Network error (i.e. connection refused, access denied due to CORS, etc.)
            $("#error").html("<div class='alert bg-yellow'><a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a><strong>Please Check Your Network Connection</strong> </div> ");

        }
        else {
            // something weird is happening
             $("#error").html("<div class='alert bg-yellow'><a href='#' class='close' data-dismiss='alert' aria-label='close'>&times;</a><strong>Some Error Occured</strong> </div>");
        }

                   }
              });
            }

        });

      });
    </script>

core/dbconnect.php

<?php
error_reporting( E_ALL & ~E_DEPRECATED & ~E_NOTICE );
if(!mysql_connect("localhost","root",""))
{
    die('oops connection problem ! --> '.mysql_error());
}
if(!mysql_select_db("admin"))
{
    die('oops database selection problem ! --> '.mysql_error());
}

?>

core/news-post-process.php

<?php
session_start();
include_once 'dbconnect.php';

if(isset($_POST['newsHeading']) && isset($_POST['newsSource']) && isset($_POST['newsContent']))
{
  $newsHeading = mysql_real_escape_string($_POST['newsHeading']);
  $newsSource = mysql_real_escape_string($_POST['newsSource']);
  $newsContent = mysql_real_escape_string($_POST['newsContent']);

  /*$newsHeading = trim($newsHeading);
  $newsSource = trim($newsSource);
  $newsContent = trim($newsContent);*/

  $query = mysql_query("INSERT INTO `news`(`news_heading`,`news_source`,`news_content`) VALUES('".$newsHeading."','".$newsSource."','".$newsContent."')");


if ($query) {
        echo "Sucess";
    }
    else{
        echo "Failed";

    }
}


?>

Why jQuery and AJAX won't work well ??

change your form tag to this....

     <form class="form-horizontal" role="form" name="newsForm">
    </form>

When it comes to using ajax to post data , u notice you are writing the method in ajax call itself like:

 $.ajax({
    method:"post",

    });   

So you don't need it in form tag to mention post method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM