I am using wordpress and need to update a tables data with jQuery ajax, I have the below code which posts the data successfully.
jQuery('#update-<?php echo $row->id; ?>').live('click', function (){
var myname = jQuery('input[name="name_two"]').val();
var mystep = jQuery('#step<?php echo $row->id; ?> option:selected').val();
jQuery.ajax({
type: "POST",
url: "/wp-content/plugins/gates/updateGateData.php",
data: {name_two:myname, step_two:mystep},
success: function(data) {
alert('Data updated');
},
});
});
Now my problem resides on what to put in the updateGateOption.php file to post to update the database.
Thanks Guys for the responses! So I have this now:
$name = $_POST['name_two'];
$step = $_POST['step_two'];
global $wpdb;
$wpdb->update(
'gate_options',
array(
'step' => $step,
'name' => $name,
'image_path' => 'new-img-path',
'option' => strtolower($name),
'value' => strtolower($name),
)
);
But the values are not being updated, plus I cannot see any errors..
Try below Code in updateGateOption.php:
$name = $_POST['name_two'];
$step = $_POST['step_two'];
Now run your query,
if(mysql_query("UPDATE tablename SET field1= $name, field2=step WHERE 1=1 AND YOUR_CONDITION")){
echo "Data updated successfully";
}else{
echo "Something went wrong";
}
Related
I am running a form which is posting data to database in such a way that every question field is having many options that are generated dynamically, the question query is working good but the option that are created dynamically(that query runs to 500) is not working.
front end and html structure:
<input name="text" placeholder="Question text" type="text" id="text">
<input type="text" placeholder="text" name="option_text[]" class="fieldname">
<input type="number" placeholder="0" name="option_score[]" class="fieldtype">
jquery: which is functioning correctly
function abc(){
var fName = new Array();
jQuery('.fieldname').each(function(index, value){
fName.push(jQuery(this).val());
})
var fType = new Array();
jQuery('.fieldtype').each(function(index, value){
fType.push(jQuery(this).val());
})
jQuery.ajax({
type: 'POST',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: { action: 'savedataques', text: document.getElementById('text').value, textopt: fName, score: fType},
success: function(data){
alert('success');
alert('data');
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
The Php code: the data query is good but the dataop query runs int the error of blank page.
function savedataques(){
global $wpdb;
$data = ($wpdb->insert('wp_dbquestions', array(
'text' => $_POST['text'],
)
));
$lastid = $wpdb->insert_id;
echo $lastid;
this is where the problem is:
$dataop = ($wpdb->insert('wp_questoptions', array(
'question_id' => $lastid
'text' => $_POST['textopt'],
'score' => $_POST['score'],
)
));
}
exit;
die();
return true;
}
//
add_action('wp_ajax_savedataques', 'savedataques');
//add_action('wp_ajax_nopriv_savedataques', 'savedataques');
this is the solution:
just need to apply a foreach on all the dynamically generated options
$i=0;
$optiontext = $_POST['textopt'];
foreach($optiontext as $key => $val ){
$score = $_POST['score'][$i];
$textopt = $_POST['textopt'][$i];
$i++;
then the query:
$data = ($wpdb->insert('wp_questoptions', array(
'question_id' => $lastid,
'text' => $textopt,
'score' => $score,
)
));
done
I'm calling a wordpress plugin function via a front end page which is working good, the function that i m calling is inserting data into the database but its not working
here is the query i m running(which is not working):
The function is being called on submit as echo value is printed but no data is being inserted
function savedata(){
echo "<pre>";print_r($_POST);exit;
global $wpdb;
$wpdb->insert('questoptions',
array(
'question_id' => $_POST['question_id'],
'text' => $_POST['text']
),
array(
'%s',
'%s'
)
);
die();
return true;
}
here is the function calling this function from front end:
function abc(){
jQuery.ajax({
type: 'POST',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: { action: 'savedata', 'question_id': document.getElementById('question_id').value, 'text': document.getElementById('text').value },
success: function(data){
alert('success');
console.log(data);
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
anyone has any idea?
Thanks.
Wordpress ajax function infromation
Add this functions and check your post data is called or not ?
wp_ajax_nopriv_(action) executes for users that are not logged in.
add_action( 'wp_ajax_savedata', 'custom_savedata' );
add_action( 'wp_ajax_nopriv_savedata', 'custom_savedata' );
function custom_savedata() {
global $wpdb;
if(isset($_POST) && !empty($_POST['question_id'])):
$data = ($wpdb->insert('table_name_add_here', array(
'question_id' => $_POST['question_id'],
'text' => $_POST['text'],
)
));
if($data){
echo 'success';
}else{
echo 'not success';
}
else:
echo 'please check post data';
endif;
exit;
}
plz remove second line
echo "<pre>";print_r($_POST);exit;'
so it execute rest of code and return.
if u should try this and also not get solution than u must be check your database table name if table name pretend by 'wp' than u should try wp_ questoptions as table name in query instead of questoptions.
thinks. might be it will help you.
I am creating a rating system in which when user rate any company then rate stored into rate along with the v_id table. (v_id is company id),
This is my url in which i want to rate...
www.ABC.com/controller/function/company_id
Here company_id is getting from database. I want to store the company rating into rate table. when user click on the star.
Controller
function visa_company_profile($v_id) {
$data['total_ratings'] = $this->Visa_mdl->total_ratings($v_id);
$data['total_average'] = $this->Visa_mdl->total_average($v_id);
$result = $this->Visa_mdl->get_company_profile($v_id);
$data['items_company_profile'] = $result;
$this->load->view('include/header');
$this->load->view('hotels/company_profile',$data);
$this->load->view('include/footer');
}
Views
This is ajax part in which i am sending the star values to the controller
$(document).ready(function(){
var click_val = 0;
$("#1_star").hover(function(){
$("#1_star").attr("src","<?php echo base_url('assets/rating/star.png'); ?>");
$("#2_star").attr("src","<?php echo base_url('assets/rating/blank_star.png'); ?>");
$('#3_star').attr('src',"<?php echo base_url('assets/rating/blank_star.png'); ?>");
$('#4_star').attr('src',"<?php echo base_url('assets/rating/blank_star.png'); ?>");
$('#5_star').attr('src',"<?php echo base_url('assets/rating/blank_star.png'); ?>");
});
$("#1_star").click(function(){
click_val = 1;
$.ajax({
url: '<?php echo base_url('Account/loggedin');?>',
success: function(logged_in) {
if (logged_in === "1") {
ajaxCall();
}else {
$("#l_modal").modal('show');
}
}
});
});
function ajaxCall() {
$.ajax({
method : 'POST',
data: {'click_val':click_val},
url: '<?php echo base_url('Hotels/ratings/');?>',
success: function() {
location.reload();
}
});
}
Star Controller To store Rate into data
Here i am trying to get the company id from url and store into column(v_id) rate table.
function ratings() {
date_default_timezone_set('Asia/Kolkata');
$last = $this->uri->total_segments();
$record_num = $this->uri->segment($last);
$value = array (
'rate' => $this->input->post('click_val'),
'date' => date('Y-m-d H:i:s'),
'v_id' => $record_num
);
$this->Visa_mdl->ratings($value);
}
Model
function ratings($value) {
$this->db->insert('user_ratings',$value);
}
You can do it simply modifying you ajax function input value
function ajaxCall() {
$.ajax({
method : 'POST',
data: {'click_val':click_val,'company_id':<?php echo $this->uri->segment(3)},
url: '<?php echo base_url('Hotels/ratings/');?>',
success: function() {
location.reload();
}
});
}
Again you can catch the company ID in your controller Function Hotels/ratings.
function visa_company_profile($v_id) {
$data['v_id'] = $v_id;
$data['total_ratings'] = $this->Visa_mdl->total_ratings($v_id);
$data['total_average'] = $this->Visa_mdl->total_average($v_id);
$result = $this->Visa_mdl->get_company_profile($v_id);
$data['items_company_profile'] = $result;
$this->load->view('include/header');
$this->load->view('hotels/company_profile',$data);
$this->load->view('include/footer');
}
If you pass click value in url then ajax script should be like this:
function ajaxCall() {
var company_id = '<?php echo $v_id; ?>';
$.ajax({
method : 'POST',
data: {'click_val':click_val, 'company_id':company_id},
url: '<?php echo base_url('Hotels/ratings/');?>'+click_val+'/'+company_id,
success: function() {
location.reload();
}
});
}
Because you are not passing click value in url so controller should be like that:
function ratings() {
date_default_timezone_set('Asia/Kolkata');
$record_num = $this->input->post('company_id', true);
$value = array (
'rate' => $this->input->post('click_val', true),
'date' => date('Y-m-d H:i:s'),
'v_id' => $record_num
);
$this->Visa_mdl->ratings($value);
}
And controller:
function ratings($record_num = 0, $company_id = 0) {
date_default_timezone_set('Asia/Kolkata');
$value = array (
'rate' => $record_num,
'date' => date('Y-m-d H:i:s'),
'v_id' => $company_id
);
$this->Visa_mdl->ratings($value);
}
HTML, AJAX and PHP included below. Before introducing AJAX, everything functions (form tags and PHP processing values removed from HTML below).
The drop-down (categories) is populated from a MySQL query. When the user selects an option, I want to pass the ID via ajax to a PHP script (index.php) to run a MySQL query to populate another drop-down (sub-categories).
The Chrome console log indicates that ajax is passing the ID correctly.
Firebug also shows it passing and that the URL is correct (index.php?business_category_id=ajax-passed value). If the GET variable is being passed, and my PHP script is looking for it, why is the script not responding? Why is it not receiving the value? I cannot echo it, so I know it's not being received.
The ajax script is in js/script.js, index.php (my controller) is in the root, and the page with the html (buy-a-biz.php) is in the root and included in the php script (see below).
If anyone can help, I'd appreciate it very much. I am new to using jQuery ajax.
HTML.
<select name="category" id="business-category">
<option value="all_categories">Select category</option>
<?php foreach ($categories as $category): ?>
<option value="<?php htmlout($category['id']); ?>"><?php htmlout($category['name']); ?></option>
<?php endforeach; ?>
</select>
AJAX. I experimented using $.get and $.post also.
$(document).ready(function(){
$("#business-category").change(function(){
var category_id = $(this).val();
console.log(category_id);
$.ajax({
type: 'GET',
url: 'index.php',
data: { business_category_id: category_id },
success: function(category_id){
$("#result").html(category_id + ' submitted successfully!');
}
});
});
});
PHP.
if(isset($_GET['business_category_id'])){
$category_id = htmlspecialchars($_GET['business_category_id']);
include 'includes/dbconnect.php';
try {
$sql = "SELECT * FROM sub_category
WHERE category_id = :category_id";
$s = $db->prepare($sql);
$s->bindValue(":category_id", $category_id);
$s->execute();
while($row = $s->fetch(PDO::FETCH_ASSOC)){
$sub_categories[] = array(
'id' => $row['id'],
'category_id' => $row['category_id'],
'name' => $row['name']
);
}
$sql2 = "SELECT * FROM category";
$s2 = $db->prepare($sql2);
$s2->execute();
while($row = $s2->fetch(PDO::FETCH_ASSOC)){
$categories[] = array(
'id' => $row['id'],
'name' => $row['name'],
);
}
}
catch (PDOException $e) {
$errMsg = "Error fetching data" . $e->getMessage();
include 'error.html.php';
exit();
}
include 'buy-a-biz.php';
exit();
}
You are passing a done callback to $.ajax. You should either name this callback success
$.ajax({
type: 'GET',
url: 'index.php',
data: { business_category_id: category_id },
success: function(category_id){
$("#result").html(category_id + ' submitted successfully!');
}
});
or invoke done on the promise returned by $.ajax:
$.ajax({
type: 'GET',
url: 'index.php',
data: { business_category_id: category_id },
}).done(function(category_id) {
$("#result").html(category_id + ' submitted successfully!');
});
I have a problem
There is a rating system on songs (Its not my code i debugging it). but it could not add or update or show me the rating.
here is my code:
Ajax.js
function bindEvents() {
$(cssSelector.rating_succes).css('display','none');
//Set the new rating when the user clicks
$(cssSelector.ratingLevel).click(function() {
var $this = $(this), rating = $this.parent().children().index($this) + 1, index;
var trackname = $(cssSelector.title+':first').text();
var postdata1 = 'action=my_special_ajax_call5&rating='+rating+'&trackname='+trackname;
alert(postdata1);
jQuery.ajax({
type:'POST',
url:ajaxurl,
cache:false,
data: postdata1,
beforeSend:function(){
},
success:function(res){
$(cssSelector.rating_succes).html(res).fadeIn(500).delay(1000).fadeOut(500);
//window.setTimeout(function(){location.reload()},2000);
}
});
$this.prevAll().add($this).addClass(attr(cssSelector.ratingLevelOn)).end().end().nextAll().removeClass(attr(cssSelector.ratingLevelOn));
});
}
Proccess.php
function implement_ajax5(){
global $wpdb;
$table = $wpdb->prefix."songs";
$table1 = $wpdb->prefix."rating";
$song_title = strip_tags($_POST['trackname']);
$rating_value = strip_tags($_POST['rating']);
$songres = $wpdb->get_row("SELECT * FROM $table WHERE `title`='$song_title'") or die(mysql_error());
$song_id = $songres->id;
$total_votes = $songres->total_votes;
$total_votes = $total_votes+1;
$ip = $_SERVER['REMOTE_ADDR'];
$data = array(
'song_id' => $song_id,
'rating_value' => $rating_value,
'user_ip' => $ip
);
$check = $wpdb->get_results("SELECT * FROM $table1 WHERE song_id='$song_id' AND user_ip='$ip'");
if(!$check){
$insert = $wpdb->insert($table1,$data);
$wpdb->update(
$table,
array(
'total_votes' => $total_votes,
),
array( 'ID' => $song_id )
) or die(mysql_error());
echo 'Thank you';
}else{echo 'Already rated';}
die();
}
index.php
add_action('wp_ajax_my_special_ajax_call5', 'implement_ajax5');
add_action('wp_ajax_nopriv_my_special_ajax_call5', 'implement_ajax5');//for users that are not logged in.
I dont understand what happen when i alert it shows me right values but not add or update in database.
ok just try this in your Ajax.js at top of the page
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
And every thing goes perfect
and i think in your process page there is no need to update query. If you want to delete this there is no issue.
i get this a lot........ajaxurl needs to be defined, so i've learned that its just easier to not use ajaxurl and put in "/wp-admin/admin-ajax.php" in the url section.
Also i dont see you using non-conflict jQuery? (use the word jQuery instead of $)
You may also have issues with your postdata string, i may be wrong but what you need is action: '' ,
rating: '',
etc.
A good practice is to var_dump $_POST and exit at the beginning of your function to make sure they are passing over correctly. then in success- console.log(res) or whatever you are calling your return data
function bindEvents() {
jQuery(cssSelector.rating_succes).css('display','none');
//Set the new rating when the user clicks
jQuery(cssSelector.ratingLevel).click(function() {
var $this = jQuery(this), rating = $this.parent().children().index($this) + 1, index;
var trackname = jQuery(cssSelector.title+':first').text();
//alert(postdata1); -> console.log() is better for looking at objects
jQuery.ajax({
type:'POST',
url: "/wp-admin/admin-ajax.php",
cache:false,
data: {
action: 'my_special_ajax_call5',
rating: rating,
trackname: trackname
}
success:function(output){
console.log(output)
jQuery(cssSelector.rating_succes).html(output).fadeIn(500).delay(1000).fadeOut(500);
//window.setTimeout(function(){location.reload()},2000);
}
});
$this.prevAll().add($this).addClass(attr(cssSelector.ratingLevelOn)).end().end().nextAll().removeClass(attr(cssSelector.ratingLevelOn));
});
}
see how you get on with that :)