Uncaught SyntaxError: Unexpected token C in JSON at position 0 - javascript

This is my code for a form. I am asking user to input email and password and checking if user is registered or not. If he is registered then I alert success:
<form role="form" class="legacy-form" action="" method="POST" id="myform1">
<div class="col-xs-12 col-sm-6 col-md-6 col-sm-offset-3 col-md-offset-3">
<div class="form-group">
<input type="email" name="email" id="loginemail" class="form-control" placeholder="Email Address" required>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-6 col-sm-offset-3 col-md-offset-3">
<div class="form-group">
<input type="password" name="password" id="loginpassword" class="form-control" placeholder="Password" required>
</div>
</div>
<div class="row" style="padding:15px">
<div class="col-xs-6 col-sm-3 col-md-3 col-sm-offset-3 col-md-offset-3">
<div class="form-group">
<input type="submit" value="Log In" class="btn btn-primary" id="loginbtn">
</div>
</div>
<div class="col-xs-6 col-sm-3 col-md-3">
<div class="form-group">
<input type="submit" value="Cancel" class="btn btn-danger" data-dismiss="modal">
</div>
</div>
</div>
</form>
This is the php code wherein the connection is placed in another file 'init.php'
<?php
include('init.php');
if(isset($_POST))
{
$loginemail=$_POST["loginemail"];
$loginpassword=$_POST["loginpassword"];
$sql = "select count(*),fname from users where password='$loginpassword' and email='$loginemail'";
$result=mysqli_query($con,$sql);
if($result) {
$response =array();
while($row=mysqli_fetch_array($result))
{
array_push($response,array("Count"=>$row[0],"name"=>$row[1]));
}
echo json_encode(array("server_response"=>$response));
} else {
echo "error";
}
mysqli_close($con);
}
?>
this is my js file. On printing info in console I get Connection sucess{"server_response":[{"Count":"1","name":"sagar"}]}
$("#loginbtn").click(function(e) {
var loginemail = $("#loginemail").val();
var loginpassword = $("#loginpassword").val();
check_for_user(loginemail, loginpassword);
function check_for_user(loginemail, loginpassword) {
console.log("in check_for_user");
var i = 0;
console.log(i);
i++;
var c = "";
var x = "1";
var user = "";
var formdata = {
loginemail: loginemail,
loginpassword: loginpassword
}
$.ajax({
url: 'getData.php',
type: "POST",
data: formdata,
dataType: 'text',
success: handle_success,
error: handle_error
});
function handle_success(info) {
console.log(info);
var obj = jQuery.parseJSON(info);
console.log(obj);
$(obj.server_response).each(info, function(index, value) {
user = value.name;
c = value.Count;
});
console.log(c);
console.log(user);
if (x == c) {
alert("Welcome");
//document.location='online.html';
} else {
alert("Enter valid username and password");
}
}
function handle_error() {
alert("error");
}
}
});
The flow of the code is like when the #loginbtn is clicked it posts loginemail and loginpassword on php and then it checks in database whether there is an identical entry in database, if yes it alerts "welcome". I have searched a lot on StackOverflow I found that it says there is error in either parsing JSON or in decoding it.

It looks like you are echoing "Connection success" in init.php although we can't see that.
A json response should have no other content in response ... just the json.

Related

Send data-attribute ID in JS to PHP on same index page using ajax?

