Passing data to PHP from Jquery using ajax without refreshing

180
April 11, 2018, at 12:12 PM

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.

<?php 
//getting values from JS 
$title = $_POST['title1']; 
 
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>Cameron West - 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 title1 = $('#title').val(); 
			 	var year1 = $('#year').val(); 
			 	var director1 = $('#director').val(); 
			 	var genre1 = $('#genre').val(); 
			 	var runtime1 = $('#runtime').val(); 
	    			 
	    			 
	    			if( title1=="") { 
	    				x.style.color = "red"; 
	    				x.innerHTML = "Please fill out all of the blanks."; 
	    			} else { 
	    				$.ajax({   
						type: 'POST',   
						url: 'test.php',  
						data: {title1:title}, 
						dataType: "JSON", 
						error: function(xhr, ajaxOptions, thrownError) { 
						alert(xhr.status); 
						alert(thrownError); 
						alert(xhr.responseText); 
					}, 
					success: function(data) { 
				                console.log(data); 
				            } 
	    				}); 
	    				return false; 
	    			} 
			 }); 
		}); 
	</script> 
    <link rel="stylesheet" href="webpage.css"> 
  </head> 
  <body class="subStyle"> 
    
	<div class="topnav"> 
  		<a href="http://cameronwest.x10host.com/">Home</a> 
  		<a href="http://cameronwest.x10host.com/Webpage/databasePage.html">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>

Answer 1

May be it should be an object

data: {title1:title1}
Answer 2

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.

Rent Charter Buses Company
READ ALSO
creating dynamic variables in php to update multiple rows in MYSQL

creating dynamic variables in php to update multiple rows in MYSQL

I am currently working on an update profile section of a website I am creating for funIn this part of the update profile business owners can update their restaurant menu (menu consists of category (appetizers, entrees, etc), menu item and allergens)

114
Different header&#39;s background-color on each categories

Different header's background-color on each categories

I want to change a different background color of header for a categoryThe category is https://afdigitale

178
Codeigniter 404 page not found on server

Codeigniter 404 page not found on server

I deployed a Codeigniter application on the server and I cannot figure out what is causing an:

127
can not check JSON request php

can not check JSON request php

I am working with an API, when I will send them a request they will send me a JSON request to a link that I provided to them

155