0

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?

13
  • your event.preventDefault() ; is missing .e.preventDefault(); is not working. Commented Nov 29, 2015 at 18:19
  • Not working with event, too...I tried to add action in form but then it says wp-admin/admin-ajax/name of action didn't found.... Commented Nov 30, 2015 at 6:29
  • your binding is making it execute in wrong time. Commented Nov 30, 2015 at 6:49
  • No matter where I put event.preventDefault(); it gives me same thing. Reloads page without executing inserting... Commented Nov 30, 2015 at 6:57
  • if your page is reloading your javascript is not working to make an ajax request.you have to find out why, I could have tried to generate the same problem,but not possible now. Commented Nov 30, 2015 at 7:00

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

and just to add - don't forget to put data in this format data: {location1: location1, location2: location2, price: price}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.