Little problem with ajax. Error-function is executed - javascript

i have a little problem with ajax and mysql.
I want to save same data to a database via ajax.
Javascript:
$.ajax({
type : "POST",
url : url_save,
async : false,
data : { item : nr, var : text },
success: function(result_save){
if (result_save.includes('Error')) {
alert("!!! Error !!!");
}
},
error: function(xhr, textStatus, errorThrown) {
alert("!!! Error !!!");
}
});
My PHP-File looks like:
PHP:
<?php
require "config.inc.php";
$db = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME) or die ('Error');
$db->set_charset("utf8");
$sql="INSERT INTO tbl (item, var) VALUES ('$_POST[item]','$_POST[var]')";
if (!mysqli_query($db,$sql))
{
return 'Error';
die();
}
mysql_close($db);
return 'i.O.';
?>
It saves to the database, but the error-function of ajax is executed every time. What is wrong?

A few observations:
jcubic is correct- you don't want to use a JS keyword as a parameter name.
catcon is also correct. Using a prepared statement is FAR preferable to reading the variable directly into your SQL text.
Even if mysqli_query() returns 0, you still want to do a mysql_close($db), don't you?
You would also like to know the specific error, wouldn't you?
SUGGESTION:
PHP:
<?php
require "config.inc.php";
$conn = new mysqli(DBHOST, DBUSER, DBPASS, DBNAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $conn->prepare("INSERT INTO tbl (item, var) VALUES (?, ?)");
$stmt->bind_param("is", $_POST[item_id], $_POST[item_value]);
if (!$stmt->execute()) {
$result = "Execute failed: (" . $stmt->errno . "): " . $stmt->error;
}
$stmt->close();
$conn->close();
return ($result) ? 'Success' : $result;
...
JS:
$.ajax({
type : "POST",
url : url_save,
async : false,
data : { item_id: nr, item_value: text },
success: function(result_save){
if (result_save === 'Success') {
console.log('Insert was successful', nr, value);
} else {
alert('mySql Error: ', JSON.stringify(result_save));
}
},
error: function(xhr, textStatus, errorThrown) {
alert('XHR Exception: ' + textStatus + ', ' + JSON.stringify(errorThrown));
}
});

Related

How to use ajax for request the WHMCS hooks function and get my required return data?

I read the WHMCS demo code for developing a provisioning module:
the frontend code, overview.tpl.
the backend code, provisioningmodule.php.
but my code follow by the upper I want to use ajax for request, so the whole page will not re-render.
My frontend ajax code:
jQuery.ajax({
url: url,
type: "POST",
data: {
...
qn_action: "bmc"
},
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data, textStatus){
console.log('ldl:',data) // pay attention I want to console.log the return data. I wish it be the PHP return data's `templateVariables`.
jQuery('.powercontrol').removeClass('disabled');
jQuery(i_id).css('display', 'none');
jQuery('#powerstatus-spinner').css('display', 'none'); // Status loading
},
error: function(jqXHR, e) {
var msg = '';
if(jqXHR.status==0){
msg = 'You are offline!!\n Please Check Your Network.';
}else if(jqXHR.status==404){
msg = 'Requested URL not found.';
}else if(jqXHR.status==500){
msg = 'Internal Server Error.<br/>'+jqXHR.responseText;
}else if(e=='parsererror'){
msg = 'Error: Parsing JSON Request failed.';
}else if(e=='timeout'){
msg = 'Request Time out.';
}else {
msg = 'Unknow Error.<br/>'+x.responseText;
}
console.log('error: '+jqXHR.responseText); // I wil get the error logs
console.log('Error msg: '+msg);
}
})
in my backend PHP code:
function qidicatedserver_ClientArea(array $params)
{
// Determine the requested action and set service call parameters based on
// the action.
$qn_action = isset($_REQUEST['qn_action']) ? $_REQUEST['qn_action'] : '';
$tblclients_id = isset($_REQUEST['tblclients_id']) ? $_REQUEST['tblclients_id'] : '';
$bmc_action = "";
$server_name = "";
$templateFile = 'templates/overview.tpl';
$bmc_result = "";
if($qn_action == "bmc"){
$resp = array(
'tabOverviewReplacementTemplate' => $templateFile,
'templateVariables' => array(
"status"=>200,
"data"=>"my test return data"
)
);
return $resp;
}
try {
// Call the service's function based on the request action, using the
// values provided by WHMCS in `$params`.
return array(
'tabOverviewReplacementTemplate' => $templateFile,
'templateVariables' => array(
'data' => array(
"status"=>"200",
"data" => array(
"bmc_result" => null
)
),
),
);
} catch (Exception $e) {
//echo $e;
// Record the error in WHMCS's module log.
logModuleCall(
'qidedicatedserver',
__FUNCTION__,
$params,
$e->getMessage(),
$e->getTraceAsString()
);
// In an error condition, display an error page.
return array(
'tabOverviewReplacementTemplate' => 'templates/error.tpl',
'templateVariables' => array(
'usefulErrorHelper' => $e->getMessage(),
),
);
}
}
when the ajax request executed, there will get error, execute the below code:
console.log('error: '+jqXHR.responseText); // I wil get the console log: `error: <!DOCTYPE html> \n<html lang="en">\n<head>\n <meta char) ....` the html is the whole page's HTML
console.log('Error msg: '+msg); // the console log: `Error msg: Error: Parsing JSON Request failed.`
So, there must be issue in there, my problem is how to use ajax for HTTP request in WHMCS custom provisioning module, but I try get failed like upper. (I tried use form request PHP, there can get correct data, but there will re-fresh the whole page, its not my desired, I don't what the page to be refresh)
Who can tell me how to use ajax for request WHMCS hook function and return correct data as my wish?
You can find more introduction of WHMCS provisioningmodulethere.
EDIT-01
I tried change the return PHP code like this:
if($qn_action == "bmc"){
$resp = array(
'tabOverviewReplacementTemplate' => $templateFile,
'templateVariables' => json_encode(array(
"status"=>200,
"data"=>"dasdas"
))
);
return $resp;
}
but still this error.
Put your Ajax/PHP code in separated file, not in _ClientArea method, suppose your module called 'mail_service', then create a file in:
\modules\servers\mail_service\for_json.php
for_json.php
<?php
#define("ADMINAREA", true);
define("CLIENTAREA", true);
#define("SHOPPING_CART", true);
require_once(__DIR__ . '/../../../init.php');
require_once(ROOTDIR . '/includes/dbfunctions.php');
#require(ROOTDIR . "/includes/orderfunctions.php");
#require(ROOTDIR . "/includes/domainfunctions.php");
#require(ROOTDIR . "/includes/configoptionsfunctions.php");
#require(ROOTDIR . "/includes/customfieldfunctions.php");
#require(ROOTDIR . "/includes/clientfunctions.php");
#require(ROOTDIR . "/includes/invoicefunctions.php");
#require(ROOTDIR . "/includes/processinvoices.php");
#require(ROOTDIR . "/includes/gatewayfunctions.php");
#require(ROOTDIR . "/includes/modulefunctions.php");
#require(ROOTDIR . "/includes/ccfunctions.php");
#require(ROOTDIR . "/includes/cartfunctions.php");
#include_once(ROOTDIR . '/includes/clientareafunctions.php');
#use WHMCS\ClientArea;
#use WHMCS\Database\Capsule;
#use WHMCS\Smarty ;
file_put_contents("C:/xampp_my/htdocs/my/sss.txt",var_export($_POST,true));
if(isset($_POST['qn_action']) && $_POST['qn_action']=="bmc")
{
// do your job
//header('Content-type: application/json; charset=utf-8');
header("Content-Type: application/json", true);
header('HTTP/1.0 200 OK');
echo '{"menu": {"id": "file","value": "File","popup": {"menuitem": [{"value": "New", "onclick": "CreateNewDoc()"},{"value": "Open", "onclick": "OpenDoc()"}, {"value": "Close", "onclick": "CloseDoc()"}]}}}';
}
?>
and use the follwing JS code:
jQuery.ajax({
url: "/modules/servers/mail_service/for_json.php",
type: 'POST',
data: {qn_action: 'bmc'},
cache: false,
dataType: 'json',
success: function (data, textStatus){console.log('ldl:',data)},
error: function(jqXHR, e){
var msg = '';
if(jqXHR.status==0){
msg = 'You are offline!!\n Please Check Your Network.';
}else if(jqXHR.status==404){
msg = 'Requested URL not found.';
}else if(jqXHR.status==500){
msg = 'Internal Server Error.<br/>'+jqXHR.responseText;
}else if(e=='parsererror'){
msg = 'Error: Parsing JSON Request failed.';
}else if(e=='timeout'){
msg = 'Request Time out.';
}else {
msg = 'Unknow Error.<br/>'+x.responseText;
}
console.log('error: '+jqXHR.responseText); // I wil get the error logs
console.log('Error msg: '+msg);
}
})

jQuery serialized data not successfully posting to PHP form handler

I’m trying to post some data via jQuery Ajax to a PHP form handler file. It was working earlier, but I wasn’t getting errors when I should have (ie it was always sending an email), so I modified the mess out of my stuff and now the PHP file is no longer receiving the serialized data. Would greatly appreciate some eyes on this. I have a feeling it’s a stupid syntax error, but I’m not seeing it.
JS (jQuery)
$form.submit(function(e) {
e.preventDefault();
var data = $(this).serialize(),
url = $(this).attr('action');
console.log(data);
$(this).addClass('sending');
$.ajax({
url: url,
type: 'GET',
async: true,
dataType: 'json',
data: data,
success:
function(response) {
console.log("Success: " + data);
if(!response.success) {
formError(response);
} else {
// on success
console.log(`✔ Form submission successful!`);
console.log(response);
// Add success message
$form.append(
'<div class="success-message"><h3>Your Message Was Sent</h3><p>'
+
successMsg
+
'</p></div>'
).delay(10)
.queue(function(){
$(this).find('.success-message').addClass('visible');
$(this).dequeue();
});
$form
.delay(10)
.queue(function() {
$(this)
.removeClass('sending')
.addClass('sent')
.dequeue();
});
$form[0].reset();
}
},
error:
function(xhr, status, error){
console.log("Fail: " + data);
formError(xhr, status, error);
}
});
function formError(xhr, status, error) {
//on failure
console.log('✘ Form submission failed.');
console.log(xhr);
console.log(status);
console.log(error);
if (!$form.hasClass('error')) {
$form
.addClass('error')
.delay(2000)
.queue(function() {
$(this)
.removeClass('error')
.removeClass('sending')
.dequeue();
});
}
};
});
PHP Handler
<?php
$errors = '';
$myemail = '#####';//<-----Put Your email address here.
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$company = $_POST['company'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$data = array($name, $email, $phone, $company, $subject, $message);
if(
empty($name) ||
empty($email) ||
empty($phone) ||
empty($company) ||
empty($message)
) {
$errors .= "\n You must fill out required fields.";
}
if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email))
{
$errors .= "\n Invalid email address.";
}
if( empty($errors) ) {
$to = $myemail;
$email_subject = "Contact Form: $name";
$email_body = "<html><body>".
"<p>Name: $name<br>".
"<p>Company: $company<br>".
"Email: $email<br>".
"Phone: $phone<br></p>".
"<p><b>Subject:</b></p>".
"<p>$subject</b></p>".
"<p><b>Message:</b></p>".
"<p>$message</p>".
"</body></html>";
$headers = "From: $myemail\r\n";
$headers .= "Reply-To: $email\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to,$email_subject,$email_body,$headers);
echo json_encode(array("success" => true, "data" => $data));
} else {
echo json_encode(array("success" => false,"error" => $errors, "data" => $data));
}
?>
The PHP handler is returning data so that I can see what's going on, and then I'm console logging it. Here's what I'm getting:
{success: false, error: "↵ You must fill out required fields.↵ Invalid email address.", data: Array(6)}
data: (6) [null, null, null, null, null, null]
error: "↵ You must fill out required fields.↵ Invalid email address."
success: false
__proto__: Object
In other words, the data isn't actually passing to the PHP file. I'm assuming I have some stupid syntax error, but I'm not seeing it. Help! 🙏🏼
You send GET data in Ajax and you try to get POST in your PHP.
Change type to POST in your Ajax function.
$form.submit(function(e) {
e.preventDefault();
var data = $(this).serialize(),
url = $(this).attr('action');
console.log(data);
$(this).addClass('sending');
$.ajax({
url: url,
type: 'POST',
async: true,
dataType: 'json',
data: data,
success:
function(response) {
console.log("Success: " + data);
if(!response.success) {
formError(response);
} else {
// on success
console.log(`✔ Form submission successful!`);
console.log(response);
// Add success message
$form.append(
'<div class="success-message"><h3>Your Message Was Sent</h3><p>'
+
successMsg
+
'</p></div>'
).delay(10)
.queue(function(){
$(this).find('.success-message').addClass('visible');
$(this).dequeue();
});
$form
.delay(10)
.queue(function() {
$(this)
.removeClass('sending')
.addClass('sent')
.dequeue();
});
$form[0].reset();
}
},
error:
function(xhr, status, error){
console.log("Fail: " + data);
formError(xhr, status, error);
}
});
function formError(xhr, status, error) {
//on failure
console.log('✘ Form submission failed.');
console.log(xhr);
console.log(status);
console.log(error);
if (!$form.hasClass('error')) {
$form
.addClass('error')
.delay(2000)
.queue(function() {
$(this)
.removeClass('error')
.removeClass('sending')
.dequeue();
});
}
};
});

