phpjqueryajaxxmlhttprequestresponsetext

Passing data to PHP from Jquery using ajax without refreshing


I asked a similar question already, but I wasn't able to get enough information. I tried reducing the code to just the what I needed for this to work.

I am trying to pass the php code a title variable and I want the php code to give me a success message when it finishes. I wanted to do this without refreshing the page.

When I run this code without the ajax bit in there, it will let me click the button and it will preform the checks without refreshing. But once I put the ajax code in, it will not preform the checks and it WILL refresh. It also doesn't run any checks in the php code.

Am I using the ajax code wrong? How can I get this to send the data to the php file without refreshing and send me back a success message?

EDIT: I added in the brackets around the data being sent to the php file. Now the "fill out the form" check works. But when the form is filled out the success check isn't returning from the php file.

EDIT2: I inserted .val() into the initiation statement and removed the .val() from the if statement. I removed the onclick attribute from the button. And updated the data in JS to "data: {title1:title},". So far status remains the same.

EDIT3: I added "dataType: JSON," as well as some error/success codes. Thank you Ron for your help with that. Now when I submit I get an xhr status of 500 with a blank response text. I've been looking around for a solution, but nothing so far.

EDIT4: I changed the title1's to title's so that there was no longer a confusion on that. Now it's working correctly! Thank you Ron for your help.

<?php
//getting values from JS
$title = $_POST['title'];

if(!$title == "")
{
  $res="Data received successfully:";
  echo json_encode($res);
}
else {
  $error="Not received,some problem occurred.";
  echo json_encode($error);
}
?>
<!DOCTYPE html>
<html>
  <head>
	<meta charset = "utf-8">
	<title>Insert</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<script type="text/javascript">
		$(document).ready(function () {
			$('#form').submit(function (e) {
				e.preventDefault();
			
				//debug
		 	var x =  document.getElementById("msg");
		 	var title = $('#title').val();
		 	var year = $('#year').val();
		 	var director = $('#director').val();
		 	var genre = $('#genre').val();
		 	var runtime = $('#runtime').val();
    			
    			
    			if( title=="" || year=="" || director=="" || genre=="" || runtime=="" ) {
    				x.style.color = "red";
    				x.innerHTML = "Please fill out all of the blanks.";
    			} else {
    				//is the value being sent correct?
    				x.style.color = "lightGreen";
    				x.innerHTML = "Title is: "+title+ 
    						"<br>Year is: "+year+
    						"<br>Director is: "+director+
    						"<br>Genre is: "+genre+
    						"<br>Runtime is: "+runtime;
    				
    				$.ajax({  
					type: "POST",
					url: "insert_DVD.php",
					data: {
						title: title,
						year: year,
						director: director,
						genre: genre,
						runtime: runtime,
						},
					dataType: "JSON",
					error: function(xhr, ajaxOptions, thrownError, data) {
						alert(xhr.status);
						alert(thrownError);
						alert(xhr.responseText);
						console.log(data);
					},
					success: function(data) {
				                console.log(data);
				            }
    				});
	    				return false;
	    			}
			 });
		});
	</script>
    <link rel="stylesheet" href="webpage.css">
  </head>
  <body class="subStyle">
   
	<div class="topnav">
  		<a href="#">Home</a>
  		<a href="#">Database</a>
  		<a class="active" href="#">Insert</a>
	</div>
	
	<form id="form" method="post">
		If there is more than one director, separate with comma.
		<table border=0>
		<tr>
		<th>Movie Title</th>
		<th>Year Made</th>
		<th>Director</th>
		<th>Genre</th>
		<th>Runtime(Minutes)</th>
		</tr>
		
		<tr>
		<td><input type=text name="title"    id="title"    maxlength=100 size=30></td>
		<td><input type=text name="year"     id="year"     maxlength=4   size=10></td>
		<td><input type=text name="director" id="director" maxlength=100 size=30></td>
		<td><input type=text name="genre"    id="genre"    maxlength=20  size=20></td>
		<td><input type=text name="runtime"  id="runtime"  maxlength=4   size=20></td>
		</tr>
		
		<tr><td>
		<button type="submit" id="update" value="send">Update Database</button></td></tr>
		</table>
	</form>
	
	<p id="msg">Click the update button.</p>
   </body>
</html>


Solution

  • I'm not at my dev computer so I can't really test the php side of things but you do have two javascript errors, one of which might be causing the issue.

    Not causing your issue but causing an error in the console.

    1) Remove the passData() function from the onclick. It's not needed since you're watching for the form submission already with the .submit.

    Might be causing your issue

    2) When you're defining "title1" you're not getting its value which will cause an HTMLFormElement.toString error when submitting the form currently. Instead go ahead and get the value when defining title 1 via:

    $('#title').val();

    and then remove title1.val() out of the if statement where you check if its been populated and instead just put title1 == ""

    Right now you're sending an HTML element via that ajax call which will cause jquery to fail. Put another way you currently are sending:

    data: {title: (HTML ELEMENT)}
    

    Let me know if that fixes it or not. If it doesn't I'll pull this up when I get to where I can run PHP.

    EDIT: Also, as pointed out in one of the comments you'll need to change your PHP to be $_POST['title'] in order to match what you're sending. You can verify what is happening on the php side of things by echoing out some errors. It's been a really long time since I've done any php but I would usually do something like:

    error_reporting(E_ALL & ~E_DEPRECATED);
    ini_set('display_errors', 1);
    

    At the top of my scripts while working on them in order to debug them. This will pass the error from php back to the Ajax response if there is one. That was back in PHP 5 days though.

    EDIT2: This is how I got it to work

    test.php

    <?php
      //getting values from JS
      $title = $_POST['title'];
    
      if(!$title == "") {
        $res="Data received su ccessfully:";
        echo json_encode($res);
      } else {
        $error="Not received,some problem occurred.";
        echo json_encode($error);
      }
    ?>
    

    index.html just the ajax part:

    $(document).ready(function() {
    $('#form').submit(function(e) {
        e.preventDefault();
    
        //debug
        var x = document.getElementById("msg");
        var title1 = $('#title').val();
    
    
    
        if (title1 == "") {
            x.style.color = "red";
            x.innerHTML = "Please fill out all of the blanks.";
        } else {
            $.ajax({
                type: "POST",
                url: "test.php",
                data: {
                    title: title1
                },
                dataType: "JSON",
                error: function(xhr, ajaxOptions, thrownError) {
                    alert(xhr.status);
                    alert(thrownError);
                    alert(xhr.responseText);
                },
                success: function(data) {
                    console.log(data);
                }
            });
            return false;
    
        }
    });
    });
    

    Unfortunately I don't have the time right now to explain what was changed but I will get to that tomorrow! (Hopefully :)

    Also, I did not put the success message in the html, I forgot, and instead am console.logging the response which you can see in the browser console. Sorry I wish I had more time tonight to respond.