Ajax can't work with wpdb - php

I have Simple code i had Created in Ajax,PHP and Mysql this code work fine in all Conditions Except one this one is wpdb Code to insert Data to table
<script type="text/javascript">
function _(id){ return document.getElementById(id); }
function submitForm(){
_("status").innerHTML = 'please wait ...';
var formdata = new FormData();
formdata.append( "m", _("m").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "<?php bloginfo('template_directory'); ?>/ajax-insert.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "empty"){
_("status").innerHTML = '<div class="error"><p>Please Fill all of the Fields</p></div>';
}
if(ajax.responseText == "Done"){
_("status").innerHTML = '<div class="success"><p>Done</p></div>';
}
if(ajax.responseText == "error"){
_("status").innerHTML = '<div class="success"><p>Problem</p></div>';
}
}
}
ajax.send( formdata );
}
</script>
<form action="" onsubmit="submitForm(); return false;">
<div id="status"></div>
<label>Your Message</label><br>
<textarea cols="50" rows="10" type="text" name="m" id="m"></textarea>
<br>
<input name="submit" type="submit" value="Send">
</form>
ajax-insert.php
i had make code to insert data with some Conditions
this is the code
<?php
if(isset($_POST['m'])){
$message = $_POST['m'];
date_default_timezone_set("Africa/Cairo");
$date = date("Y/m/d h:i:sa");
}if(empty($message))
echo "empty";
elseif(!preg_match("~^[0-9a-z\-'\s\p{Arabic}]{1,60}$~iu", $message)){
echo "error";
}else{
echo "Done";
$insert = $wpdb->insert( 'chat_support', array( 'id' => '1', 'message' => $message , 'date' => $date, 'user' => $user_ID));
}
?>
if i try submit the form while textarea is Empty it give me Response that it is Empty but the Problem When i Write any thing to submit in database the code after Else dosen't work
The response be Please wait..... and This Response Still more thime without Doing and Thing

It is Highly advisable to use WordPress Ajax actions, you need to hookup your function to be called to wp_ajax and it would be available throughout the wp environment
Details about how to create and call ajax functions can be viewed from here https://codex.wordpress.org/AJAX_in_Plugins

Related

Modal ajax form stuck on success message when refired

I have a page with roughly 20 enquiry buttons. Each button fires the same modal ajax PHP form. The form system works as it should, sending an email and triggering the success message. The success message displays inside the form tags but the rest of the form disappears leaving just tags.
The success message has a close button which closes the modal but the problem is that when I click any of the other enquiry buttons on the page they fire the modal but its still stuck on the success message.
Is there a way of using the modal close button as a sort of clear form trigger?
This is the ajax script im using…
<script>
function _(id){ return document.getElementById(id); }
function submitForm() {
_("sendenquiry").disabled = true;
_("status").innerHTML = 'please wait…';
var formdata = new FormData();
formdata.append( "n", _("n").value );
formdata.append( "e", _("e").value );
formdata.append( "m", _("m").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "enquire.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
_("enquiry_form").innerHTML = '<p>Thanks '+_("n").value+', we will be in touch shortly.</p>';
} else {
_("status").innerHTML = ajax.responseText;
_("sendenquiry").disabled = false;
}
}
}
ajax.send( formdata );
}
</script>
This is my html
<!--enquiry modal-->
<div class="enquire-form-modal ef-effect" id="efmodal">
<div class="ef-content">
<div>
<form class="enquire-message" id="enquiry_form" onsubmit="submitForm(); return false;">
<fieldset>
<legend>Please fill out your enquiry below and we'll quickly get back to you.</legend>
<div class="">
<label class="" for="">Name</label>
<span><input type="text" id="n" class="" name="" placeholder="My name" required></span>
</div>
<div class="">
<label class="" for="">Email</label>
<span><input type="email" id="e" class="" name="email" placeholder="My email" required></span>
</div>
<div class="">
<label class="" for="">Enquiry</label>
<span><textarea id="m" class="" name="" placeholder="My enquiry" required></textarea></span>
</div>
<div>
<input id="sendenquiry" type="submit" value="SEND"> <span id="status"></span>
</div>
</fieldset>
</form>
<button class="ef-close">Close</button>
</div>
</div>
</div>
<div class="enquire-form-overlay"></div>
<!--enquiry modal end-->
Any help would be hugely appreciated. I’ve tried various things but nothing is working yet. If you need more code please let me know.
Thanks in advance
The problem is that you're replacing all of the form's html when the ajax call is complete. Try using the "status" div for housing the success message. Then, perhaps a simple setTimeout will suffice for clearing the message.
<script>
function _(id){ return document.getElementById(id); }
function submitForm() {
_("sendenquiry").disabled = true;
_("status").innerHTML = 'please wait…';
var formdata = new FormData();
formdata.append( "n", _("n").value );
formdata.append( "e", _("e").value );
formdata.append( "m", _("m").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "enquire.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
_("status").innerHTML = '<p>Thanks '+_("n").value+', we will be in touch shortly.</p>';
} else {
_("status").innerHTML = ajax.responseText;
}
// clear the "status" message after 5 seconds
setTimeout(function() {
_("status").innerHTML = "";
}, 5000);
_("sendenquiry").disabled = false;
}
}
ajax.send( formdata );
}
</script>