I am not sure how to word this title. Feel free to edit it.
Intro I am doing a datatables.net library server-side table using JSON and PHP. I am basically done except for the edit form.
My first problem was solved. I had a while loop instead of an if statement.
My second problem is now going to be transferring this Javascript code near before the AJAX call:
var edit_id = $('#example').DataTable().row(id).data();
var edit_id = edit_id[0];
to here which is php:
$edit_id = $_POST['edit_id'];
They are both on the same page, index.php so I do not think I can use ajax for this.
Index.php
<script type="text/javascript">
$(document).on('click', '.edit_btn', function() {
var id = $(this).attr("id").match(/\d+/)[0];
var edit_id = $('#example').DataTable().row(id).data();
var edit_id = edit_id[0];
$("#form2").show();
//console.log(edit_id[0]);
$.ajax({
type: 'POST',
url: 'edit.php',
data: {
edit_id: edit_id,
first_name: $("#edit2").val(),
last_name: $("#edit3").val(),
position: $("#edit4").val(),
updated: $("#edit5").val(),
},
success: function(data) {
alert(data);
if (data == 'EDIT_OK') {
alert("success");
} else {
// alert('something wrong');
}
}
})
});
</script>
<?php
$sql="select * from employees WHERE id=$edit_id";
$run_sql=mysqli_query($conn,$sql);
while($row=mysqli_fetch_array($run_sql)){
$per_id=$row[0];
$per_first=$row[1];
$per_last=$row[2];
$per_position=$row[3];
//$per_date=$row[4];
$per_updated=$row[5];
?>
<form id="form2" class="form-horizontal">
<label class="col-sm-4 control-label" for="txtid">ID</label>
<input id="edit1" type="text" class="form-control" name="txtid" value="<?php echo $per_id;?>" readonly>
<div class="form-group">
<label class="col-sm-4 control-label" id="edit2" for="txtname">First Name</label>
<div class="col-sm-6">
<input type="text" class="form-control" id="txtname" name="txtname" value="<?php echo $per_first;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtsalary">Last Name</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit3" name="txtsalary" value="<?php echo $per_last;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtage">Position</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit4" name="txtage" value="<?php echo $per_position;?>">
</div>
</div>
<div class="form-group">
<label class="col-sm-4 control-label" for="txtage">Updated</label>
<div class="col-sm-6">
<input type="number" class="form-control" id="edit5" name="txtage" value="<?php echo $per_updated;?>">
</div>
<button type="button" class="close" value="Cancel" data-dismiss="modal">×</button>
<button type="button" class="update" value="Update"></button>
</form>
edit.php
$edit_id = $_POST['edit_id'];
$stmt = $conn->prepare("UPDATE employees SET first_name=?, last_name=?, position=?, updated=? WHERE id=?");
$stmt->bind_param('ssssi', $_POST['first_name'], $_POST['last_name'], $_POST['position'], $_POST['updated'], $_POST['edit_id']);
$confirmUpdate = $stmt->execute();
if($confirmUpdate) {
echo "EDIT_OK";
}else {
trigger_error($conn->error, E_USER_ERROR);
return;
}
?>
I eventually figured it out:
<script type="text/javascript">
$(document).on('click','.edit_btn',function (){
var id = $(this).attr("id").match(/\d+/)[0];
var edit_id = $('#example').DataTable().row( id ).data();
var edit_id = edit_id[0];
alert(edit_id);
$.ajax({
url: 'index.php',
data: { edit_id : edit_id },
contentType: 'application/json; charset=utf-8',
success: function(result) {
//alert(result);
}
});
});
</script>

Contact form not working after migration from HTML (static) to WP

Thanks in advance for reading.
I converted my static HTML page to Wordpress, after the contact-form stopped working. I think it has something to do with the linking in the form.js and handler.php. See ** in handler.php and form.js. Help me out !!! :)
Live version: 050management.nl
Form HTML
<div class="row">
<div class="col-md-7">
<div class="input-group">
<input type="text" class="form-control" type="text" name="Name" id="name" placeholder="Uw naam..." required data-error="Voer uw naam in">
</div>
</div>
</div>
<div class="row">
<div class="col-md-7 pt-2">
<div class="input-group">
<input type="text" class="form-control" type="email" name="Email" id="email" placeholder="Uw e-mailadres..." required data-error="Voer uw e-mailadres in">
</div>
</div>
</div>
<div class="row">
<div class="col-md-12 pt-2">
<div class="input-group">
<textarea name="Message" id="message" class="form-control" cols="30" rows="5" placeholder="Uw bericht..." data-error="Stel uw vraag"></textarea>
</div>
</div>
</div>
<div class="input-group pt-2">
<div class="g-recaptcha" data-sitekey="6LddA2oUAAAAAHmFtwEkS68c4_UUi3hGpd7AZyOo"></div>
</div>
<div class="row">
<div class="col-md-9 pt-2">
<div class="input-group">
<input type="submit" class="contact-submit" value="Verzenden">
</div>
</div>
</div>
</form>
<div id="success_message" style="display:none">
<h4>Dank voor uw bericht.</h4>
<p>
We zullen spoedig contact met u opnemen.
</p>
</div>
<div id="error_message"
style="width:100%; height:100%; display:none; ">
<h4>Er ging iets mis...</h4>
<p>Mail ons of bel ons rechtsreeks. Dank u wel.
</div>
</div>
.........
<script src="<?php echo get_template_directory_uri().'/js/form.js' ?>"></script>
form.js (url: /js/form.js)
$(function()
{
function after_form_submitted(data)
{
if(data.result == 'success')
{
$('form#reused_form').hide();
$('#success_message').show();
$('#error_message').hide();
}
else
{
$('#error_message').append('<ul></ul>');
jQuery.each(data.errors,function(key,val)
{
$('#error_message ul').append('<li>'+key+':'+val+'</li>');
});
$('#success_message').hide();
$('#error_message').show();
//reverse the response on the button
$('button[type="button"]', $form).each(function()
{
$btn = $(this);
label = $btn.prop('orig_label');
if(label)
{
$btn.prop('type','submit' );
$btn.text(label);
$btn.prop('orig_label','');
}
});
}//else
}
$('#reused_form').submit(function(e)
{
e.preventDefault();
$form = $(this);
//show some response on the button
$('button[type="submit"]', $form).each(function()
{
$btn = $(this);
$btn.prop('type','button' );
$btn.prop('orig_label',$btn.text());
$btn.text('Sending ...');
});
$.ajax({
type: "POST",
**url: 'handler.php',**
data: $form.serialize(),
success: after_form_submitted,
dataType: 'json'
});
});
});
handler.php (url: handler.php) same folder as index.php
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
**require_once '/vendor/autoload.php';**
use FormGuide\Handlx\FormHandler;
$pp = new FormHandler();
$validator = $pp->getValidator();
$validator->fields(['Name','Email'])->areRequired()->maxLength(50);
$validator->field('Email')->isEmail();
$validator->field('Message')->maxLength(6000);
$pp->requireReCaptcha();
$pp->getReCaptcha()->initSecretKey('REMAINS SECRET :)');
$pp->sendEmailTo('info#050management.nl');
echo $pp->process($_POST);
In WordPress things are done a little differently.
You can post data from client to server through ajax with setting a right action.
specify a global variable ajaxurl inside head tag or anywhere before your form handling:
<script>
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
</script>
When you submit the data you can do it like this:
$.post( ajaxurl, {
action: 'handle_form',
form_data: $form.serialize()
}, function(data) {
// logic after receiving a response
}, 'json'
);
On the server side in functions.php:
function handle_form_ajax_handler() {
$form_data = $_POST['form_data'];
// logic with $form_data
wp_die();
}
add_action('wp_ajax_handle_form', 'handle_form_ajax_handler'); // add action for logged users
add_action( 'wp_ajax_nopriv_handle_form', 'handle_form_ajax_handler' ); // add action for unlogged users

