500 error on javascript, ajax update of MYSQL cell - javascript

jquery.js?ver=1.12.4-wp:4
POST https://xyz/update.php 500 (Internal Server Error)
send # jquery.js?ver=1.12.4-wp:4
ajax # jquery.js?ver=1.12.4-wp:4
myFunction # 6011c7fbf.min.js?ver=1600216310:3
onclick # (index):453
I am getting a 500 error above from the console. What I dont know is whether the error is in my PHP in trying to update the row or elsewhere.
PHP below is contained inside my update-file.php file
function function_1() {
global $wpdb;
$wpdb->query( $wpdb->prepare("UPDATE 'my_table_name' SET `currentstatus` = 'myupdate1' WHERE ID = '1'"));
}
JAVASCRIPT contained on the page
function myFunction() {
jQuery.ajax({
type: 'post',
url: '/wp-content/themes/yummy/update-file.php',
success: function(data){
// callback function
}
});
alert("I've been clicked!!");
}
HTML
Go!
EDIT 1
As per suggestions I have updated as such:
JAVASCIPT
jQuery.ajax({
type: 'post',
url: my_ajax.ajax_url,
action: 'function_1',
success: function(data){
// callback function
}
});
Thinking the above was not correct I also tried :
jQuery.ajax({
type: 'post',
url: my_ajax.https://myurl.com/wp-content/themes/yummy/update-waitinglist.php, // this is the location of the update php below
action: 'function_1',
success: function(data){
// callback function
}
});
PHP below is contained inside my update-file.php file
add_action('wp_ajax_function_1', 'myfunctionname'); // logged in user can make a call
add_action('wp_ajax_nopriv_function_1', 'myfunctionname'); // non logged in user can make a call
function myfunctionname() {
global $wpdb;
$results = $wpdb->query( $wpdb->prepare("UPDATE 'my_table_name' SET `currentstatus` = 'myupdate1' WHERE ID = '1'"));
die($results);
}
ADDED TO FUNCTIONS FILE
wp_localize_script('myfunctionname', 'my_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
With the EDIT 1 in place, I also get an error - Notice: wp_localize_script was called incorrectly. Scripts and styles should not be registered or enqueued until the wp_enqueue_scripts, admin_enqueue_scripts, or login_enqueue_scripts hooks. This notice was triggered by the wait list_update handle. Please see Debugging in WordPress for more information. www.xyz.com/wp-includes/functions.php on line 5225 . I must have misunderstood something in the suggestion.
EDIT 2 Got everything else working but the button doesnt seem to update anything.
PHP from functions file -
function my_scripts() {
wp_enqueue_script( 'waitlist_update_call', get_template_directory_uri().'/assets/js/waitlist_update_call.js', array('jquery'), null, true );
wp_localize_script('waitlist_update_call', 'my_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
echo getcwd();
//calls Waitinglist data and creates table
}
add_action('wp_enqueue_scripts', 'my_scripts');
add_action('wp_ajax_waitlist_update_function', 'waitlist_update_function'); // logged in user can make a call
function waitlist_update_function() {
global $wpdb;
$results = $wpdb->query( $wpdb->prepare("UPDATE 'mytablename' SET `currentstatus` =
'myupdate1' WHERE ID = '1'"));
die($results);
}
JS
// JavaScript Document
function update() {
jQuery.ajax({
type: 'post',
url: my_ajax.ajax_url,
// add your action inside data object
data: {
action: 'waitlist_update_function'
},
success: function(data){
// callback function
}
});
}
HTML
Go!

The issue should be with the URL, it must be absolute I think.
jQuery.ajax({
//....
url: 'http://yourwebsite.com/wp-content/themes/yummy/update-waitlist.php'
// ...
The WordPress way
You must enqueue your JS file script.js before with same handle
and then localize after it
Localize the script to pass generic data. We will pass the ajax_url with my_ajax object.
functions.php
wp_localize_script('your-script-handle', 'my_ajax', array('ajax_url' => admin_url('admin-ajax.php')));
Then in your script file, you can use the my_ajax object to get the AJAX URL. Define a action function_1 which will be executed when this AJAX call is requested.
script.js
jQuery.ajax({
type: 'post',
url: my_ajax.ajax_url,
data: {
action: 'function_1',
}
success: function(data){
// callback function
}
});
Define a function and attach it with Ajax action that will query the database & returns the result.
functions.php
add_action('wp_ajax_function_1', 'function_to_execute_some_query'); // logged in user can make a call
add_action('wp_ajax_nopriv_function_1', 'function_to_execute_some_query'); // non logged in user can make a call
function function_to_execute_some_query() {
global $wpdb;
$results = $wpdb->query( $wpdb->prepare("UPDATE 'wp_wpdatatable_4' SET `currentstatus` =
'myupdate1' WHERE wdt_ID = '1'"));
die($results);
}

Related

How do I pass javascript variable to Ajax script?

In an html button I have this onclick event:
onclick='javascript:updateStatus(59)'
Then I have this function
function updateStatus(){
$.ajax({
type: 'post',
url: '/update-status.php',
success: function(data){
// callback function
}
});
return false;
}
And this is update-status.php
$sql = "UPDATE requests SET status='Closed' WHERE requestid=$requestid";
$updatestatus = mysqli_query($con, $sql);
if (!$updatestatus) {
die("Database query failed: " . mysqli_error($con));
} else {
return "success!";
}
Ultimately, I want the number from the original onclick event (in this example it's 59, but could be any number) to get passed into the $requestid variable in update-status.php.
What is the best/proper way to accomplish this?
Figured out to use "data" in the function after more googling, sorry.
Since you are using the JQuery AJAX function, just use another parameter in the configuration object, data. You're also missing an argument for the function.
function updateStatus(i){
$.ajax({
type: 'post',
data: 'requestid='+i,
url: '/update-status.php',
success: function(data){
// callback function
}
});
return false;
}
You could also create a map and send the map, like so
...
data: {"requestid" : i},
...
You're server side code should be updated though. You don't want to be using input from the client without first sanitizing it. This opens up the threat for SQL Injection attacks.
for example, what if the value of requestid is
1 or '1'='1' --
or
1; drop table requests
First, take the passed in argument in your javascript function and send it to your PHP script like this:
function updateStatus(id){
$.ajax({
type: 'post',
url: '/update-status.php',
data: {id: id},
success: function(data){
}
});
return false;
}
In your PHP access it through $_POST['id']. However, make sure you escape the value to prevent SQL injection attacks.
$requestid = $_POST['id'];

some precision about the success function of a ajax call

I'm creating a wordpress plugin and I use the wp_ajax_[your action] callback. In my code the php return nothing to the javascript (no echo, no return). If the php return no value, the 'data' in 'success: function(data)' is empty so why the 'click' trigger work?
the js:
$(document).one('click', '#publish', function (event) {
event.preventDefault();
jQuery.ajax({
type:"post",
url: ajaxurl,
data: {action: 'save_img_data', imgUrlsArray: iUrlsArray, imgNamesArray: iNamesArray, pid: pl_vars.post_id},
success: function(data) {
$('#publish').trigger( "click" );
}
});
});
the php:
function lmg29_img_data() {
$pid = $_POST['pid'];
$iUrlsArray = $_POST['imgUrlsArray'];
$iNamesArray = $_POST['imgNamesArray'];
if (isset($iUrlsArray) and isset($iNamesArray)) {
update_post_meta( $pid, 'lg29_urls', $iUrlsArray );
update_post_meta( $pid, 'lg29_names', $iNamesArray );
die();
}
}
add_action("wp_ajax_save_img_data", "lmg29_img_data");
as you can see there's no response:
The HTTP response code is 200, so it's considered a successful request. Actual data in the response is not required.
And, to be clear, functions in JS don't have mandatory arguments. There's no error if you call a function with arguments in its' declaration without any arguments provided.
A failure occurs if the response code is, for example, 400-something or 500-something. Like 404 or 503. https://en.wikipedia.org/wiki/List_of_HTTP_status_codes
To see how to set a response code read this:
http://php.net/manual/en/function.http-response-code.php
if you make a POST request, there is no data in success.
$.ajax({
url: "/post/url.php",
type: "POST",
data: parameters,
success: successFunction /*no data argument*/,
error: errorFunction
});
Therefore, success is "called" (and your trigger happens) but data means nothing.

Class Yii is not found when posting a variable with ajax

I want to get a variable from ajax to php. I'm using the Yii framework.
So my problem is, when I want to transfer a variable from ajax to a php script I get this error:
Fatal error: Class 'Yii' not found in
/var/www/vhosts/adappter.de/comamos/protected/views/store/search_area.php
on line 44 store.js:1308:13
This is how my Ajax Call looks like
var selectedCuisine = [];
$( document ).on( "click", "#cuisines", function()
{
if ( $(this).is(':checked') )
{
selectedCuisine.push($(this).val());
}
// document.getElementById('cuisine-list').style.visibility='hidden';
$.ajax({
type: "GET",
url: "../protected/views/store/search_area.php",
data: {cuisine : selectedCuisine},
success: function(response){
console.log(response);
}
});
});
and this is my php script to line 44
<?php
if (!isset($_SESSION)) { session_start(); }
$_SESSION['search_type']='';
if (isset($_GET['s'])){
$_SESSION['kr_search_address']=$_GET['s'];
$_SESSION['search_type']='kr_search_address';
}
unset($_SESSION['kr_item']);
unset($_SESSION['kr_merchant_id']);
$marker=Yii::app()->functions->getOptionAdmin('map_marker');
if (!empty($marker)){
echo CHtml::hiddenField('map_marker',$marker);
}
?>
The jQuery call is only when I click on a checkbox. So the value of the selected box gets pushed in an array. I want to return the array to the php script.
When I'm loading the site, I don't get such an error. So I don't know why this error occurs.
You need to use controller with action. Not only view file. You try to call view file from web. But it is wrong, because all code in protected directory. All requests must processing from index file. In index file connected framework. Here a small example. Controller:
class SiteController extends Controller
public function actionTest()
{
//... example
echo CHtml::button('test');
}
js:
var selectedCuisine = [];
$( document ).on( "click", "#cuisines", function()
{
if ( $(this).is(':checked') )
{
selectedCuisine.push($(this).val());
}
// document.getElementById('cuisine-list').style.visibility='hidden';
$.ajax({
type: "GET",
url: "/site/test", // url for your action
data: {cuisine : selectedCuisine},
success: function(response){
console.log(response);
}
});
});

Update information in database using php

I'm quite new to programming, and im trying to update a certain column in a database using php and javascript.
The data base only has 2 columns, seatnums and status. Basically, i want the status to reset back to 1 if the status is currently 0. Could anybody point me in the right direction?
I have a class inside a div in my HTML:
<a class='two' href="javascript:databaseReset() ">Reset</a>
My javascript function (Part im struggling with):
function databaseReset();
$.ajax({
url: "dbreset.php",
type: "POST",
data: {
'seatnum': seatnum,
'status': '1'
},
success: function () {
alert("ok");
}
function over(id) {
selectedseat=$(id).attr('title');
$(id).attr('src','images/mine.gif');
$(id).attr('title', 'Available');
}
function out(id) {
$(id).attr('src','images/available.gif');
}
my php file:
<?php
include("dbconnect.php");
$query="UPDATE seats SET status=1 WHERE status=0";
$link = mysql_query($query);
if (!$link) {
die('error 2');
}
?>
I assume it was simply a typo, but your function call needs to wrap brackets around the ajax call:
function databaseReset(){ //<---*****Add these braces*****
$.ajax({
url: "dbreset.php",
type: "POST",
data: {
'seatnum': seatnum,
'status': '1'
},
success: function () {
alert("ok");
}
}; //<---*****Add these braces*******
your code seems to declare the function, but not assign its functionality
Also, the data section is unnecessary, as it is not used. In fact, since you are not posting data, you can use the "GET" method instead.
Beyond that your code looks good, can you please specify what the issue is?

Ajax Call inside JavaScripts using Yii Framework

I am trying to use ajax function inside javascript, but its not calling its goes to failure part,
JS code :
Yii::app()->clientScript->registerScript('my-event-listener',"
$('#dedup_id').change(function(data){
$.ajax({
type: 'POST',
url: '".$this->createUrl('CheckDedupField')."',
data: {crm_base_contact_id:1652},
success: function(msg){
alert('Sucess')
},
error: function(){
alert('failure');
}
});
});
");
My controller code :
public function actionCheckDedupField($id)
{
echo "Inside CheckDedup".var_dump($_POST);
}
Please anyone find out what mistake am doing here.
You have to call ajax url as
url: '".$this->createUrl('checkDedupField')."', // change C to c
In URL, controller function names will start with lower case.
as per the comment. you are calling controller function with wrong name.
Then For missing parameter, change as
data: {id:1652},

Categories