AJAX POST PHP NOT ACCEPTING? - javascript

I understand this has been asked multiple times but I am unsure why this isn't working!
<?php
if(isset($_POST['testingajax'])) {
echo "Received";
} else {
echo "Not received";
}
?>
<button onclick = 'sendAjax()'>click me</button>
<script>
function sendAjax() {
$.ajax({
type: 'POST',
url: 'test.php',
data: {
testingajax: 2
},
success: function(data) {
console.log("AJAX POST SENT");
},
error: function (jqXHR) {
handle.innerText = 'Error: ' + jqXHR.status;
}
});
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
This is what shows after clicking the button, it should say Received
I have tried changing the URL to http://localhost/TESTINGPLANNER/src/test.php and ./test.php but no luck. Also, I have changed testingajax: 2 to 'testingajax': 2. From the network screenshot it seems like AJAX it is working so I am not sure where the issue is.

Related

Delete all data from MySQL table with button

I am currently trying to implement a 'Delete' button that clears a MySQL table of all its data. I am finding it much more difficult than the submit button was.
Researched examples all show how to do it by a row, but I just have a single 'Delete' button. I believe I am currently way off, as I was trying to come up with a solution based on the submit Ajax function.
Currently:
HTML
<button class="myButton" id="delete" type="delete">DELETE</button>
JavaScript (This is where my hangup is I think)
function deleteMessage() {
$.ajax({
type: 'POST',
url: 'info_message.php',
async: false,
//data: ,
success: function(response) {
if (response == "success") {
successPopup("Successfully deleted message");
}
else {
alert("Unable to delete message. " + response);
}
}
});
}
PHP (or here???)
if (isset($_POST['deleteMessage'])) {
$message = $_POST['message'];
// Deletes all records in Announcement table
$query = "DELETE from Announcement";
if ($dbc->query($query) === FALSE) {
echo "Error: " . $query . "<br>" . $dbc->error;
}
else {
echo "success";
}
exit();
}
You looking for post data which you're not passing with your ajax call. Specifically you need to add deleteMessage and message which is the 2 post variables you are trying to read in your php script. Something like below
$.ajax({
type: 'POST',
url: 'info_message.php',
async: false,
data: { deleteMessage: true, message:"insert what message you want to pass" } ,
success: function(response) {
if (response == "success") {
successPopup("Successfully deleted message");
}
else {
alert("Unable to delete message. " + response);
}
}
});
}

Why ajax doesn't work on certain wordpress hooks?

I built an ajax function which works perfectly when i hook it to admin_head or admin_notices hooks but it doesn't work when i hook it to manage_posts_extra_tablenav hook, instead of doing the ajax call it just reload the page and the url of the opened page after page reload is
Request URL: http://localhost/wc/wp-admin/edit.php?s=&post_status=all&post_type=product&_wpnonce=c1a10340ac&_wp_http_referer=%2Fwc%2Fwp-admin%2Fedit.php%3Fs%26post_status%3Dall%26post_type%3Dproduct%26action%3D-1%26product_cat%26product_type%26stock_status%26paged%3D1%26action2%3D-1&action=-1&product_cat=&product_type=&stock_status=&paged=1&action2=-1
and that upper link do a 302 redirect to that link
http://localhost/wc/wp-admin/edit.php?s&post_status=all&post_type=product&action=-1&product_cat&product_type&stock_status&paged=1&action2=-1
This is my code, however both actions connected to the same function but the version on top works fine and the one on the other hook doesn't work, so i was wondering what is the reason and how to solve it?
add_action( 'manage_posts_extra_tablenav', 'apm_update_all_products_ajax' );
add_action('admin_notices', 'apm_update_all_products_ajax');
function apm_update_all_products_ajax() {
$product_ids = wc_get_products( array( 'return' => 'ids', 'limit' => -1 ) );
?>
<div class="apm_bulk_update_prices_wrap alignleft actions">
<button class="button apm_update_prices" id="update_prices" onclick="apm_update_all_products()">Update All Products</button>
<p id="apm_bulk_status">test</p>
</div>
<script type="text/javascript" >
product_ids = <?php echo json_encode($product_ids); ?>;
product_ids_n = product_ids.length;
product_ids_step = 0;
function apm_update_all_products() {
product_id = product_ids[product_ids_step];
$.ajax({
type: "POST",
url: ajaxurl,
dataType: "JSON",
data: {
action: 'apm_update_single_product',
postId: product_id
},
success: function(lookup_data) {
product_ids_step++
$('#bulk_status').text('Updated ' + product_ids_step + ' of ' + product_ids_n );
if (product_ids_step < product_ids_n) {
apm_update_all_products();
}
},
error: function(jqXHR, textStatus, errorThrown) {
}
})
};
</script>
<?php
}
and here is a screenshot showing the place of the 2 hooks
https://snag.gy/zNXUmv.jpg

