-1

Ive been trying to create a div on my index page that onclick calls a js function that would submit the data to a php page for calculations and mysql queries. but not only does my chrome developers tools show that no POST request is even happening, but the page just refreshes the minute i click the submit button. my event handler on the main php page is onclick, which should lead to this function

    function submitvote(uv){
 $('#rank_IFC').html('<img src="ajax-loader.gif">').show();
 var sortdata = $('ul.sort').sortable('toArray').join(',');
 var url= "results.php";
 $.post(url, {Tablename:uv, sortdata: sortdata}, function(){
     $('#rank_IFC').html('').show();
    });
    }

which should than lead to my php conditional,

  <?php  if(!defined('INCLUDE_CHECK')) die('You are not allowed to execute this    file directly');
   // Including file for the DB connection:
    require 'connect.php';

  // If the poll has been submitted:
  $tablename=$_POST['Tablename'];


   if($tablename=='IFC')
 {     

    $userOrder=$_POST['sortdata'];


// The data arrives as a comma-separated string,
// so we extract each post ids:
$data=explode(',',str_replace('li','',$_POST['sortdata']));



    // Getting the number of objects
list($tot_objects) = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM sort_objects"));

if(count($data)!=$tot_objects) die("Wrong data!");

foreach($data as $k=>$v)
{
    // Building the sql query:
    $str[]='('.(int)$v.','.($tot_objects-$k).')';
}

$str = 'VALUES'.join(',',$str);



// This will limit voting to once a day per IP:
mysql_query("   INSERT INTO `sort_votes` (ip,date_submit,dt_submit,userOrder,Tablename)
                VALUES       ('".$_SERVER['REMOTE_ADDR']."',NOW(),NOW(),$userOrder,$tablename)");

//  If the user has not voted before today:
if(mysql_affected_rows($link)==1)
{

mysql_query('   INSERT INTO `IFC` (id,votes) '.$str.'
                    ON DUPLICATE KEY UPDATE votes = votes+VALUES(votes)');
}


  }

my main index page is in php. my question is, why is no AJAX post request being made when the function is called?

  • Have you watched the request / response in your browser's console? In addition, please [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and consider using PDO, [it's not as hard as you think](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard May 27 '15 at 16:53
  • How are you calling that function? It's probably the case that you've also got a `
    ` on the page, and that the form is being submitted.
    – Pointy May 27 '15 at 16:54
  • yes, by default it's asynchronous. You have to explicitly say you want a synchronous call. Your sql code is vulnerable to [sql injection attacks](http://bobby-tables.com), and probably suffering from syntax errors as well - since you have absolutely NO error handling in there, you'll never be able to tell. – Marc B May 27 '15 at 16:54
  • Are there any errors on your console? – crc442 May 27 '15 at 16:55
  • 1
    You might need to prevent the default behavior of the submit too. – frz3993 May 27 '15 at 16:59
  • yes it is asynchronous until you specify it to be synchronous explicitly. – Sourabh Kumar Sharma May 27 '15 at 17:03
  • Seems to be a problem with your events not the functions itself. We can't tell how you register the onclick event and if you are stoping the submit event, so more html and/or js code is required to find the problem. – MinusFour May 27 '15 at 17:10

2 Answers2

0

$.POST and all other AJAX calls are asynchronous by default, but you can make it synchronous by changing async to false.

A better fix though would be to prevent event propagation. Because the call is asynchronous, the function submitvote continues to execute, and you have nothing in to prevent it from propagating the event to other listeners. To fix this, you should return false at the bottom of submitvote. See here for more details.

Also, you should probably use $.submit to listen to form submissions rather than button clicks. This will capture, e.g. form submissions done via keyboard.

ysimonson
  • 1,072
  • 2
  • 9
  • 16
0

From the doc By default, all ajax requests are sent asynchronously (i.e. async set to true by default). If you need synchronous requests, set async: false.

$.post() is a shorthand Ajax function

As for your problem, I would assume (and also suggest that) your submit event look like the following provided you've a voting form (like the one at the end).

$('#myForm').on("submit", function(evt) {
    evt.preventDefault();
    submitvote("yourParam");
});

function submitvote(uv) {
    $('#rank_IFC').html('<img src="ajax-loader.gif">').show();
    var sortdata = $('ul.sort').sortable('toArray').join(',');
    var url= "results.php";
    $.post(url, {Tablename:uv, sortdata: sortdata}, function(){
        $('#rank_IFC').html('').show();
    });
}

And the form may look like this:

<form id="myForm">
    <!-- ... more input elemenst -->
    <input type="submit" value="Submit Me" />    
</form>
lshettyl
  • 8,166
  • 4
  • 25
  • 31