I am storing the unicode values in java script array but when I pass it to the ci controller it is not showing in proper language.
How to pass javascript unicode array to php using form post?
My code is:-
var myTableArray = [];
$("table#search_result_table tr").each(function() {
var arrayOfThisRow = [];
var tableData = $(this).find('td');
if (tableData.length > 0) {
tableData.each(function() { arrayOfThisRow.push($(this).text()); });
myTableArray.push(arrayOfThisRow);
}
});
var myJSON = JSON.stringify(myTableArray);
$.post("<?php echo base_url("Purchase/addnew"); ?>",{data:
myJSON},$("#purform").serialize(),function(data)
Santosh, to post Unicode Array through AJAX and JSON, you need 3 files i.e. Javascript file, html file and a php file. Below is the samle code,
JS file
// make the AJAX request
// #dataform : it is a html data form id
var dataString = $('#dataform').serialize();
$.ajax({
type: "POST",
url: 'php_file.php',
data: dataString,
dataType: 'json',
success: function (data) {
if (data.success == 0) {
var errors = '';
if (data.err_msg != '')
alert('Error');
}
else if (data.success == 1) {
alert('Success');
}
},
error: function (x,e) {
alert('Error: '+x.status+','+x.responseText);
}
});
HTML file
<form id="dataform" name="dataform" method="post" action="" role="form">
<input type="text" name="field1" id="field1" />
<input type="text" name="field2" id="field2" />
<input type="text" name="field3" id="field3" />
<input type="text" name="field4" id="field4" />
<button type="button" name="submit" id="submit" onclick="return false;">Submit</button>
</form>
PHP file
$field1=$_REQUEST["field1"];
$field2=$_REQUEST["field2"];
$field3=$_REQUEST["field3"];
$field4=$_REQUEST["field4"];
//Your Validation Logic
$return_array = validate($field1);
if($return_array['success'] == '1') {
//Your SQL Query //
}
function validate($field1)
{
$return_array = array();
$return_array['success'] = '1';
$return_array['err_msg'] = '';
//Validate Field Logic
if($field1=='')
{
$return_array['success'] = '0';
$return_array['err_msg'] = 'Field1 is required!';
}
return $return_array;
}
header('Content-type: text/json');
echo json_encode($return_array);
die();
Related
I'm trying to post input data and display it on the same page (view_group.php) using AJAX but I did not understand how it works with MVC, I'm new with MVC if anyone could help me it would be very helpful for me.
view_group.php
<script type = "text/javascript" >
$(document).ready(function() {
$("#submit").click(function(event) {
event.preventDefault();
var status_content = $('#status_content').val();
$.ajax({
type: "POST",
url: "view_group.php",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {}
});
});
}); </script>
if(isset($_POST['postStatus'])){ $status->postStatus($group_id); }
?>
<form class="forms-sample" method="post" id="form-status">
<div class="form-group">
<textarea class="form-control" name="status_content" id="status_content" rows="5" placeholder="Share something"></textarea>
</div>
<input type="submit" class="btn btn-primary" id="submit" name="submit" value="Post" />
</form>
<span id="result"></span>
my controller
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
}
first in the ajax url you must set your controller url , then on success result value will be set on your html attribute .
$.ajax({
type: "POST",
url: "your controller url here",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {
$('#result).text(result);
}
});
Then on your controller you must echo the result you want to send to your page
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
echo $status;
}
I have created an AJAX function in Wordpress. The function is called on form submission. The function is run, but it is not receiving any of the form data that I have submitted. What am I missing?
PHP Function
I have added the PHP function here, which is called successfully via AJAX. This form creates a new user successfully, but only when I create the variables manually (eg. see $new_user_data['user_login'] = 'This Text Works';). For some reason, the $_POST data isn't coming through to the function.
add_action("wp_ajax_register_user", __NAMESPACE__ . "\\register_user");
add_action("wp_ajax_nopriv_register_user", __NAMESPACE__ . "\\register_user");
function register_user() {
// NONCE VERIFICATION
if ( !wp_verify_nonce( $_REQUEST['nonce'], "rtr_register_nonce")) {
exit("Oops! This is embarassing!");
}
// Get all post data for the user.
$new_user_data = array();
$new_user_data['first_name'] = sanitize_text_field($_POST['first-name']);
$new_user_data['last_name'] = sanitize_text_field($_POST['last-name']);
$new_user_data['user_email'] = $_POST['email'];
$new_user_data['user_pass'] = sanitize_text_field($_POST['password']);
$new_user_data['user_login'] = 'This Text Works';
$new_user_data['role'] = 'subscriber';
// Create the User
$registered_user = wp_insert_user( $new_user_data );
$result['user'] = $registered_user;
// AJAX CHECK
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
} else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die();
}
JQuery
function registerUser(){
var nonce = $('#regForm').attr("data-nonce");
var formData = $('#regForm').serialize();
$.ajax({
url: rtr_register_user.ajaxUrl,
type: 'post',
dataType: 'json',
data : {action: 'register_user', nonce: nonce, formData: formData},
success: function (response) {
console.log(response);
$('#regForm').html('Your form has been submitted successfully');
},
});
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("form-tab");
// Exit the function if any field in the current tab is invalid:
if (n === 1 && !validateForm()) {
return false;
}
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form... :
if (currentTab >= x.length) {
//...the form gets submitted:
//document.getElementById("regForm").submit();
registerUser();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
$('#nextBtn').click(function () {
nextPrev(1);
});
$('#prevBtn').click(function () {
nextPrev(-1);
});
Form
<?php
$nonce = wp_create_nonce("rtr_register_nonce");
$link = admin_url('admin-ajax.php?action=register_user&nonce='.$nonce);
?>
<form id="regForm" <?php echo 'data-nonce="' . $nonce . '"'; ?> action="<?php echo $link; ?>" method="post" enctype="multipart/form-data">>
<div class="my-3 text-center">
<span class="form-step">1</span>
<span class="form-step">2</span>
</div>
<div class="form-tab">
<p><input name="first-name" placeholder="First Name" oninput="this.className = ''"></p>
<p><input name="last-name" placeholder="Last Name" oninput="this.className = ''"></p>
<p><input name="dob" type="date" oninput="this.className = ''"></p>
</div>
<div class="form-tab">
<p><input name="email" type="email" placeholder="Email" oninput="this.className = ''"></p>
<p><input name="password" type="password" placeholder="Password" oninput="this.className = ''"></p>
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" class="btn btn-brand" id="prevBtn">Previous</button>
<button type="button" class="btn btn-brand" id="nextBtn">Next</button>
</div>
</div>
</form>
Seems you are not triggering registerUser() check following script works fine for me
jQuery(document).ready(function($) {
jQuery('body').on('click', '#nextBtn', function() {
registerUser();
});
});
function registerUser(){
var nonce = jQuery('#regForm').attr("data-nonce");
var formData = jQuery('#regForm').serialize();
jQuery.ajax({
url: ajaxurl,
type: 'post',
dataType: 'json',
data : {action: 'register_user', nonce: nonce, formData: formData},
success: function (response) {
console.log(response);
$('#regForm').html('Your form has been submitted successfully');
},
});
}
add method="post" to your 'form' - 'get' is the default https://stackoverflow.com%2Fquestions%2F2314401%2Fwhat-is-the-default-form-http-method&usg=AOvVaw1dKc3hW4K6r5SwQurLztBw
The "user_login" is a username of the user so probably it doesn't accepts space too.
See also WP Insert Post
Please try passing some username such as "custom_user" and see the result.
Hope this might work.
Ok it was a bit of help from everyone here. But yes, I was calling the AJAX correctly, but not actually submitting the form. I added a .on(submit) to the form and then added a listener to the form to perform the AJAX call on submit. Here's the amendments below.
function nextPrev(n) {
var x = document.getElementsByClassName("form-tab");
if (n === 1 && !validateForm()) {
return false;
}
x[currentTab].style.display = "none";
currentTab = currentTab + n;
if (currentTab >= x.length) {
// ADDED THIS SUBMIT() HERE
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
// ADDED AN EVENT LISTENER TO TRIGGER THE AJAX CALL HERE
$('#regForm').on('submit', function () {
var nonce = $('#regForm').attr("data-nonce");
var formData = $('#regForm').serialize();
$.ajax({
url: rtr_register_user.ajaxUrl,
type: 'post',
dataType: 'json',
data: {
action: 'register_user',
nonce: nonce,
formData: formData
},
success: function (response) {
console.log(response);
$('#regForm').html('Your form has been submitted successfully');
},
});
});
I need your help to try to sort out an issue with ajax callback.
What happen is that the php script is called without issues, the query works fine and it generate the json output, but the callback doesn't works.
No div is displayed on success and no changes on class happens.
This is my form
<form class="form-inline">
<input type="hidden" id="id_pro" value="1">
<input type="hidden" id="status" value="1">
<button id="submit" type="button" class="btn btn-link">
<span id="check" class="glyphicon glyphicon-check" title="my tytle"></span>
</button>
</form>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Form Submitted Success</span>
This is the js part
$(function() {
$("#submit").click(function() {
var id_pro = $("#id_pro").val();
var status = $("#status").val();
var dataString = 'id_pro='+ id_pro + '&status=' + status;
if(id_pro=='' || status=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "myphppage.php",
data: dataString,
datatype: 'json',
success: function(data)
{
if(data.result=='1')
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
$("#check").attr('class', data.check);
}
}
});
}
return false;
});
});
And this is the php part
<?
if($_POST)
{
$id_pro=$_POST['id_pro'];
$status=$_POST['status'];
if($status==0){$status=1;}else{$status=0;}
if ($mysqli->query("UPDATE mytable SET online=".$status." WHERE id=".$id_pro." ") === TRUE) {
header("Content-type: application/json");
$data = array('check'=>'new_class','check_text'=>'new text','result'=>'1');
print json_encode($data);
}
else
{
header("Content-type: application/json");
$data = array('result'=>'0');
print json_encode($data);
}
$result->close();
}else { }
?>
Any idea?
Thank you in advance
error 500 means error in php and in your php don't see defined $mysqli and $result i think here is your problem.
better PHP looks like this but must define connect to DB
<?php
header("Content-type: application/json");
$data = array('result'=>'0');
if ($_SERVER['REQUEST_METHOD'] == 'post' )
{
$id_pro = $_POST['id_pro'];
$status = ($_POST['status'] == 0) ? 1 : 0; // if($status==0){$status=1;}else{$status=0;}
// define $mysqli
if ($mysqli->query("UPDATE mytable SET online=".$status." WHERE id=".$id_pro." ") === TRUE) {
$data = array('check'=>'new_class','check_text'=>'new text','result'=>'1');
}
// $result->close(); // ????
}
print json_encode($data);
I'm new to using jQuery with AJAX. I want to build a simple form that prompts the user when one of the field inputs are incorrect.
My only requirement (for now) is that the name must be "John".
html (ajaxtutorial.html)
<!DOCTYPE html>
<html>
<head>
<title>AJAX Form</title>
</head>
<body>
<form action="ajax/contact.php" method="post" class="ajax">
<div>
<input type="text" name="name" placeholder="Your name">
</div>
<div>
<input type="text" name="email" placeholder="Your email">
</div>
<div>
<textarea name="message" placeholder="Your message"></textarea>
</div>
<input type="submit" value="Send">
<div>
</form>
<script src="js/jquery-1.11.0.js"></script>
<script src="js/main.js"></script>
</body>
</html>
jQuery (main.js):
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this), //references the inputs within the find function
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
dataType: 'json',
cache: false,
success: function(result) {
if(result.error == true) {
console.log('Did not type John');
}
else {
console.log('Typed John');
}
}
});
return false;
});
php (contact.php):
<?php
$errors = array();
$form_data = array();
$name = htmlspecialchars($_POST['name']);
$email = htmlspecialchars($_POST['email']);
$message = htmlspecialchars($_POST['message']);
if ($name != 'John') {
$errors['name'] = true;
}
if (array_key_exists('name',$errors)) {
$form_data['success'] = true;
$form_data['error'] = true;
} elseif (empty($errors)) {
$form_data['success'] = true;
}
echo json_encode($form_data);
?>
I feel it's simple, but can't solve it. I want to identify the error by it's class (i.e. result.['class']) in order to provide unique feedback for each error.
Thanks for the help
Try to use serialize() instead of looping like,
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method');
$.ajax({
url: url,
type: type,
data: that.serialize(),// use form.serialize() here
dataType: 'json',
cache: false,
success: function(result) {
if(result.error == true) {
console.log('Did not type John');
}
else {
console.log('Typed John');
}
}
});
return false;
});
Also in PHP in case of error, your are assigning success and error both try it like,
if (array_key_exists('name',$errors)) {
// remove success key from here
$form_data['error'] = true;// only error
} elseif (empty($errors)) {
$form_data['success'] = true; // only success
}
echo json_encode($form_data);
m having a problem while submitting the form using jquery & Ajax. my prob is that i want to insert some values into the database before submitting the form. code that i am using is as below for form submission :
$('.buttons').click(function(){
var account_num = $("#accountNum").val();
var ref_num = $("#refNum").val();
var dataString = "account_num="+ escape(account_num) + "&reference_no=" + escape(ref_num);
$("#frmTransaction").hide();
$("#loader_div").show();
$.ajax({
type : "Post",
url : "validate-data.php",
data : dataString,
success: function(html) {
if(html) {
alert(html);
$("#frmTransaction").submit();
} else {
alert('Unknown Error Please...Retry');
return false;
}
}, error :function (){
return false
},
complete: function () { }
});
return false;
});
html form is as :
<form method="post" action="https://sample.com/pay" name="frmTransaction" id="frmTransaction">
<input name="accountNum" id="accountNum" type="hidden" size="60" value="<? echo $_POST['account_id'] ?>">
<input name="refNum" id="refNum" type="hidden" size="60" value="<? echo $reference_no;?>" />
<input type="text" class="field" name="name" id="name" />
<input type="text" class="field" name="city" id="city" />
<input type="text" class="field" name="state" id="state" />
<input type="text" class="field" name="postal_code" id="postal_code" />
<input type="submit" class="buttons" name="submitted" value="Proceed" />
</form>
content of validate-data.php is as :
<?PHP
$account_num = $_REQUEST['account_num'];
$reference_no = $_REQUEST['reference_no'];
$countF = mysql_num_rows(mysql_query("SELECT * FROM orders where order_id='".$reference_no."'"));
if($countF == 0 ) {
$res = mysql_query("insert into orders(order_id, user_account_num)values('".$reference_no."', '".$account_num."')");
}
if($res)
echo "$res ";
else
echo "";
?>
only two problem :
One, see your callback success:
success: function(html) {
if(html) {
alert(html);
$("#frmTransaction").submit();
} else {
alert('Unknown Error Please...Retry');
return false;
}
}
your if statement will ask to computer, if isset variable html
and two, you print the mysql query on your php code ...
if($res)
echo "$res ";
else
echo "";
and the workaround:
change your jquery code with this one:
$.ajax({
type : "Post",
url : "validate-data.php",
data : dataString,
success: function(html) {
var callback = $.parseJSON(html); // Parse your callback
if(callback.process == 'success'){
$("#frmTransaction").submit();
} else {
alert('Unknown Error Please...Retry');
}
}, error:function(){
alert('Unknown Error Please...Retry');
},
});
and the php code:
<?PHP
$account_num = mysql_real_escape_string($_POST['account_num']); // make sure `$_POST` and `mysql_real_escape_string` used to prevent sql injection
$reference_no = mysql_real_escape_string($_POST['reference_no']); // And this line too
$countF = mysql_num_rows(mysql_query("SELECT * FROM orders where order_id='".$reference_no."'"));
if($countF == 0 ) {
$res = mysql_query("insert into orders(order_id, user_account_num)values('".$reference_no."', '".$account_num."')");
}
if($res){
echo json_encode(Array("process" => "success"));
}
else {
echo json_encode(Array("process" => "fail"));
}
?>
Good luck, Friend
Your form doesn't submit because in the Javascript for the submit button click, you return false at the end. That means the form will be prevented from submitting, so remove that line completely.
I also noticed you're building the raw post data as a string, you can do that but it's easier to let jQuery take care of it, you can pass an object literal instead and forget about the encoding:
$.ajax({
.....
data : { 'account_num' : account_num, 'reference_no' : ref_num },
.....
In the PHP you are echoing a MySQL result resource. Instead you should echo something like a boolean 1 or 0, or JSON encode a response object.
echo $res ? '1' : '0';
The above is a ternary operator which is saying, if the query was successful then echo 1, if not then echo 0.