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!
Related
check_availability.php
this is my php to check the form if it is already exist.
<?php
require_once("config.php");
//code check email
if (!empty($_POST["CUSUNAME"])) {
$result = mysqli_query($con, "SELECT count(*) FROM tblcustomer WHERE CUSUNAME='" . $_POST["CUSUNAME"] . "'");
$row = mysqli_fetch_row($result);
$email_count = $row[0];
if ($email_count > 0) echo "<span style='color:red'>Username is already used.</span>";
else echo "<span style='color:green'>Username is available.</span>";
}
// End code check email
//Code check user name
if (!empty($_POST["PHONE"])) {
$result1 = mysqli_query($con, "SELECT count(*) FROM tblcustomer WHERE PHONE='" . $_POST["PHONE"] . "'");
$row1 = mysqli_fetch_row($result1);
$user_count = $row1[0];
if ($user_count > 0) echo "<span style='color:red'>Phone is already used.</span>";
else echo "<span style='color:green'>Phone number is available.</span>";
}
// End code check username
?>
LogSignModal.php
here is my page.
<div class="form-group">
<div class="col-md-10">
<label class="col-md-4 control-label" for=
"CUSUNAME">Username:</label>
<div class="col-md-8">
<input class="form-control input-sm" onBlur="checkUserNameAvailability()" id="CUSUNAME" name="CUSUNAME" placeholder=
"Username" type="text" value="">
<span id="username-availability-status"></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<label class="col-md-4 control-label" for=
"PHONE">Contact Number:</label>
<div class="col-md-8">
<input class="form-control input-sm" onBlur="checkPhoneAvailability()" id="PHONE" name="PHONE" placeholder=
"Phone Number" type="number" value="">
<span id="Phone-availability-status"></span>
</div>
</div>
</div>
<div class="form-group">
<div class="col-md-10">
<label class="col-md-4" align = "right"for=
"image"></label>
<div class="col-md-8">
<input type="submit" name="submit" value="Sign Up" class="submit btn btn-pup" />
<button class="btn btn-default" data-dismiss="modal" type=
"button">Close</button>
</div>
</div>
</div>
<script>
function checkUserNameAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:'CUSUNAME='+$("#CUSUNAME").val(),
type: "POST",
success:function(data){
$("#username-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
function checkPhoneAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:'PHONE='+$("#PHONE").val(),
type: "POST",
success:function(data){
$("#Phone-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
</script>
my code is all worked, but I can't make a submit button to appear when the value I input in textbox is available in database and disappear if it is already use.
I hope someone help me, thank you.
Edit: First, you should definitely also check the comment of Dharman and rewrite how you fetch data from MySQL in your PHP code since the current state is vulnerable to SQL Injections and is absolutely not safe to use!
The problem is how you pass your data to your ajax function. The way you do it, the server receives nothing but a plain string, for example 'CUSUNAME=dave'. This way $_POST["CUSUNAME"] will find nothing and your server response will stay empty. So you should pass your data as an object the following way :
<script>
function checkUserNameAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:{'CUSUNAME': $("#CUSUNAME").val()},
type: "POST",
success:function(data){
$("#username-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
function checkPhoneAvailability() {
$("#loaderIcon").show();
jQuery.ajax({
url: "check_availability.php",
data:{'PHONE': $("#PHONE").val()},
type: "POST",
success:function(data){
$("#Phone-availability-status").html(data);
$("#loaderIcon").hide();
},
error:function (){}
});
}
</script>
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);
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.
I am trying to update an image in the my database. I have a modal that is loaded with jquery. When clicking on the save modification button, alla the form data shows up except for the image file, which does not show up in the $_FILES in php. I tried all the indication found on the web (php ini file enables file upload, images size is good). The code works if I use that classic submit method, but I don't want a full screen refresh, I need to do it all in ajax. Here is the html:
$('#updatePubDevFrm').submit(function (e) {
e.preventDefault();
var data = $(this).serialize();
alert(data);
var url = '/PubDev/updatePubDev';
$.post(url, data, null, 'json')
.done(function (data) {
if (data.status === "OK") {
$('#updatePubDevModal').removeClass('md-show');
} else {
alert("update error");
}
})
.fail(function (data) {
alert("ajax error");
})
.always(function () {
});
});
<div class="md-modal md-effect-1" id="updatePubDevModal" >
<div class="md-content">
<div class="modal-header">
<button class="md-close close">×</button>
<h4 class="modal-title">Update Publisher/Developer</h4>
</div>
<form id="updatePubDevFrm" class="dz-clickable dropzone" action="/PubDev/updatePubDev" method="post" enctype="multipart/form-data">
<div class="modal-body">
<div class="row dropzone">
<div class="col-lg-5">
<div class="form-group">
<label for="pubDevName">System Id of Publisher/Developer</label>
<input type="text" placeholder="Name of Publisher/Developer" name="pubDevIdDisplay" id="pubDevIdDisplay" class="form-control input-large" disabled="true">
<input type="hidden" name="pubDevId" id="pubDevId" >
</div>
<div class="form-group">
<label for="pubDevName">Name of Publisher/Developer</label>
<input type="text" placeholder="Name of Publisher/Developer" name="pubDevName-update" id="pubDevName-update" class="form-control input-large">
</div>
<div class="form-group">
<label for="date-founded">Date Founded</label>
<input type="text" placeholder="Date founded" id="date-founded-update" name="date-founded-update" class="form-control date-picker input-large">
</div>
<div class="form-group">
<label>What type of company is this?</label>
<div class="checkbox-nice">
<input type="checkbox" name="isPub-update" id="isPub-update">
<label for="date-founded-update">
This company is a publisher
</label>
</div>
<div class="checkbox-nice">
<input type="checkbox" name="isDev-update" id="isDev-update">
<label for="isDev-update">
This company is a developer
</label>
</div>
</div>
</div>
<div class="col-lg-7">
<div class="main-box clearfix main-box-frame" >
<header class="main-box-header clearfix">
<h2>Upload Publisher /Developer Logo</h2>
</header>
<div class="main-box-body clearfix imgcontainer center">
<img id="preview" src="" class="pointable" alt="No Image Available" style="max-height:100%; max-width: 100%; "/>
<div class="main-box-body clearfix">
<div id="dropzone" class="drop-zone-frame" >
<input type="file" name="image2" id="image2">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" id="confirmUpdPubdev" class="btn btn-primary">Save Modifications.</button>
</div>
</form>
</div>
</div>
Here is the php code:
public function updatePubDev() {
$fields = array();
$fields[$this->pubdev->get_id_name()] = $this->input->post('pubDevId');
$fields['name'] = $this->input->post('pubDevName-update');
if ($this->input->post('date-founded'))
$fields['date_founded'] = stampa_data_formato_DATE($this->input->post('date-founded-update'), '/');
if ($this->input->post('isPub-update'))
$fields['publisher'] = 1;
else
$fields['publisher'] = 0;
if ($this->input->post('isDev-update'))
$fields['developer'] = 1;
else
$fields['developer'] = 0;
$row_count = $this->pubdev->update($fields,$this->pubdev->get_id_name());
$file = $_FILES['image2'];
//$idPubDev = $this->input->post("pubDevName");
$ds = DIRECTORY_SEPARATOR;
$path = dirname('../') . $ds . 'application' . $ds . 'assets' . $ds . 'img' . $ds . 'pub_devs' . $ds . 'logos' . $ds;
//print_r($file);
$info = new SplFileInfo($file['name']);
//var_dump($info->getExtension());
$filename = "logo_id_" . str_pad( $this->input->post('pubDevId'), 11, "0", STR_PAD_LEFT) . "." . $info->getExtension();
$result = $this->upload->uploadfile($file, $path, $filename);
//echo "test";
if ($result['status'] === "OK") {
$logo = 'logo_id_' . str_pad($this->input->post('pubDevId'), 11, "0", STR_PAD_LEFT) . '.' . $info->getExtension();
$this->pubdev->update(array('logo' => $logo, $this->pubdev->get_id_name() => $this->input->post('pubDevId')), $this->pubdev->get_id_name());
$result['message'] = "file saved successfully";
$result['query'] = $this->db->last_query();
}
$result['update_rows']= $row_count;
echo json_encode($result);
}
I tried the .ajax version, but the problem persist, here is the modified jquery:
$('#updatePubDevFrm').submit(function (e) {
e.preventDefault();
var data = $(this).serialize();
var url = '/PubDev/updatePubDev';
$.ajax({
url: url,
type: "POST",
data: data,
processData: false,
contentType: false
})
.done(function (data) {
if (data.status === "OK") {
$('#updatePubDevModal').removeClass('md-show');
} else {
alert("update error!");
}
})
.fail(function (data) {
alert("ajax error!");
})
.always(function () {
});
});
It is not a duplicate question because the answer provide contained different properties necessary to uplaod both image and data inputs. these two properties in the $.ajax call are needed:
processData: false,
contentType: false
This way, it solved my problem.
Use FormData as data instead of $(this).serialize();, set processData and contentType to false
var data = new FormData();
data.append("file", $(":file", this)[0].files[0]);
$.ajax({
url: "/PubDev/updatePubDev",
type: "POST",
data: data,
processData: false,
contentType: false
})
Please try to use file_get_contents('php://input'); to get the upload content.
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(){});