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'];
Related
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);
}
I am trying to pass a JSON object that looks similar to this:
{"service": "AAS1", "sizeTypes":[{"id":"20HU", "value":"1.0"},{"id":"40FB","2.5"}]}
Just a note: In the sizeTypes, there are a total of about 58 items in the array.
When the user clicks the submit button, I need to be able to send the object to a PHP script to run an UPDATE query. Here is the javascript that should be sending the JSON to the PHP script:
$('#addNewSubmit').click(function()
{
var payload = {
name: $('#addservice').val();
sizeTypes: []
};
$('input.size_types[type=text]').each(function(){
payload.sizeTypes.push({
id: $(this).attr('id'),
value: $(this).val()
});
});
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {service: payload},
dataType: 'json',
success: function(msh){
console.log('success');
},
error: function(msg){
console.log('fail');
}
});
});
Using the above click function, I am trying to send the object over to php script below, which is in api/editService.php:
<?php
if(isset($_POST['service']))
{
$json = json_decode($_POST['service'], true);
echo $json["service"]["name"] . "<br />";
foreach ($json["service"]["sizeTypes"] as $key => $value){
echo $value["value"] . "<br />";
}
}
else
{
echo "Nooooooob";
}
?>
I do not have the UPDATE query in place yet because I am not even sure if I am passing the JSON correctly. In the javascript click function, you see the SUCCESS and ERROR functions. All I am producing is the ERROR function in Chrome's console.
I am not sure where the error lies, in the JavaScript or the PHP.
Why can I only produce the error function in the AJAX post?
Edit
I removed the dataType in the ajax call, and added JSON.stringify to data:
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {servce: JSON.stringify(payload)},
success: function(msg){
console.log('success');
},
error: function(msg){
console.log('fail'), msg);
}
});
In the PHP script, I tried this:
if(isset($_POST['service'))
{
$json = json_decode($_POST['service'], true);
foreach ($json["service"]["sizeTypes"] as $key => $value){
$insert = mysqli_query($dbc, "INSERT INTO table (COLUMN, COLUMN, COLUMN) VALUES (".$json["service"] . ", " . "$value["id"] . ", " . $value["value"]")");
}
}
else
{
echo "noooooob";
}
With this update, I am able to get the success message to fire, but that's pretty much it. I cannot get the query to run.
without seeing the error, I suspect the error is because ajax is expecting json (dataType: 'json',) but you are echoing html in your php
Try to change
error: function(msg){
console.log('fail');
}
to
error: function(msg){
console.log(msg);
}
There might be some php error or syntax issue and you should be able to see it there.
Also try to debug your php script step by step by adding something like
echo "still works";die;
on the beginning of php script and moving it down till it'll cause error, then you'll know where the error is.
Also if you're expecting JSON (and you are - dataType: 'json' in js , don't echo any HTML in your php.
As you are sending an object in your service key, you probably have a multi-dimensional array in $_POST['service'].
If you want to send a string, you should convert the object to json:
data: {service: JSON.stringify(payload)},
Now you can decode it like you are doing in php.
Also note that you can only send json back from php if you set the dataType to json. Anything other than valid json will have you end up in the error handler.
Example how to handle a JSON response from editService.php. Typically, the editService.php script will be the worker and will handle whatever it is you need done. It will (typically) send a simple response back to the success method (consider updating your $.ajax to use the latest methods, eg. $.done, etc). From there you handle the responses appropriately.
$.ajax({
method: 'POST',
url: '/api/editService.php',
data: { service: payload },
dataType: 'json'
})
.done(function(msh) {
if (msh.success) {
console.log('success');
}
else {
console.log('failed');
}
})
.fail(function(msg) {
console.log('fail');
});
Example /editService.php and how to work with JSON via $.ajax
<?php
$response = [];
if ( isset($_POST['service']) ) {
// do your stuff; DO NOT output (echo) anything here, this is simply logic
// ... do some more stuff
// if everything has satisfied, send response back
$response['success'] = true;
// else, if this logic fails, send that response back
$response['success'] = false;
}
else {
// initial condition failed
$response['success'] = false;
}
echo json_encode($response);
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?
I have the following code for requesting data from a mysql database:
jquery/javascript:
ajaxGet = function (url) {
var result = $.ajax({
url:url,
type:"POST",
data:{action:'call_this'},
dataType: 'json',
success:function(data) {
}
});
return result;
}
php:
<?php
if($_POST['action'] == 'call_this') {
// call waypoint search
include ('link.php');
$sql="SELECT * FROM Waypoints"; //data in table Waypoints
$result = mysqli_query($link,$sql);
$wptdata=array();
while($line = mysqli_fetch_assoc($result)){
$wptdata[] = $line;
};
mysqli_close($link);
echo json_encode($wptdata);
};
?>
To get the data as a javascript array, I would like to be able to say something like this:
wpdata=ajaxGet('datacall.php');
Suggestions on how to get this to work? If I put alert(data[0].name) within the success function, it comes up with the right result, so the call to the database table is definitely working. But I can't seem to figure out how to get the array out of the $.ajax call.
Thanks for any help- have been searching through other questions, and just came seem to find a solution. I would like to keep the ajaxGet function if at all possible- once I get it working, I will be able to update it so that it is flexible as to what kind of data are called from the table.
The answer is no. You cannot do this is any way that is sane. Use callbacks/promises - that's the way to go!
function ajaxGet(url) {
return $.ajax({
url: url,
type: "POST",
data: {
action: 'call_this'
},
dataType: 'json'
});
}
ajaxGet().done(function(wpdata) {
// use wpdata here
});
I am working with Concrete-5 CMS, I have an issue in passing value form view to controller.In my application I am using following code for displaying employee role.
foreach($rd as $data){
echo "<tr><td>".$data[role_name]."</td><td>".$data[role_description]."</td><td>Edit</td><td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td></tr>";
}
<input type="hidden" name="rno" id="rno" />
script:
$delConfirmJS = t('Are you sure you want to remove this Role?'); ?>
<script type="text/javascript">
function deleteRole(myvar) {
var role = document.getElementById('rno');
role.value = myvar;
if (confirm('<?php echo $delConfirmJS ?>')) {
$('#rolelist').submit();
//location.href = "<?php echo $this->url('/role/add_role/', 'delete', 'myvar')?>";
}
}
</script>
html code
I did edit operation by passing role_id through edit action. But, In case of delete i should ask for a conformation, so I use java script to conform it and call the href location and all.
But i don't know how to pass the role_id to script and pass to my controller. how to achieve this task?
thanks
Kumar
You can pass value to server using ajax calls.
See the following code. Here We use a confirm box to get user confirmation.
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm)
{
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}
In delete.php you can take the employee id by using $_POST['emp_id']
You can do it easily by using jquery
var dataString = 'any_variable='+ <?=$phpvariable?>;
$.ajax({
type: "POST",
url: "otherfile.php",
data: dataString,
success: function(msg){
// msg is return value of your otherfile.php
}
}); //END $.ajax
I would add an extra variable in to the delete link address. Preferrably the ID of the row that you need to be deleted.
I don't know Concrete-5 CMS. But, i am giving you the general idea
I think, you are using some button on which users can click if they want to delete role.
<td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td>
My suggestion,
add onClick to button
onClick="deleteEmployee(roleId);" // roleId - dynamic id of the role by looping over
Frankly speaking dude, i dont know how you will add this to your button that i guess there would surely be some way to simply add this to existing html.
And now, simply use Sajith's function
// Sajith's function here
function deleteEmployee(empId){
var confirm=confirm("Do you want to delete?");
if (confirm){
var url = "path/to/delete.php";
var data = "emp_id="+empId;
$.ajax({
type: "POST",
url: "otherfile.php",
data: data ,
success: function(){
alert("Employee deleted successfully.");
}
});
}
}