AJAX showing error message

I have one form ,when i click submit button am saving those values and on button click am calling "SaveData() " method.
So when i try to add data and click on submit button and nothing is happening am getting following errors in my browser log.
My onclick function code
function requestReferral() {
var nameperson = $("#namefield").val();
var contact1 = $("#contact").val();
//Till this part working i mean alert is printing .
$.ajax({
url: '/mycontroller/myfunction',
data: 'name='+nameperson+'&contact='+contact1,
type: 'post',
success: function(result){
data = jQuery.parseJSON(result);
if(data.result == "SUCCESS"){
clearMyFormData();
} else {
showMessage();
}
}
});
}
my error is
Failed to load resource: the server responded with a status of 500 (Internal Server Error) with my controller url www.example.com/mycontroller/myfunction
First of all, check if your url is ok, for example, if you are using php with codeigniter your url need to be like this:
url: <?php echo base_url()?>mycontroller/myfunction
and second, when I used ajax, I send data like this
postData = {
name: nameperson,
contact: contact1
}
$.ajax({
url: '/mycontroller/myfunction',
data: postData
type: 'post',
success: function(result){
data = jQuery.parseJSON(result);
if(data.result == "SUCCESS"){
clearMyFormData();
} else {
showMessage();
}
}

$this->request->is('ajax') always false

I have the code in my view but on sending to my controller action via ajax(as shown in the last part of the add.ctp)
//add.ctp
<?php
echo $this->Form->create('Poll',array('action' => 'index'));
echo $this->Form->input('one', array('id'=>'name'));
echo $this->Form->input('two', array('id'=>'email'));
echo $this->Form->input('three', array('id'=>'message'));
echo $this->Form->input('four', array('id'=>'four'));
echo $this->Js->submit('Send', array('id' => 'btn'), array(
'before'=>$this->Js->get('#sending')->effect('fadeIn'),
'success'=>$this->Js->get('#sending')->effect('fadeOut'),
'update'=>'#success'
));
echo $this->Form->end();
?>
<div id="sending" style="display: none; background-color: lightgreen;">Sending...</div>
<script>
$('#btn').click(function(event) {
form = $("#PollIndexForm").serialize();
// console.log(form);
$.ajax({
type: "POST",
url: 'pollsController/index';,
data: form,
success: function(data){
//
}
});
event.preventDefault();
// return false; //stop the actual form post !important!
});
</script>
on getting to my controller, I made an isAjax request test and if failed
public $components = array('RequestHandler');
public function index(){
$this->autoRender = false;
if($this->RequestHandler->isAjax()){
echo debug('Ajax call');
}
if(!empty($this->data)){
echo debug('not empty');
}
}
I get 'not empty' every time i tried to run this and $this->request->is('ajax') is always false
My version of cakephp is 2.3 and I have tried $this->request->is('ajax') and all that.
I'll appreciate if someone can point out what I am missing out
In your code, you have
if($this->RequestHandler->isAjax()){
Try to make the condition this way:
if ($this->request->is('ajax')) {
}
http://book.cakephp.org/2.0/en/appendices/2-0-migration-guide.html?highlight=isajax#requesthandlercomponent
RequestHandlerComponent: Many of RequestHandlerComponent’s methods are
just proxies for CakeRequest methods. The following methods have been
deprecated and will be removed in future versions: isSsl() isAjax()
isPost() isPut() isFlash() isDelete() getReferer()getClientIp()
Are you sending with your AJAX call the right headers?
{ 'X-Requested-With': 'XMLHttpRequest'}
If you are using jQuery, you can use:
$.ajaxSetup({
headers: { 'X-Requested-With': 'XMLHttpRequest' }
})
You can check it in Chrome developer tools under the network tab, where you must select your request.
and here is the documentation for ajaxSetup()
EDIT:
You can put it here:
<script>
$('#btn').click(function(event) {
form = $("#PollIndexForm").serialize();
$.ajaxSetup({
headers: { 'X-Requested-With': 'XMLHttpRequest' }
})
$.ajax({
type: "POST",
url: 'pollsController/index';,
data: form,
success: function(data){
}
});
event.preventDefault();
// return false; //stop the actual form post !important!
});
</script>

Empty $_POST when posting from jquery.ajax

I am doing some Add, Edit, and Delete for my project in school. The codes in the add module went well, in fact I've added few records. Then, here comes the Edit module, at first it was quite good, similar codes was used from the add module. But as I try and try, the post in the edit module was empty.
here's my edit codes:
$(".careersEdit").click(function () {
var careersTableSelect = encodeURIComponent($("input:radio[name=careersTableSelect]:checked").val());
if (careersTableSelect > 0) {
$(".careersEditForm_load").show();
$(".careersEditForm_error").hide();
$(".careersEditForm").hide();
var dataStringCareersEdit = 'careersTableSelect=' + careersTableSelect;
$.ajax({
type: "POST",
url: "admin/careers/process/careersEditGet.php",
data: dataStringCareersEdit,
beforeSend: function(){
alert(dataStringCareersEdit);
},
success: function () {
setTimeout("", 5000);
fetchResult();
},
error: function () {
alert("Post Error");
}
});
function fetchResult() {
$.ajax({
url: "admin/careers/process/careersEditGet.php",
type: "POST",
dataType: "json",
success: function (result) {
if (result) {
$("input#careersEditPosition").val(result['position']);
$("input#careersEditCompany").val(result['company']);
$("input#careersEditLocation").val(result['location']);
$(".careersEditForm_load").hide();
$(".careersEditForm").show();
}
},
error: function () {
alert("Fetch Error");
}
});
}
} else {
$(".careersEditForm").hide();
$(".careersEditForm_load").hide();
$(".careersEditForm_error").show();
}
});
Here's the careersEditGet.php:
<?php
include('connect.php');
error_reporting(0);
$careersTableSelect = $_POST['careersTableSelect'];
//$careersTableSelect = $careersTableSelect + 1;
//echo $careersTableSelect;
$query = "SELECT * FROM atsdatabase.admincareers WHERE refNum ='" . $careersTableSelect . "' LIMIT 0 , 30";
$runQuery = mysql_query($query);
if (!$runQuery) {
die('Could not enter data: ' . mysql_error());
}
$result = mysql_fetch_row($runQuery);
$array = array(
'position' => "" . $result[1] . "",
'company' => "" . $result[2] . "",
'location' => "" . $result[3] . "",
);
echo json_encode($array);
mysql_close($connection);
?>
Yes, the code is ugly/wrong/crap, I'm quite new to jquery stuffs, about 3-4 days. To those that will help, please do correct me. I wanna learn this jquery ajax stuff. Gracias
Maybe try passing data in more common way:
change
data: dataStringCareersEdit,
to
data: { "careersTableSelect" : careersTableSelect },
Call your ajax function once like,
$.ajax({
url: "admin/careers/process/careersEditGet.php",
type: "POST",
dataType: "json",
data: {careersTableSelect: careersTableSelect},
success: function (result) {
if (result) {
$("input#careersEditPosition").val(result.position);// json not array
$("input#careersEditCompany").val(result.company);// json not array
$("input#careersEditLocation").val(result.location);// json not array
$(".careersEditForm_load").hide();
$(".careersEditForm").show();
}
},
error: function () {
alert("Fetch Error");
}
});
Thanks guys for all the effort to answer this question, I've consulted to a friend who's a web developer, taught me how to properly use ajax in jquery. ;)
You are doing something fundamentally wrong when u are posting Data from jQuery.Ajax..
The data should be an object and the key should be the name of the server side POST variable which will be used later in the PHP ...
Example :
data : {"server_side_vriable" : "Your_data_to_Post" }
......
var dataStringCareersEdit = 'careersTableSelect=' + careersTableSelect + "&careersTableSelect=" + careersTableSelect;
$.ajax({
type: "POST",
url: "admin/careers/process/careersEditGet.php",
data: {"careersTableSelect" : dataStringCareersEdit},
beforeSend: alert(dataStringCareersEdit),
success: function () {
alert("Fetching Result");
setTimeout("", 3000);
$.ajax({
url: "admin/careers/process/careersEditGet.php",
type: "GET",
dataType: "json",
success: function (result) {
if (result) {
$("input#careersEditPosition").val(result['position']);
$("input#careersEditCompany").val(result['company']);
$("input#careersEditLocation").val(result['location']);
$(".careersEditForm_load").hide();
$(".careersEditForm").show();
}
},
error: function () {
alert("Fetch Error");
}
});
},
error: function () {
alert("Post Error");
}
});

Categories

Resources