Can`t take value from html textarea to php variable

I made a blogging platform and I have an ajax updated page where I can select which article to display and his comments and add comments. When I leave a comment it takes the logged user info, the article on which the comment has been made but the comment value is not taken to store it in the database. This is the code :
<div align="center">
<h3>Comentarii:</h3>
<form method="POST">
<textarea rows="4" cols="50" name="comentariu" placeholder="Comenteaza">
</textarea><br>
<input type="submit" name="submit"><br>
<hr>
</form>
</div>
<?php
$comnou = $_POST['comentariu'];
$comuser = $_SESSION['user'];
$conadaugacom = mysqli_connect("localhost", "root", "", "blog");
$sqladaugacom = "insert into comentarii (continut_comentarii,
user_comentarii, articol_comentarii) values ('$comnou', '$comuser', '$ta')";
mysqli_query($conadaugacom, $sqladaugacom);
mysqli_close($conadaugacom);
?>
AJAX Code ->
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "getuser.php?q=" + str, true);
xmlhttp.send();
}
}
Make sure that before POST request serialize the data from form.
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div align="center">
<h3>Comentarii:</h3>
<form method="POST">
<textarea rows="4" cols="50" name="comentariu" placeholder="Comenteaza">
</textarea><br>
<input type="submit" name="submit"><br>
<hr>
</form>
</div>
Jquery
<script>
$('input').submit(function(e){
e.preventDefault();
var data = $('form').serialize();
$.ajax({
url: 'your_url_to_post.php',
data: data,
success: function(response){
},
type: 'POST'
});
});
</script>
php file
add this line to check comentariu not empty
if(isset($_POST['comentariu'])){
$comentariu = $_POST['comentariu];
}

How can I output the most recent mysql $row value after it changes without reloading page?

I have a user settings page where the user changes their name via ajax and calls an update script that works great. The problem is I include a separate sidebar file which echos the current name in the database, but doesn't change until you reload the page because it's a separate sidebar.php include.
included sidebar.php within settings.php page
<h2 id="profile-name">
<?php
if(!$userRow['name']){
echo "You";
}else{
echo ucfirst($userRow['name']);
}
?>
</h2>
//form starts
<form id="my_form" onsubmit="submitForm(); return false;">
Name: <input id="name" type="text" class="form-control" placeholder= "<?php echo $userRow['name']; ?>" name="name" value="<?php echo $userRow['name']; ?>"><br>
<input class="btn btn-default" id="mybtn" type="submit" value="Submit Form"> <span id="status"></span>
</form>
//ajax works fine and updates database
function _(id){ return document.getElementById(id); }
function submitForm(){
var formdata = new FormData();
formdata.append( "name", _("name").value );
var ajax = new XMLHttpRequest();
ajax.open( "POST", "update_name.php" );
ajax.onreadystatechange = function() {
if(ajax.readyState == 4 && ajax.status == 200) {
if(ajax.responseText == "success"){
} else {
// _("status").innerHTML = ajax.responseText;
alert("saved");
_("mybtn").disabled = false;
}
}
}
ajax.send( formdata );
}
Just can't figure out how to get the sidebar to update without reloading the page. Thanks everyone!

Form when submitted to display a result (Firstname) on the thank you page

Stuck on a thing with PHP, i know it is something simple but am not sure of the correct way of doing it, either by jquery or php.
I have a contact form which when it submits its form, i want the results of some of the fields to display on the results thank you paeg saying:
Thank you for entering YOURNAME. Blah blah blah
Is this acheivable with a simple line of php or does it need to called through jquery.
Thanks, only new to php so somethings are still bit confusing
<?php
define('is_freetrial-celebrity', 1);
include_once('includes/header.inc.php');
?>
<div role="main" id="main">
<article id="mainFreetrial" class="greyBlock twoColumnsLayout">
<header>
<h1>Get Started</h1>
</header>
<div>
<form method="get" action="/forms_validation/freetrial.php" class="trialForm ajaxForm">
<div class="column">
<p>
<label for="firstNameTrial">First name<sup class="red">*</sup></label><input type="text" id="firstNameTrial" name="firstNameTrial" value="" required/>
</p>
<p>
<label for="lastNameTrial">Last name<sup class="red">*</sup></label><input type="text" id="lastNameTrial" name="lastNameTrial" value="" required/>
</p>
<p>
<label for="ageTrial">Age</label><input type="text" id="ageTrial" name="ageTrial" value=""/>
</p>
<p>
<label for="celebrityTrial" style="display: block; width: auto; margin-bottom: 5px;">Name the celebrity you would most like to meet, and why?<sup class="red">*</sup></label>
<textarea id="celebrityTrial" name="celebrityWhyTrial" style="width: 430px; height: 3em;" required></textarea>
</p>
<p class="ajaxFormBeforeValid">
<input type="submit" value="Submit now" class="redButton"/><span class="ajaxFormWait"></span><span class="ajaxFormError error"></span>
</p>
<div class="ajaxFormValid">
<p>
Thank you! Your local consultant will contact you soon. 'Like' us while you wait for all the latest VIP offers and promotions!
</p>
</div>
<p>
<small>
<sup class="red">*</sup>These are mandatory fields.
</small>
</p>
</div>
</form>
</div>
</article>
</div>
<?php include_once('includes/footer.inc.php'); ?>
Heres the jquery part
/*************************
plugin to manage ajax forms
*************************/
(function( $ ){
var methods = {
init : function( options ) {
return this.each(function(){
var $this = $(this),
data = $this.data('ajaxForm'),
ajaxForm = $('<div />', {
text : $this.attr('title')
});
// If the plugin hasn't been initialized yet
if ( ! data ) {
$(this).data('ajaxForm', {
target : $this,
ajaxForm : ajaxForm
});
//get the spinner, the valid box and the error box
var mySpinner = $this.find('.ajaxFormWait');
var myValid = $this.find('.ajaxFormValid');
var myError = $this.find('.ajaxFormError');
var myBeforeValid = $this.find('.ajaxFormBeforeValid');
myError.hide();
mySpinner.hide();
//add an event to send the form via AJAX
$this.submit(function(){
// get all the inputs into an array.
var $inputs = $this.find(':input:not([type="submit"], [type="button"])');
// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
if (this.type == "radio" || this.type == "checkbox"){
if($(this).is(':checked')){
if(typeof(values[this.name]) === 'undefined'){
values[this.name] = $(this).val();
}else{
values[this.name] += ', '+($(this).val());
}
}
} else
values[this.name] = $(this).val();
});
function defineTheInvalidsFields(fieldsList){
for(var i in fieldsList){
if(fieldsList[i] == 'closestStudio'){
$this.find('[name="'+fieldsList[i]+'"]').parent().addClass('invalid');
}else{
$this.find('[name="'+fieldsList[i]+'"]').addClass('invalid');
}
}
}
//send an AJAX request
$.ajax({
url: $this.attr('action'),
dataType: 'json',
data: values,
beforeSend: function(){
mySpinner.show();
},
success: function(result){
mySpinner.hide();
$this.find('.invalid').removeClass('invalid');
//error management
if(typeof(result.valid) === 'undefined'){
if(result.multipleSend){ //if multiple send
myError.html('Your request is already sent.');
}else if(result.required){ //if fields are required
defineTheInvalidsFields(result.required);
myError.html('The fields in red are required.');
}else if(result.format){ //if the forma is incorrect
defineTheInvalidsFields(result.format);
myError.html('The fields in red have invalid content.');
}else if(result.loginInvalid){
myError.html(result.loginInvalid);
}else{
myError.html('An unknown error occured.');
}
myValid.slideUp(300);
myError.slideDown(300);
}else if(typeof(result.loginUrl) !== 'undefined'){
window.location.href = result.loginUrl;
}else{
if(result.valid || result.valid == 'true'){
if($('#inputFreetrialFitnessFirst').length){
myBeforeValid.slideUp(300);
myError.slideUp(300);
myValid.slideDown(300);
}else{
window.location = '/free-trial-thank-you/';
}
}else{
myError.html('There was an error sending your details. Please try again.');
myValid.slideUp(300);
myError.slideDown(300);
}
}
}
});
return false;
});
//special case for the heardAbout
$('#heardAbout').change(function(){
if($(this).find('option:selected').attr('value') == 'Other'){
$('#otherHeardAbout').slideDown(300);
}else{
$('#otherHeardAbout').slideUp(300);
}
});
}
});
},
destroy : function(){
return this.each(function(){
var $this = $(this),
data = $this.data('ajaxForm');
// Namespacing FTW
$(window).unbind('.ajaxForm');
data.ajaxForm.remove();
$this.removeData('ajaxForm');
})
}
};
$.fn.ajaxForm = function( method ) {
// Method calling logic
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.ajaxForm' );
}
};
})( jQuery );
The form gets sent to the other page, is there a way to target a specific div and add the custom message with the name.
if(result.valid || result.valid == 'true'){
if($('#inputFreetrialFitnessFirst').length){
myBeforeValid.slideUp(300);
myError.slideUp(300);
myValid.slideDown(300);
}else{
window.location = '/free-trial-thank-you/';
}
}else{
myError.html('There was an error sending your details. Please try again.');
myValid.slideUp(300);
myError.slideDown(300);
}
if You wand to fetch specific element div via ajax call You can do like this:
$.ajax({
url: 'page.html',
success: function(data) {
item=$(data).filter('#specific_element');
$(selector).html(item);
}
});
If You wand to redirect to other page using
window.location = '/free-trial-thank-you/';
and then show data on a different page You should pass needet parameters like
window.location = '/free-trial-thank-you/page.php?name1=Daniel&name2=Pablo;
and on different site show parameters using _GET or _POST for example:
echo $_GET['name1'] or echo $_POST['name1'] if You use PSOT method in Your Ajax request
One way that I can think of is using session to store the information.
At freetrial.php store the form information in session like this:
session_start();
$_SESSION['firtNameTrial'] = $_GET['firstNameTrial'];
On ajax success, redirect the page to the thank you page using javascript windows.location.replace:
// similar behavior as an HTTP redirect
window.location.replace("http://yourwebpageaddress.com/thankyou.php");
Get the session on the thank you page. If you don't know, you may look at this example: Click here for session example

CodeIgniter - Ajax validation not working correct and not storing data in database

I'd like some help please.
From my tests till now, I get these:
If validation fails - The div #ajaxResults from my view gets the class alert-error and shows the errors (as expected).
If validation succeeds - The div #ajaxResults gets the class alert-error (not expected) and shows true (as expected).
What I'd like to do is when there's an ajax request is this:
If the validation succeeds - return the div #ajaxResults with a class alert-success(bootstrap) and also display a message saying "data stored in database successfully". I can't figure out how should I return and the message from the controller.
If the validation fails to show the div #ajaxResults with a class alert-error with the validation errors. (as it is)
2.Also I have notice that in case of a NON-ajax-request the data are stored in the database, but in case of an ajax-request don't. How can I fix this to work correct??
This is my controller
public function manage($id = NULL){
$this->layout->add_includes('js/ckeditor/ckeditor.js')->add_includes('js/ajax_scripts.js');
$this->load->library('form_validation');
$data['categ'] = $this->category_model->with_parents();
//fetch a single product or create a new one
if ( isset($id) ) {
$data['prod'] = $this->product_model->get($id);
$data['attr'] = $this->attributes_model->get_by('product_id', $id);
} else {
$data['prod'] = $this->product_model->make_new();
$data['attr'] = $this->attribute_model->make_new();
}
if ( isset($_POST['general_settings']) ) {
if ($this->form_validation->run('product_rules') === true) {
// get post inputs and store them in database
$data = $this->product_model->input_posts(array('product_name', 'brand', 'category_id', 'general_description','visible'));
$this->product_model->save($data, $id);
$result = array('status' => 200, 'message' => 'data stored in database successfully');
} else {
// validation failed
$result = array('status' => 400, 'reason' => validation_errors());
}
if ( $this->input->is_ajax_request() ) {
echo json_encode($result);
exit;
}
$this->session->set_flashdata('message', $result);
redirect('admin/product');
}
// if ( isset($_POST['attribute_settings']) ) { same goes here }
// load the view
$this->load->view('admin/products/manage', $data);
}
this is my js script
$(document).ready(function () {
$('form.ajax-form').on('submit', function() {
var obj = $(this), // (*) references the current object/form each time
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
obj.find('[name]').each(function(index, value) {
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
// console.log(data);
// data.general_settings = 1;
$.ajax({ // see the (*)
url: url,
type: method,
data: data,
dataType: 'json',
success: function(response) {
//console.log(response);
$('#ajaxResults').removeClass('alert alert-success alert-error');
$('.control-group').removeClass('error warning error info success');
if (response.status == 200) {
$('#ajaxResults').addClass('alert alert-success').html(response.message);
$('.control-group').addClass('success'); // ** apply it only on valid fields
} else {
$('#ajaxResults').addClass('alert alert-error').html(response.reason);
$('.control-group').addClass('error'); // ** apply it only on invalid fields
}
}
});
return false; //disable refresh
});
});
one of my forms with class .ajax-form inside the view
<?php echo form_open('admin/product/manage/'.$prod->product_id, array('class' => 'ajax-form')); ?>
<div class="control-group">
<label class="control-label" for="product_name">Product *</label>
<input type="text" name="product_name" value="<?php echo set_value('product_name', $prod->product_name); ?>" />
<?php echo form_error('product_name'); ?>
</div>
<div class="control-group">
<label class="control-label" for="brand">Brand</label>
<input type="text" name="brand" value="<?php echo set_value('brand', $prod->brand); ?>" />
<?php echo form_error('brand'); ?>
</div>
// apply same to all my fields
<p>
<label for="category_id">Category *</label>
<?php echo form_dropdown('category_id', $categ);
echo form_error('category_id');
?>
</p>
<p>
<label for="general_description">General Description</label>
<textarea class="ckeditor" name="general_description" rows="10" cols="250"><?php echo set_value('general_description', $prod->general_description); ?></textarea>
<?php echo form_error('general_description') . PHP_EOL; ?>
</p>
<p>
<label for="visible">Visible</label>
<select name="visible" class="span1">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
</p>
<p>
<button class="btn btn-primary" type="submit" name="general_settings">Ok</button>
</p>
<?php echo form_close() . PHP_EOL; ?>
Any help would be appreciated.
As I'm understand You need something like this (I've put just code fragments).
Controller:
if($this->form_validation->run('product_rules') === true){
//your code will be here
$result = array(
'status' => 200, 'message' => 'data stored in database successfully'
);
}
else{
$result = array('status' => 400, 'reason' => validation_errors());
}
if ( $this->input->is_ajax_request()){
echo json_encode($result);
exit;
}
else{
$this->session->set_flashdata('message', $result);
redirect('admin/product');
}
Ajax function:
data.general_settings = 1;
$.ajax({
url: url,
type: method,
data: data,
dataType: 'json',
success: function(response) {
$('#ajaxResults').removeClass('alert alert-success alert-error');
if(response.status == 200){
$('#ajaxResults').addClass('alert alert-success').html(response.message);
}
else{
$('#ajaxResults').addClass('alert alert-error').html(response.reason);
}
}
});
Are You saw same errors in firebug for ajax request?

Categories