PHP not delivering a variable via AJAX

I've noticed that there are similar questions on this platform, but I've spent my entire day researching and fixing bugs to figure out why my ajax code doesn't return a response from the php file. All I need is for it to notify me when a user has been registered so that they can proceed with the signing up process. I just need someone's guidance to help me identify what I'm doing wrong!

Instead of going through the validation part of the js file, I'll focus on the ajax code.

  if(ValidationComplete == true){
   var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};

that.find('[name]').each(function(register, value) {
    var that = $(this),
        name = that.attr('name'),
        value = that.val();

        data[name] = value; 
});

    $.ajax({
    url:url, 
    type:type,
    data: data,
    dataType: 'json', 
    success: function(result){
        alert(result.status);
        console.log(result.data);

    },
error: function(xhr, textStatus, error){
  console.log(xhr.statusText);
  console.log(textStatus);
  console.log(error);
   }        

});

return false;
} else {
    return false;
}

Currently, if I remove the dataType part, the alert works, but nothing happens when it's included.

Let's move on to the important part - the php file.

    $query = "INSERT INTO person 
   VALUES('','$first_Name','$surname','$email','$dob','$password',
  '1','','0','1','','','','$emailCode')";
  if($query_run =mysql_query($query)) {
      echo json_encode(array("response"='true'));

Any help would be greatly appreciated!

Updated code:

  <?php    

if( isset($_POST['firstname']) && 
isset($_POST['surname']) && 
isset($_POST['email']) && 
isset($_POST['day']) && 
isset($_POST['month']) && 
isset($_POST['year']) && 
isset($_POST['password']) && 
isset($_POST['re_type_password'])){

  $first_Name = $_POST['firstname'];
  $surname = $_POST['surname'];
  $email = $_POST['email'];
$password = $_POST['password'];
$day = $_POST['day'];
$month = $_POST['month'];
$year = $_POST['year'];
$re_type_password = $_POST['re_type_password'];
$emailCode = md5($_POST['$first_Name'] + microtime());

if(!empty($first_Name)&& 
!empty($surname)&& 
!empty($email)&& 
!empty($day) && 
!empty($month) && 
!empty($year) && 
!empty($password)&&                                   
!empty($re_type_password)){



  if(strlen($firstname)>30 || strlen($surname)>30 || strlen($email)>50){
  echo 'the data enetered is to long';
} else {
  if($password != $re_type_password){
  echo 'passwords do not match, please try again.';
} else{ 
$query = "SELECT email FROM person WHERE email ='$email'";
$query_run = mysql_query($query);
if(mysql_num_rows($query_run)==1){
  echo 'Email address already on database';         
} else{
  if($day>31 || $month>12){
    echo 'date of birth wrong';
  } else{

    $dob= $year.'-'.$day.'-'.$month;
  $query = "INSERT INTO person 
  VALUES('','$first_Name','$surname','$email','$dob','$password'
   ,'1','','0','1','','','','$emailCode')";
   if($query_run =mysql_query($query)) {
      email($email, ' Email Confirmation', "Hello ". $first_Name." ,
    \n\nYou need to activate your account. Please click the link provided.");
    $return_data['status'] = 'success';
     echo json_encode($return_data);
  } else {
      echo @mysql_error();
  }

}

 }

  } 
  }

  } else {
      echo "<p id='error'> All fields are required. Please try again.</p>";

  }
      }

   ?>

  <?php
  } else if (loggedIn()) {

echo 'you are already registered and logged in';

   }


  ?>

   </body>
  </html>

Answer №1

This is the updated final line

echo json_encode(array("response"=> 'true'));

Notice the additional > present in the array declaration, used for assigning arrays with keys.

In general, it is recommended to include error handling in your ajax statement. You can find more information on this topic by referring to this answer.

EDIT: Wow! Your code seems quite messy, but after some cleanup, I found that you have an issue of excessive closing braces }. Please remove the } just before the following line and also eliminate the unnecessary opening and closing tags surrounding this line as they serve no purpose.

} // <------ THIS ONE!

} else if (loggedIn()) {

    echo 'you are already registered and logged in';

}

I would like to highlight two other problems with your code:

  1. You are accepting user input without properly sanitizing and validating it. This practice is highly discouraged. For more details, please read this article.
  2. You are using deprecated mysl_ functions, which are insecure. Instead, consider switching to PDO, a safer alternative.

EDIT:

To resolve any potential errors, add ini_set('error_reporting', 1); at the beginning of your PHP script.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When utilizing Javascript's Array.push method, a nested array is generated that is inaccessible using the index

I have reviewed several articles discussing the issue of asynchronous calls returning undefined. Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference Get data from fs.readFile However, none of these articles ...

Adding parameters to TR or TDs in DataTables 1.10.5 via Ajax: A step-by-step guide

