Click here to Skip to main content
15,886,724 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
I am doing an ajax request using PHP and jQuery but it is not working, also there is no error message. How can I know the issue and fix it? Here is item_check.php code:
PHP
<?php
if(isset($_POST['item_check'])){
  $itemNo = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '',
  (isset($_POST['itemNo']) && $_POST['itemNo'] != ''?sanitize($_POST['itemNo']):''));
  $title = preg_replace('/^\s+|\s+$|\s+(?=\s)/', '',
  (isset($_POST['title']) && $_POST['title'] != ''?sanitize($_POST['title']):''));
  $sql = $db->prepare("SELECT * FROM products WHERE itemNo = ? OR title = ?");
  $sql->bind_param('ss', $itemNo, $title);
  $sql->execute();
  $result = $sql->get_result();
  if($result->num_rows > 0){
    while($row = mysqli_fetch_assoc($result)){
      if($itemNo == $row['itemNo']){
          echo "taken1";
        }else{
          echo 'not_taken1';
        }
      if($title == $row['title']){
      echo "taken2";
        }else{
      echo 'not_taken2';
      }
    }
  }
}
?>

and here is products.php code:
HTML
<input name="itemNo" id="itemNo" class="form-control" value="<?=$itemNo;?>">
<input name="title" id="title" class="form-control" value="<?=$title;?>">

JavaScript
<script>
$(document).ready(function(){
$('#itemNo, #title').on('keyup', function(){
         var itemNo = $('#itemNo').val();
         var title = $('#title').val();
         if (itemNo == '') {
          $( "#itemNo" ).removeClass( "is-valid is-invalid" );
         	return;
         }
         if (title == '') {
          $( "#title" ).removeClass( "is-valid is-invalid" );
           return;
         }
         $.ajax({
           url: 'ajax/item_check.php',
           type: 'post',
           data: {
           	'item_check' : 1,
           	'itemNo' : itemNo,
            'title' : title,
           },
           success: function(response){
             if (response == 'taken1' ) {
              $( "#itemNo" ).removeClass( "is-valid is-invalid" );
              $( "#itemNo" ).addClass( "is-invalid" );
            }else if (response == 'not_taken1') {
              $( "#itemNo" ).removeClass( "is-valid is-invalid" );
              $( "#itemNo" ).addClass( "is-valid" );
            }
            if (response == 'taken2'){
              $( "#title" ).removeClass( "is-valid is-invalid" );
              $( "#title" ).addClass( "is-valid" );
            }else if (response == 'not_taken2'){
              $( "#title" ).removeClass( "is-valid is-invalid" );
              $( "#title" ).addClass( "is-valid" );
           }
          }
         });
        });
});
</script>


What I have tried:

What's wrong with my code, and how to check the error and fix it?
Posted
Updated 6-May-22 20:12pm
v3
Comments
Richard Deeming 5-May-22 4:19am    
Define "not working". If you use your browser's developer console, do you see the AJAX request? If so, what is the exact content of the response?
FRS4002 5-May-22 4:41am    
In short, the aim of this code is to check if the item number and title is available in the database, if item number is available in the database change the input color into red and show a red exclamation mark else make input green and show a green check mark, same thing to title. So, these colors are not working... Also, where and how to see exactly ajax request in developer console?
Richard Deeming 5-May-22 4:47am    
For Chrome / Edge:
Inspect network activity - Chrome Developers[^]

For Firefox:
Network Monitor — Firefox Source Docs documentation[^]
Depending on your settings, AJAX requests may also be visible in the Browser Console[^]
FRS4002 5-May-22 4:58am    
Ok, there is no ajax request. I've tried on a working code and I see the ajax request, but the code that has the issue there is no ajax request
Richard Deeming 5-May-22 5:01am    
So either the keyup event isn't firing; or one of the fields is empty, meaning you return from the event handler before getting to the AJAX request.

Set a breakpoint on the first line of the event handler and step through it to see which is the case.

1 web browser use CHROME or MS EDGE, press F12 ,see CONSOLE
2 install http sniffe software FIDDLER ,https://www.telerik.com/fiddler
3 open PHP error log in PHP.INI,
error_reporting = E_ALL

display_errors = On

log_errors = On

error_log="D:\SERVER\Logs\php56_errors.log"

---------------
YOU will get error msg in browser console, or http request in fiddler, or php logs
 
Share this answer
 
v2
Comments
FRS4002 5-May-22 4:13am    
@long ware I already said before there are no errors in console. Regarding software fiddler there are 5 products, what products should I use ?? and how to use it ?? Also, there are no errors in php logs regarding this issue. Could you please check my code and tell me where is the error or what's wrong in my code ??
Member 15627495 16-May-22 15:52pm    
you are on a good syntax and spelling, but no effects, nothing happens..
debug by Js engine is lightweight.
Hello !

HTML and JS/Jquery :
you use same name="value_name" and id="value_name" , that is an error in your form and html declaration. id's are single or it leads to one more bug.

Don't use same value for this descriptor, your DOM is lazy so action on page are failing.

in all your jquery calls ,use concatenation to pick in a selector ( id and class ) , so : $(''+myselector+'') // with selector like [ #something ; or .myclass ] // it's 2 single quote, not the double quotes.
you can do this too :
$('#'+selector_from_submit_and_on_click+'').myjqueryfunction_call();

//+ is concatenating operator in JS.


about the function( response ) , it's tail of your function but written too fast..
write it again with a switch / case, and call a new function in, because you just add a class or avoid it ...you write 4 time addclass / remove class ,
group your code when you have twice the same function to use ( in one another function to call )
I suggest you to use switch / case statements because embeded if elseif chaining is too confusing so hard to read and fix.

Php :

explode your source code, group your functions too.

you know $_POST is an ARRAY , so a loop will fetch it perfectly

in a loop you can call all functions needed to act on values in your array.

It's not an error to sanitize the content values in $_POST through $_POST and a loop,

foreach($_POST as $item){
if(!empty($item)){
// if isset==true :: empty could be true;
// if !empty==true :: isset is already true;

preg_replace($item,'reg_exp_pattern');
sanitize($item);
}
}
so the content of $_POST will be ready for the following processing instructions.


but [ $new_var = $_POST['value_1']; ] is irrelevant , and useless in code.

less code to write every time. and a real $_POST use, it's already a container at server level.


AJAX : one important thing ,

every time you 'echo $var' , a data is sent.
so your ajax response will be several instead of just one.
by ajax you really can abuse of 'echo' ..
with multiple echo or a loop , it's always sent. ( echo -> ajax:(response) )
 
Share this answer
 
v5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900