If and else condition inside success in ajax

As the title says I want to run the if and else inside the success condition in Ajax, For example after running the Ajax and sees that there is a record it will go to success then inside the success it must look for the "if statement" and display the alert inside the "if statement" if the statement is true but instead it always display the "else statement" with the alert('no') inside of it, even if there is a record, Thank you
<script>
function renderAttendees(id)
{
///$("#attendeesContent").empty();
var dataString = { "id": id };
$.ajax({
type: 'POST',
url: server+'webservice/crm/viewAttendeesDetails',
data: dataString,
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
cache: true,
success: function(data)
{
if($.trim(data) === 'error')
{
alert('yes');
}
else
{
alert('no');
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Error connecting to server. " + XMLHttpRequest + ", " + textStatus +", "+ errorThrown);
}
</script>
//My Controller Code
public function viewAttendeesDetails()
{
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
$data = array();
$id = $_POST['id'];
$AttendeesDetails = $this->model->GetAttendeesDetail($id);
if($row = $AttendeesDetails->fetch(PDO::FETCH_ASSOC))
{
$this->tp->DBToHTMLAll($row, $data);
}
echo json_encode($data);
exit;
}
?>
//My Model Code
db->prepare("SELECT * FROM crm_contact_list WHERE id = :AttendId");
$stmt->bindParam(":AttendId", $id);
$stmt->execute();
return $stmt;
}
catch (Exception $e)
{
return $e->getMessage();
return $stmt;
}
return;
}
?>
//Here is the result of console.log(data);
Object
email:"kyle#localhost.com"
full_name:"Test kim"
id:"1"
interest:"Test"
number:"123456"
position:"Prog"
venueID:"1"
I would return from your controller something like
{status: 'success', data: myArrayWithFoundData}
so when you receive the ajax response you could do a json_decode, and check the status.
So in you controller you would have
if($row = $AttendeesDetails->fetch(PDO::FETCH_ASSOC))
{
$this->tp->DBToHTMLAll($row, $data);
$rsp_data = {status: 'success', data: $data};
}else{
$rsp_data = {status: 'error', data: null};
}
echo json_encode($resp_data);
Something like that, so in the ajax response you would do a
var a = JSON.parse(data);
and check the a.status for error

Ajax form submitting successfully but alert error showing up

I created an AJAX form that submits to a php page. This form is submitting successfully in terms of, I am getting the email address in my database and I have a confirmation email that sends out.
However, I am getting an alert message saying "Error|", so obviously it is coming from this:
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + "|" + errorThrown);
I am unsure of why an error is throwing if it works. Another thing, this form is reloading the page. I have event.preventDefault(); in place, so why would the page be reloading?
I appreciate any help.
<form action="" method="POST">
<input type="email" id="footer-grid1-newsletter-input" placeholder="Your Email Address">
<input type="submit" id="footer-grid1-newsletter-submit" name="submit">
</form>
$(document).ready(function(){
$("#footer-grid1-newsletter-submit").on("click", function () {
event.preventDefault();
var newsletter_email = $("#footer-grid1-newsletter-input").val();
$.ajax({
url: "newsletterSend.php",
type: "POST",
data: {
"newsletter_email": newsletter_email
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to insert email!");
alert(data);
} else {
/*$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html('Announcement Successfully Added!');
$('.announcement_success').delay(5000).fadeOut(400);*/
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + "|" + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
});
ini_set('display_errors', 1);
error_reporting(E_ALL);
$newsletter_email = $_POST['newsletter_email'];
try {
$con = mysqli_connect("localhost", "", "", "");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$stmt = $con->prepare("INSERT INTO newsletter (email, subscribed) VALUES (?, NOW())");
if ( false===$stmt ) {
die('Newsletter email prepare() failed: ' . htmlspecialchars($con->error));
}
$stmt->bind_param('s', $newsletter_email);
if ( false===$stmt ) {
die('Newsletter email bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$stmt->execute();
if ( false===$stmt ) {
die('Newsletter email execute() failed: ' . htmlspecialchars($stmt->error));
}
} catch(Exception $e) {
die($e->getMessage());
}
Your event doesn't have any reference
.on("click", function () {
should be
.on("click", function (event) {
Then clearing your form. you can do
$("YOUR_FORM")[0].reset()

AJAX form not submitting that gives error

I have my AJAX code here
$("#add-student").click(function(e) {
e.preventDefault();
formData = $("#student-form").serialize();
if (cleanFormInput()) {
sendTheInfo(formData);
} else {
shakeForm();
}
});
function sendTheInfo(formData) {
$.ajax({
type: "POST",
url: "../classes/ajax/postNewStudent.php",
data: formData,
statusCode: {
404: function() {
alert( "page not found" );
}
},
success: function(formData) {
console.log("New student submitted:\n" + formData);
//clearForms();
},
error: function(result, sts, err) {
console.warn("Connection error:\n" + err + " : " + sts);
console.log(result);
shakeForm();
},
complete: function() {
console.log("Everything complete");
}
});
}
Always without fail outputs this error:
Connection error:
SyntaxError: Unexpected end of input : parsererror
But still gives the complete message: Everything complete
Update, PHP code here:
require '../../core/init.php';
require '../../classes/Config.php';
header('Content-Type: application/json');
if (!empty($_POST)) {
$id = $_POST["sid"];
$first = $_POST["first"];
$last = $_POST["last"];
$fav = "0";
$sql = "INSERT INTO `students` (`id`, `first`, `last`, `active`) VALUES ('{$id}', '{$first}', '{$last}', '{$fav}')";
$link = mysql_connect(Config::get('mysql/host'),Config::get('mysql/username'),Config::get('mysql/password')) or die("could not connect");;
mysql_select_db(Config::get('mysql/db'), $link);
$result = mysql_query($sql, $link);
if ($result) {
header('Content-Type: application/json');
$student_data = $id . $first . $last . $fav;
echo json_encode($student_data);
}
}
I'm a bit confused, am I doing my ajax set up wrong? Or is it something else in by backend code wrong? I'm using MySQL and jQuery 2.0.3
Updated code here: here
I have had a look at your code. I saw that from the PHP side you are sending a JSON object. but you didn't specified the return dataType for the response. Try to add the dataType in the ajax call. Maybe that will solve the problem
function sendTheInfo(formData) {
$.ajax({
type: "POST",
url: "../classes/ajax/postNewStudent.php",
data: formData,
dataType : 'json',
statusCode: {
404: function() {
alert( "page not found" );
}
},
success: function(formData) {
console.log("New student submitted:\n" + formData);
//clearForms();
},
error: function(result, sts, err) {
console.warn("Connection error:\n" + err + " : " + sts);
console.log(result);
shakeForm();
},
complete: function() {
console.log("Everything complete");
}
});
}
It should be noted that the Ajax COMPLETE method will fire even if the back end does not return a result.
complete: function() {
console.log("Everything complete");
}
will thus show the log'ed entry every time an ajax call is 'finished executing', even if the submit failed.
I would also suggest NOT having 2 headers or the same declaration (you have one up top, and one in the if(result) call.
In a comment thread, you pointed out that you're working on the server but not locally, And thus that implies you have some pathing issues. Check your
../
relative path style urls and make sure that you have the same basepoints.
removed my old answer. I don't think it is an ajax/javascript error. it's definitely a PHP error. It's this lines:
$student_data = $id . $first . $last . $fav;
echo json_encode($student_data);
You $student_data is not an array, it's just a string. You need to pass an array into the json_encode function

Categories

Resources