My goal is to dynamically load datatable data using AJAX and customize the rows and cells by adding parameters such as classes or 'data' attributes. The challenge lies in utilizing a PHP helper that generates JavaScript code, as shown below: $da ...

Retrieve the character count of the text within a dynamically created div using AJAX

I have a .php file containing an array of strings. One of these strings is fetched by my page and inserted into an empty div named post. However, when I try to determine the length of the string in the post, I always receive the error: Uncaught TypeErro ...

Stop the slider when a video pops up

Years ago, I had a slider created for me that supports both images and video with a timer. However, the issue I'm facing is that when the timer runs every 10 seconds, the video gets cut off if it's not finished playing. Below is the json file st ...

The attempt to remove a cookie through a Next.js server-side operation was unsuccessful

Having trouble removing a cookie using the next/headers module in my Next.js application. The code snippet below is what I've tried: import {cookies} from "next/headers"; export default async function Signout() { async function deleteTok ...

Ways to ascertain if a view has completed rendering in JavaScript

I am currently building my application using the awesome backbone.js framework. Within my code, I have this layoutView that handles rendering the overall layout and also includes a smaller profile section. The dilemma I'm facing is with the timing o ...

Route Handler 13 is encountering difficulties in retrieving data from the body in the (app/api/auth) endpoint

Whenever I attempt to retrieve the body from the new export async function POST( req: Request), it seems to come through as a stream instead of the expected content type. The route handler can be found in api/auth/signup See folder layout image export asyn ...

Tips for displaying previous values when discarding changes to a record in a material-ui table

How can I prevent changes from reflecting in a material-ui table when clicking on the X icon while editing a row? Is there a way to only save the edited record on the check (_) icon instead? Any suggestions or solutions would be greatly appreciated as I am ...

What methods can I employ to utilize the name attribute for POST requests instead of the ID attribute in TinyMCE?

My inline TinyMCE form sends content to qry.php with the key "edit_me". I prefer the default behavior of sending content using the name attribute instead. <script type="text/javascript"> tinymce.init({ selector: '#edit_me', ...

Guide on utilizing automatic intellisense in a standard TextArea within a web application

I have successfully created an Online compiler web application that is currently running smoothly. However, I am now looking to enhance my application by implementing intellisense in the TextArea where the program is being typed. For instance, if I type "S ...

Personalized styling of PHP exception including gathered information

When working with PHP Exception sub classes, I often encounter scenarios where I need to gather data and then compile it into a final error message. For instance: One use case involves checking for contiguous days in the data. $missing = new MissingAdj ...

Tips for removing markers from personal Google Maps

I am having trouble deleting markers from my Google Maps using my code. The markers array seems to be empty even after adding markers. Can anyone help me troubleshoot this? Thank you! When I use console.log(markers.length) in the removeMarkers() function, ...

Unusual Quirks with the Range Setting in a jQuery

I am facing an issue with jQuery UI Slider. The slider in my code is not functioning properly. Instead of rendering two handlers, it only renders one. Additionally, the slider can only slide until the value 70, which corresponds to the second value in my a ...

Updating records in Laravel 5.3 by only modifying those that have changed, leaving unchanged records as they are

https://i.stack.imgur.com/X4FPd.pnghttps://i.stack.imgur.com/X4FPd.pngI have a requirement to only update the values in a profile that have been changed. The issue I am facing is that even the unchanged data gets updated when I try to update the record. M ...

Invoke the designated JavaScript function within a subordinate <frame>

Below is an example of the standard HTML structure for a parent page named "index.html": <html> <head> <title>test title</title> </head> <frameset cols="150,*"> <frame name="left" src="testleft.html"> ...

How can code be seamlessly executed between two jQuery animations?

Here is a piece of code I am working with that switches fullscreen background images by using fadeOut and fadeIn: setInterval(function() { var id = parseInt($('img.active').attr('id').substring(3,4)); var id_next = id; ...

The AJAX request to send data to PHP is not functioning correctly

I have an issue where I am trying to send data to my server using AJAX in PHP. Even though I have set the method as POST, it seems to be executing as a GET request instead. Here is the code snippet: $.ajax({ type: 'POST', data: { user: us ...

Retrieving ng-model using ng-change in AngularJS

Here is an example of the HTML code I am currently working with: <select ng-model="country" ng-options="c.name for c in countries" ng-change="filterByCountry"></select> This HTML snippet is being populated by the following object containing a ...

The module 'iap_verifier' could not be located

Setting up a new server using the following repository - https://github.com/surespot/web-server. I have successfully installed node.js, npm, CoffeScript, and all required dependencies. apt-get install nodejs npm npm install -g <a href="/cdn-cgi/l/email ...

find the index of the array-like name attribute in HTML using jQuery

In my code snippet, there is a simple structure like this: <div class="question_wrapper"> <input type="text" class="textinput_questions new_question" name="new_question[1][]"> <input type="checkbox" class="radioinput" na ...