Member 14603400 Ответов: 1

Моя подача форм PHP, jquery, ajax не работает


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.


Что я уже пробовал:

это файл jquery ajax.

$(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 файл
<?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();

F-ES Sitecore

Каково содержание" html " в вашей функции успеха? Если это не "1", то пройдите через свой php-код, чтобы проверить, какой путь принимает код и почему он не "1".

Member 14603400

спасибо, дай мне осмотреть ее

1 Ответов

Рейтинг:
10

Member 14603400

Я получил его работать спасибо, вот мой новый код

<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>


Member 14603400

единственная проблема с которой я столкнулся это то что я хочу отобразить данные с помощью ajax но он не работает без обновления страницы

Member 14603400

решил это спасибо