• Resolved AnotherChance

    (@anotherchance)


    I have created a simple form to insert data into a custom table. The problem is that while the Ajax request is recieving data, it is not passing that data onto the server to update the database any help will be appreciated.

    First the code for the form.

    <!DOCTYPE html>
    	<html>
    		<head>
    		<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    		<script src="<?php bloginfo('stylesheet_directory'); ?>/tset.js"></script>
    		</head>
    		<body>
    			<form method="get" name="testForm" id="testForm" action="https://www.paygate.co.za/paywebv2/process.trans">
    				<table>
    					<tr>
    						<td><label for="firstName">Name</label></td>
    						<td><input type="text" id="firstName" name="firstName" /></td>
    					</tr>
    					<tr>
    						<td><label for="lastName">Surname</label></td>
    						<td><input type="text" id="lastName" name="lastName" /></td>
    					</tr>
    					<tr>
    						<td><label for="age">Age</label>
    						<td><input type="number" id="age" name="age" min="0" max="100" /></td>
    					</tr>
    					<tr>
    						<td><input type="hidden" name="myHiddenField" id="myHiddenField" value="this is hidden" /></td>
    					</tr>
    					<tr>
    						<td><button name="submit" id="submit">Update</button><td>
    					</tr>
    				</table>
    			</form>
    		</body>
    	</html>

    Then the code for the PHP

    global $wpdb;
    
    		$table = "tset";
    		$data = array(
    			"First_Name" => $_POST["firstName"],
    			"Last_Name" => $_POST["lastName"],
    			"Age" => $_POST["age"],
    			);
    			array(
    			"%s",
    			"%s",
    			"%d",
    			);
    		$wpdb -> insert($table, $data);
    
    		$response = array("myHiddenField" => "this is now filled in");
    
    		echo json_encode($response);

    Finally the js.

    $j = jQuery.noConflict();
    
    $j(document).ready(function(){
    	$j('#testForm').submit(submit_testForm);
    });
    
    function submit_testForm() {
    		$j.ajax({
    			url: "https://localhost/wordpress/wp-content/themes/responsive-mobile-child/tset.php",
    			type: "POST",
    			data: console.log($j('#testForm').serialize()),
    			dataType: 'json',
    			success: testForm_success
    		});
    		return false;
    	}
    
    function testForm_success() {
    	$j("#myHiddenField").val(response.my_hidden_field);
    	document.forms["testForm"].submit();

Viewing 15 replies - 1 through 15 (of 18 total)
  • Have you tried this ajax in wp
    , the code which you shown is not the right way in wp, like the url must be wp-admin/admin-ajax.php and there should be variable named “action” , check it once, i think you will figure out ??

    Thread Starter AnotherChance

    (@anotherchance)

    Hi thanks for this. I have read the documentation and done a few tutorials but for some reason I am getting stuck at the ajaxurl. It keeps giving me, Uncaught ReferenceError: myAjax is not defined.

    I am about to pull my hair out.

    Check my below implementation of working ajax example and compare with yours.
    HTML part

    <a href="#" id="testajax_click">Shoot Ajax</a>

    Jquery part

    <script type="text/javascript">
    jQuery(document).ready(function(){
    
    	jQuery('a#testajax_click').click(function(){
    
    		jQuery.ajax({
    
    			url:"<?php echo admin_url('admin-ajax.php') ?>",
    			type:'POST',
    			data:{
    				action:'custom_action',
    				testvar:"test value"
    			},
    			success:function(response){
    			alert(response);
    			}
    
    		});
    
    	});
    
    });
    </script>

    PHP code

    function custom_action_callbk(){
    
    	if(isset($_POST)){
    
    		echo $_POST['testvar'];
    
    	}
    	die;
    
    }
    
    add_action('wp_ajax_custom_action','custom_action_callbk');
    add_action('wp_ajax_nopriv_custom_action','custom_action_callbk');

    PHP code should go to functions.php

    Thread Starter AnotherChance

    (@anotherchance)

    Thanks, I have done this. When I submit I get a 404 (Not Found) for the admin-ajax.php file. And that is coming from jquery.min.js:4

    Thread Starter AnotherChance

    (@anotherchance)

    Just a quick question. I am using this ajax request to update a custom form. Does it make any difference as to how the scripts are enqueued? also do i reference the .js in the head even though I have enqueued the script?

    the script must be enqueued through wp_enqueue_script function and if you have already enqueued that then dont need to include in head section again.

    @anotherchance

    order of code in jquery is very important; as for first to input and second to output and then in loop.

    if order is not well written, it can easily ruin code,

    @swayam

    not really, jquery is called on any page or front page of WP, but, to put it plain, it’s still ajax in DOM but improved. That’s why input/output is so important. If HTML > Jquery > any call of php or api is well written it will work in a single way route.
    But something can’t be done on a LAMP server, like full rewrite of html data or fields WITHOUT REFRESHING PAGE, it’s just because we are not on node.js or other. To use some data, it must be posted or refreshed in real time (or use a call to action to send data to “next page”.
    Something not possible with Apache ‘as is’.

    Without changing page, it’s real time data exchange, i think it’s node.js or so. That’s why it’s so cool, real time i/o (with a little delay aka 1/2 s max).

    Ajax and what we can do here are great, but, limited a bit. I don’t think you can pull a response of Jquery or database without refreshing a WP page.

    But ultimately, the coordination of PHP, Jquery and CSS leads to great UI and great things, I love the topic ??

    (note: I could try to help this code, but it wil not output with refresh). But it’s a great one by the way, one the best i saw in years.

    @swayam

    By the way, this coordination of html, Jquery, and PHP is perfect?

    Any bug in it? I don’t see any.

    ah, found some in Jquery part, even if you use old Jquery:

    <script type="text/javascript">
    $ready(function(){
    
    	jQuery('a#testajax_click').click(function(){
    
    		jQuery.ajax({
    
    			url:"<?php echo admin_url('admin-ajax.php'); ?>",
    			type:'POST',
    			data:{
    				action:'custom_action',
    				testvar:"test value"
    			},
    			success:function(response){
    			alert(response);
    			}
    
    		});
    
    	});
    
    });
    </script>
    Thread Starter AnotherChance

    (@anotherchance)

    Thanks for the response. I have managed to sort out the url problem but it is still not adding the data to the table. I now have a Uncaught TypeError: document.forms.testForm.submit is not a function in the console.

    I have amended the code as follows.

    js

    jQuery(document).ready(function(){
    	jQuery('#testForm').submit(submit_testForm);
    });
    
    function submit_testForm(){
    	jQuery.ajax({
    		url: '../wp-admin/admin-ajax.php',
    		type: 'POST',
    		data: $(this).serialize(),
    		dataType: 'json',
    		success: testForm_success
    	});
    	return false;
    }
    
    function testForm_success(response){
    	jQuery('#my-hidden-field').val(response.my_hidden_field);
    	document.forms['testForm'].submit();
    }

    php, in the functions.php

    function addUser(){
    		global $wpdb;
    
    			$name = $_POST['firstName'];
    			$lastname = $_POST['lastName'];
    			$age = $_POST['age'];
    
    				if(!empty($_POST)){
    					$wpdb -> insert('tset', array(
    					'First_Name' => $name,
    					'Last_Name' => $lastname,
    					'Age' => $age),
    					array(
    					'%s',
    					'%s',
    					'%d'
    					));
    				$response = array('my_hidden_field'=> 'this is now filled in');
    				echo json_encode($response);
    				};
    				die();
    	}
    	add_action('wp_ajax_addUser', 'addUser');
    Thread Starter AnotherChance

    (@anotherchance)

    Right I have removed all the nice to haves and just left the bit to add data to the table. It appears that my action hooks aren’t working. According to the consol.log() the data is reaching the ajax request and according to the network it is posting the Data to admin-ajax.php and the status of this is 200 OK. The problem must then lie in the functions.php. In the add_action(‘wp_ajax_myAction’, ‘……’ ), what exactly is myAction referring to?

    Check the action parameter which i have passed in ajax call, that should be there in houra too, as you have called action hook “wp_ajax_addUser”, so in this case addUser is your action parameter in ajax call, check in my code both of them are same.

Viewing 15 replies - 1 through 15 (of 18 total)
  • The topic ‘jQuery, Ajax and PHP Request’ is closed to new replies.