Insert data into mysql database with php and ajax

2019-09-05 13:38发布

inside my function.php I added new top level admin menu. I added input fields and inside it and put it into html form element.

<form id="prices_form" method="post" action="">
    <div style=font-weight:bold;font-size:16px;>Location 1</div>
    <input id="location1" name="location1" type="text" />
    <input type="hidden" name="count" value="1" />
    <div style=font-weight:bold;font-size:16px;>Location 2</div>

    <input class="input" id="location2" name="location2" type="text" placeholder="Type something"/>
<div style=font-weight:bold;font-size:16px;>Price(KN)</div>
<input type="number" id="price" name="price" min="0" step="0.01"/><br>
<input id="submit" name="submit" type="submit" value="Save prices" />
</form>

Then I added php where I call ajax via ajax-admin.php and gives user possibility to use ajax. So I want to add input fields into database on submit click.

function ajax_savePrice(){
    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $location1 = $_POST['location1'];
    $location2 = $_POST['location2'];
    $price = $_POST['price'];

    $result = $conn->query("SELECT * FROM prices WHERE location1 = '$location1' AND location2='$location2' OR location1 = '$location2' AND location2='$location1'");
    $row_count = $result->num_rows;
    if ($row_count >= 1) {
        echo 'That locations are already inserted. Do you want to update price?';
    } else {
        $query = "INSERT INTO prices (location1, location2, price) VALUES(?, ?, ?)";
        $statement = $conn->prepare($query);

        //bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
        $statement->bind_param('ssi', $location1, $location2, $price);

        if ($statement->execute()) {
            print 'Success! ID of last inserted record is : ' . $statement->insert_id . '<br />';
        } else {
            die('Error : (' . $conn->errno . ') ' . $conn->error);
        }
        $statement->close();
    }

}

function ajax_savePrice_init(){

wp_register_script('ajax-savePrice-script', get_template_directory_uri() . '/ajax-savePrice-script.js', array('jquery') ); 
wp_enqueue_script('ajax-savePrice-script');

wp_localize_script( 'ajax-savePrice-script', 'ajax_savePrice_object', array( 
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'redirecturl' => home_url(),
'loadingmessage' => __('Sending data, please wait...')
));

// Enable the user with no privileges to run ajax_login() in AJAX
add_action( 'wp_ajax_nopriv_ajaxsavePrice', 'ajaxsavePrice' );
add_action( 'wp_ajax_ajaxsavePrice', 'ajaxsavePrice' );
}
add_action('init', 'ajax_savePrice_init');

And I made .js file to proccess ajax request:

jQuery(document).ready(function($) {

// Perform AJAX login on form submit
$('#prices_form').on('submit', function(e){

$.ajax({
    type: 'POST',
    dataType: 'json',
    url: ajax_savePrice_object.ajaxurl,
    data: { 
        'action': 'ajaxsavePrice', 
        'location1': $('#location1').val(), 
        'location2': $('#location2').val(), 
        'price': $('#price').val() },
    success: function(data){
        $('#prices_form').hide();

    }
});
e.preventDefault();
});

}); 

Page reloads and nothing happens...

Any hint?

EDIT:

I succeed to call ajax and added 3 echo-s to my php so I can get response via server.

$result = $conn->query("SELECT * FROM prices WHERE location1 = '$location1' AND location2='$location2' OR location1 = '$location2' AND location2='$location1'");
        $row_count = $result->num_rows;
        if ($row_count >= 1) {
           // echo 'That locations are already inserted. Do you want to update price?';
            echo 'exist';
        } else {
            $query = "INSERT INTO prices (location1, location2, price) VALUES(?, ?, ?)";
            $statement = $conn->prepare($query);

            //bind parameters for markers, where (s = string, i = integer, d = double,  b = blob)
            $statement->bind_param('ssi', $location1, $location2, $price);

            if ($statement->execute()) {
               // print 'Success! ID of last inserted record is : ' . $statement->insert_id . '<br />';
                echo 'yes';
            } else {
                //die('Error : (' . $conn->errno . ') ' . $conn->error);
                echo 'no';
            }
            $statement->close();
        }

Now in my js:

    location1=$("#location1").val();
    location2=$("#location2").val();
    price=$("#price").val();
data: "location1="+location1+"location2="+location2+"price="+price,
        success: function(html){
          if(html==='exist')
          {
            $("#prices_form").fadeOut("normal");        
          }
          else
          {
               $("#aaa").fadeOut("normal"); 
          }
        },
        beforeSend:function()
        {

        }
    });
     return false;
    });

So whatever I enter in my input fields and post to php I got this else part. I tried with all 3 states that php can return to js but always else get executed.

Any hint now?

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-05 14:10

Name your form in html as -

<form id="prices_form" name="pricesForm" method="post" action=""> 

Try JSON.stringify() data before sending with the AJAX like below -

var data = JSON.stringify({ 
    action: 'ajaxsavePrice', 
    location1: $('#location1').val(), 
    location2: $('#location2').val(), 
    price: $('#price').val() 
});

And then replace your ajax call on form submit as below-

$('form.pricesForm').on('submit', function(e){
  e.preventDefault();
  $.ajax({
   method: 'POST',
   dataType: 'json',
   url: ajax_savePrice_object.ajaxurl, // also check this if it returns the correct url
   data: data,
   success: function(res){
     $('#prices_form').hide();
   }
  });

});

Hope this helps.

查看更多
登录 后发表回答