Click here to Skip to main content
14,734,526 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i have a php form im trying to submit using ajax and its saving data properly but its always returning the error message not the success, any help please to go about it.


What I have tried:

this is the jquery ajax file.

$(document).ready(function() {
       var loader='<img src="https://media.giphy.com/media/11ASZtb7vdJagM/giphy.gif" />';
       
	   
	   //if submit button is clicked
     
		$('#submit').click(function () {       
			
			//show the loader
			$('.loading').html(loader).fadeIn();     
		  
			var prog_description = $('input[name=prog_description]').val();
			var type_of_contrib = $('select[name=type_of_contrib]').val();
			var benefit_factor = $('input[name=benefit_factor]').val();
			var budgeted_spend = $('input[name=budgeted_spend]').val();
            var actual_amount = $('input[name=actual_amount]').val();
            var current_status = $('select[name= current_status]').val();
            var anticipated_completion = $('input[name= anticipated_completion]').val();
           
			 
	 
			
			//organize the data properly
            var form_data = 
            
           'prog_description='+prog_description+
			'&type_of_contrib=' +type_of_contrib+
           '&benefit_factor='+benefit_factor+
            '&budgeted_spend='+budgeted_spend+
            '&actual_amount='+actual_amount+
            '¤t_status='+current_status+
            '&anticipated_completion='+anticipated_completion;

			 
			//disabled all the text fields
			$('.text').attr('disabled','true');
			 
			 
			//start the ajax
			$.ajax({
				//this is the php file that processes the data and send mail
				url: "process.php",
				 
				//POST method is used
				type: "POST",
	 
				//pass the data        
				data: form_data,    
				 
				
				//success
				success: function (html) {             
					//if process.php returned 1/true (send mail success)
					if (html===1) {                 
						//hide the form
						$('#fupForm').fadeOut('slow');                
						 
						 
						 //hide the loader
						 $('.loading').fadeOut();   
						 
						//show the success message
						$('.message').html('Successfully Registered ! ').fadeIn('slow');
						 
						 
						 
					//if process.php returned 0/false
					} else alert('Sorry, unexpected error. Please try again later.');              
				}      
			});
			 
			//cancel the submit button default behaviours
			return false;
    });
}); 
 
 
</script>


process.php file
<?php

session_start();
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "socio_economic");

// Check connection
if ($link === false) {
    die("ERROR: Could not connect. " . mysqli_connect_error());
}


// Prepare an insert statement
$sql = "INSERT INTO socio_spends (prog_description,type_of_contrib,benefit_factor,budgeted_spend,actual_amount,current_status,anticipated_completion) VALUES (?, ?, ?,?,?,?,?)";

if ($stmt = mysqli_prepare($link, $sql)) {
    // Bind variables to the prepared statement as parameters
    mysqli_stmt_bind_param($stmt, "sssssss", $prog_description, $type_of_contrib, $benefit_factor, $budgeted_spend, $actual_amount, $current_status, $anticipated_completion);

    // Set parameters
    $prog_description = (isset($_POST['prog_description']) ? $_POST['prog_description'] : '');
    $type_of_contrib = (isset($_POST['type_of_contrib']) ? $_POST['type_of_contrib'] : '');
    $benefit_factor = (isset($_POST['benefit_factor']) ? $_POST['benefit_factor'] : '');
    $budgeted_spend = (isset($_POST['budgeted_spend']) ? $_POST['budgeted_spend'] : '');
    $actual_amount = (isset($_POST['actual_amount']) ? $_POST['actual_amount'] : '');
    $current_status = (isset($_POST['current_status']) ? $_POST['current_status'] : '');
    $anticipated_completion = (isset($_POST['anticipated_completion']) ? $_POST['anticipated_completion'] : '');

 
    

    // Attempt to execute the prepared statement
    if (mysqli_stmt_execute($stmt)) {
        
        echo '1';

        $socio_id =mysqli_insert_id($link);

      $_SESSION['socio_id'] =$socio_id;
        
    } else {
        echo "ERROR: Could not execute query: $sql. " . mysqli_error($link);
    }
} else {
    echo "ERROR: Could not prepare query: $sql. " . mysqli_error($link);
}
  
header('Location:index.php');
// Close statement
mysqli_stmt_close($stmt);

// Close connection
mysqli_close($link);


exit();
Posted
Updated 17-Oct-19 3:59am
v2
Comments
F-ES Sitecore 16-Oct-19 9:52am
   
What is the contents of "html" in your success function? If it isn't "1" then step through your php code to examine what path the code is taking and why it isn't "1".
Member 14603400 16-Oct-19 9:59am
   
thanx lemme examine it

1 solution

I got it working thanks, here is my new code
<script>


    $(document).ready(function(){

var request;

$("#fupForm").submit(function(event){

    if(request){
      request.abort();

    }

    var $form=$(this);
    var $inputs=$form.find("input,select");
    var serializeddata=$form.serialize();
    $inputs.prop("disabled",true);
    request= $.ajax({
        url:"process.php",
        type:"post",
        data:serializeddata
    });

    request.done(function(response,textStatus,JqXHR){
     
        swal("Good job!", "You have succesifully saved your data!", "success");

    
        
    });

    request.fail(function(JqXHR,testStatus,errorThrown){
        console.error("Error occured"+ testStatus,errorThrown);
    });

    request.always(function(){
        $inputs.prop("disabled",false);
    });

    event.preventDefault();

    $("#fupForm").trigger("reset");




});



});

</script>
   
Comments
Member 14603400 17-Oct-19 9:01am
   
the only issue im having is i want to display the data with ajax but it isnt working without page refresh
Member 14603400 18-Oct-19 8:01am
   
solved it thanks

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

  Print Answers RSS
Top Experts
Last 24hrsThis month



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