Bootstrap dismissable success message not showing longer with ajax

I have an ajax form which gets data with PHP post method. Instead of using the alert function of Javascript, I called bootstrap success message. But problem it doesn't show longer last only for less than a second. How to show its length until the user manually closed it as it's dismissable.
Coding Part:
function send_form() {
$.ajax({
url: "./admin-security.php",
type: "POST",
data: {
ip: $("#ip").val()
},
success: function(response) {
if(response==1) {
$("#ajax-ip-success").show();
location.href = "./admin-security.php";
}
else alert("Fail! DataBase Error");
}
});
}
<?php
//--AJAX PART CALLING
if(isset($_POST['ip'])){
if($IP = filter_input(INPUT_POST, 'ip',
FILTER_SANITIZE_STRING)){
$add_ip = $mysqli->prepare("INSERT INTO block_ip(b_ip)
VALUES(?)");
$add_ip->bind_param("s",$IP);
$add_ip->execute();
$add_ip->store_result();
$add_ip->close();
echo 1;
}
else {
echo 0;
}
exit;
}
?>
<div class="alert alert-success alert-dismissable fade in" style="display: none;" id="ajax-ip-success">
×
<strong>Success!</strong> IP added successfully.
</div>
<div class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-2" for="ip"> Enter IP:</label>
<div class="col-sm-8">
<input type="text" name="ip" class="form-control" id="ip" />
</div></div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-8">
<button type="button" onClick="send_form()" class="btn btn-default"
>Submit</button>
</div></div>
</div>
You can set Timeout for location redirect
setTimeout(function(){
location.href = "./admin-security.php";
},2000);

Form submit in continuous loop?

This is my view: product_information.php
<form id="form-product-info" data-parsley-validate class="form-horizontal form-label-left">
<div class="form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="product-SKU">SKU <span class="required">*</span>
</label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input type="text" id="product-SKU" required="required" class="form-control col-md-7 col-xs-12" value="<?php echo $results[0]->SKU; ?>">
</div>
</div>
<div class="ln_solid"></div>
<div class="form-group">
<div class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
<button class="btn btn-primary" type="button" id="btn-customer-list">Cancel</button>
<button class="btn btn-danger" type="button" id="btn-delete-product">Delete</button>
<button type="submit" class="btn btn-success source">Submit</button>
</div>
</div>
</form>
This is my controller: product.php
public function updateProductInformation()
{
$product_information['name'] = $this->input->post('name');
$product_information['SKU'] = $this->input->post('SKU');
$product_information['product_id'] = $this->input->post('id');
$product_information['last_updated'] = date('Y-m-d H:i:s');
var_dump($product_information);
$update = $this->updateProductInformation($product_information);
$this->update($update);
}
The JavaScript file: product.js
$('#form-product-info').submit(function() {
alert('Submitting form');
var id = $('#product-name').data('product-id');
updateProductInformation(id);
});
function updateProductInformation(id)
{
alert('Updating product information ' + id);
var name = $('#product-name').val();
var SKU = $('#product-SKU').val();
alert(name);
alert(SKU);
alert(id);
$.ajax({
type: 'post',
url: base_url + 'product/updateProductInformation',
data: {
'name' : name,
'SKU' : SKU,
'id' : id
},
success: function(msg)
{
if (msg == 'true')
{
alert('Updating product information successful');
}
else
{
alert("Please try again. ");
}
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log('Response text: ' + jqXHR.responseText);
console.log('Status code: ' + textStatus);
console.log('Error thrown: ' + errorThrown);
}
});
}
When I hit submit, an error is thrown in the console. When I open it in a new tab, I get a continuous stream of this:
array(4) { ["name"]=> NULL ["SKU"]=> NULL ["product_id"]=> NULL ["last_updated"]=> string(19) "2017-09-23 10:07:20" }
Until eventually it runs out of memory and I get a fatal error. I can't seem to find what could be causing this. The alerts I set show only once as they should. The updateProductInformation(id) is assigned to only one event handler as far as I have checked. And even if it was being called from other places, then the alerts should be showing more than once.
Found the culprit:
$update = $this->updateProductInformation($product_information);
This should be:
$update = $this->Product_model->updateProductInformation($product_information);
Can be quite easy to miss!

Custom AJAX form not working async

I have a contact from that uses PHP mailer that I have integrated into my Wordpress blog. The script sends emails no problem - the issue is that it does not work async so once the form is submitted I am taken to another page with the following text on it: {"message":"Your message was successfully submitted from PHP."}. The script works as expected when used outside of wordpress - I have no idea whats going on.
PHP
<?php
/**
* Sets error header and json error message response.
*
* #param String $messsage error message of response
* #return void
*/
function errorResponse ($messsage) {
header('HTTP/1.1 500 Internal Server Error');
die(json_encode(array('message' => $messsage)));
}
/**
* Pulls posted values for all fields in $fields_req array.
* If a required field does not have a value, an error response is given.
*/
function constructMessageBody () {
$fields_req = array("name" => true, "description" => true, "email" => true, "number" => true);
$message_body = "";
foreach ($fields_req as $name => $required) {
$postedValue = $_POST[$name];
if ($required && empty($postedValue)) {
errorResponse("$name is empty.");
} else {
$message_body .= ucfirst($name) . ": " . $postedValue . "\n";
}
}
return $message_body;
}
//header('Content-type: application/json');
//attempt to send email
$messageBody = constructMessageBody();
require 'php_mailer/PHPMailerAutoload.php';
$mail = new PHPMailer;
$mail->CharSet = 'UTF-8';
$mail->setFrom($_POST['email'], $_POST['name']);
$mail->addAddress("example#example.com");
$mail->Subject = $_POST['name'];
$mail->Body = $messageBody;
//try to send the message
if($mail->send()) {
echo json_encode(array('message' => 'Your message was successfully submitted from PHP.'));
} else {
errorResponse('An expected error occured while attempting to send the email: ' . $mail->ErrorInfo);
}
?>
(function($) {
$('#form').on('submit', function(){
event.preventDefault();
var contactFormUtils = {
clearForm: function () {
grecaptcha.reset();
},
addAjaxMessage: function(msg, isError) {
$("#feedbackSubmit").append('<div id="emailAlert" class="alert alert-' + (isError ? 'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() + '</div>');
}
};
$('#submit-email').prop('disabled', true).html("sending");
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(data) {
console.log('success');
$('#form').fadeOut(400)
contactFormUtils.addAjaxMessage(data.message, false);
contactFormUtils.clearForm();
},
error: function(response) {
console.log('error');
contactFormUtils.addAjaxMessage(response.responseJSON.message, true);
$('#submit-report').prop('disabled', false).html("Send message");
contactFormUtils.clearForm();
},
complete: function() {
console.log('complete');
}
});
return false;
});
})( jQuery );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-8 site-block">
<form id="form" method="post" class="form-horizontal ajax" action="<?php echo get_template_directory_uri(); ?>/assets/php/process-contact.php" data-toggle="validator">
<div class="form-group">
<label for="inputName" class="col-sm-2 control-label">Name</label>
<div class="col-sm-10">
<input name="name" type="text" class="form-control" id="inputName" placeholder="Enter your full name and title here" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Phone</label>
<div class="col-sm-10">
<input name="number" type="number" class="form-control" id="inputEmail3" placeholder="Enter your preferred telephone number here" required>
</div>
</div>
<div class="form-group">
<label for="inputEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-10">
<input name="email" type="email" class="form-control" id="inputEmail" placeholder="Enter your preferred email address here" required>
</div>
</div>
<div class="form-group">
<label for="inputMessage" class="col-sm-2 control-label">Message</label>
<div class="col-sm-10">
<textarea name="description" class="form-control" id="inputMessage" placeholder="Type your message here" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button id="submit-email" name="submit" type="submit" class="btn btn-danger">Submit</button>
</div>
</div>
</form>
<div id="feedbackSubmit"></div>
</div>
change
jQuery('#form').on('submit', function(){
to
jQuery('.ajax').on('submit', function(event){
and replace ALL $ with jQuery
and
wrap your code in document ready function
jQuery(function(){});

Categories