Jump to content
Larry Ullman's Book Forums

Ajax Refuses To Submit Data For Processing To Php


Recommended Posts

(Using the example in Modern javascript)

Am trying to submit data for processing and insertion into the database using php but it could not work and I don't why and these are the steps taking so far. 1. Using php alone, am able to insert data into the database an d this is the php code.

 

 

<?php

try {
$linkas = 2;
require_once 'db/DBConnect.php';
$errors = [];
$good = true;
if ($_SERVER['REQUEST_METHOD'] == 'POST' && !empty($_POST['testimony'])):
$testimony = filter_input(INPUT_POST, 'testimony', FILTER_SANITIZE_STRING);

if (strlen($testimony) < 20):
//report error and do not go
$errors[] = 'It has to be more than 20 characters' . '<br>';
$good = false;
else:
$good = true;
if ($good):
$insertTestimony = 'INSERT INTO testimony(content, j_member_id, time_send) ';
$insertTestimony .= 'VALUES (:testimony, :user_id, NOW())';
$insert = $conn1->prepare($insertTestimony);
$insert->bindValue(':testimony', $testimony, PDO::PARAM_STR);
$insert->bindValue(':user_id', $linkas, PDO::PARAM_INT);
$insert->execute();
if ($insert->rowCount() == 1):
//success message
$_SESSION['msg'] = 'Thanks for the testimony';
header('Location: index.php');
exit();
else:
//fail message
echo 'Something is wrong, please resubmit';
endif;
endif;
endif;
endif;
} catch (Exception $e) {
echo 'Database error: ' . $e->getMessage() . ' in ' . $e->getFile() . ':' . $e->getLine();
}
?>

 

After testing the php and seeing that it works, I proceeded to create the html page which is below

 

<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<section class="">
<article>
<div id="testifyForm">
<form action="" method="post" id="testimony" accept-charset="utf-8">
<fieldset>
<legend>Your testimony</legend>
<label for="testimony"></label>
<textarea id="testimony" name="testimony" maxlength="300"></textarea>
</fieldset>
<input type="submit" name="testify" id="testify" value="Testify">
</form>
</div>
</article>
</section>
<script src="js/ajax.js"></script>
<script src="js/testify.js"></script>
</body>
</html>

 

Finally, I created the ajax.js script and testify.js script and placed them inside the js folder and link them to the html which you can see above.

 

This is the testify script

 

function validateForm() {
'use strict';
var testimony = document.getElementById('testimony');
if ((testimony.value.length > 20)) {
var ajax = getXMLHttpRequestObject();

ajax.onreadystatechange = function () {
if (ajax.readyState == 4) {
if ((ajax.status >= 200 && ajax.status < 300) || (ajax.status == 300)) {
//return ajax.responseText
document.getElementById('testifyForm').innerHTML = ajax.responseText;
} else {
document.getElementById('theForm').submit();
//return ajax.statusText
}//End of status
ajax = null;
}//End of readyState
};//End of onreadystatechange
//return true;
ajax.open('POST', 'empty.php', true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var data = 'testimony=' + encodeURIComponent(testimony.value);
ajax.send(data);
return false;
} else {
document.getElementById('error').innerHTML = 'Characters must be more than 20 words';
return false;
}//End of testimony
}

function init() {
'use strict';
if (document && document.getElementById) {
var testifyForm = document.getElementById('testifyForm');
testifyForm.onsubmit = validateForm;
}
}

window.onload = init;

 

And this is the ajax script

 

function getXMLHttpRequestObject() {
var ajax = null;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
} else if (window.ActiveXObject) { // Older IE.
ajax = new ActiveXObject('MSXML2.XMLHTTP.3.0');
}
return ajax;
}

 

The problem now is that ajax refuses to submit those data for processing and saving(which I believe PHP should handle). I also tried debugging it if there is any error by checking the console with ctrl+shift+j on chrome(that is the only step taken so far about debbuging)

P.s. This is pure JavaScript and ajax not jquery

Link to post
Share on other sites

Sorry, to be clear, in Google Chrome, view the Developer Tools. Then look at the "Network" pane. You should see requests there to your server-side PHP script. These are the JavaScript "Ajax"/XHR requests. If there aren't any, then the problem is with your JavaScript. If there are requests, you can click on one for more information. The "headers" pane shows what was sent to the PHP script and the "response" pane shows what the PHP script returned. 

Link to post
Share on other sites
  • 2 months later...

gbengasupowale807, I took a look at your code, and like Larry suggested, it helps a lot of you use your browser console.

In this case, it looks like the browser is reloading the page after the JS error occurs, thus making it hard to catch the error. However, if you check the Preserve log option in Chrome (or the similar option in the browser of your choice), you should then see the error upon form submission.

Long story short, you're trying to reference the value property of the testimony DOM element on line 4 of testimony.js. However, the problem is that testimony is a form DOM element, which doesn't have a value property, thus the issue. Resolve that, and hopefully, you can progress forward with your code.

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...