Ajax sometimes works with post and sometimes works with get - php

I know this may look strange but it happened to me many times.
I'm building a website, and everytime I use ajax, i choose POST as method, and to call datas in php file I use $_POST.
At first it works... but after a few days, all scripts using ajax don't work anymore, then I tried to remplace $_POST to $_GET, but ajax method is still always POST.
and after some days again scripts don't work and i remplace get to post... I don't want to get these errors again so I want to know why i had to remplace those methodes in php files.
this is example of the JS code
$(".add-category").click(function(e) {
e.preventDefault();
var $this = $(this);
$(".cats").append('<div class="load" style="margin:auto"><i class="fa fa-spinner fa-spin"></i></div>');
$.ajax({
method : "POST",
url : $this.data("url"),
data : {
cat : $this.prev().val()
},
success : function(data){
$('.load').remove();
$(".cats").append(data);
}
});
});
and this is its php file
<?php
require_once "../../core/Database.php";
require_once "../../core/functions.php";
Database::connect();
if(isset($_GET["cat"]) && strlen($_GET["cat"]) > 0 ){
Database::query("INSERT INTO categories(title_category) VALUES(?)",[$_GET["cat"]]);
$req = Database::query("SELECT * FROM categories ORDER BY id_category DESC");
$cat = $req->fetch();
echo '
<div class="gray cat">'.$cat->title_category.'
<i class="fa fa-trash"></i>
</div>
';
}
Thanks

Related

AJAX Call Return PHP Value Empty

i have a problem about ajax call, i dont get what exactly why i still getting this empty success call. i tried the past solution to solve this but i don't know what the cause of this.
as you can see this my table then when i click the action of update, delete, or, add, even print_r($_POST) it's still empty.
then when i go to console i got this error.
the value of selected attr still send to the php file
heres my code :
$(document).on('click', '.update', function(){
var user_ID = $(this).attr('id');
$.ajax({
url:"datatable/account/fetch_single.php",
method:"POST",
data:{user_ID:user_ID},
dataType:"json",
success:function(data)
{
console.log(data);
$('#account_modal').modal('show');
$('#username').prop("disabled", true);
$('#username').val(data.user_Name);
$('#email').val(data.user_Email);
$('#pass').val(data.user_Pass);
$('#con_pass').val(data.user_Pass);
$('#level').val(data.level_ID).change();
$('#status').val(data.user_status).change();
$('#action').val('Edit');
$('#operation').val('Edit');
$('.modal-title').text('Edit Account Info');
$('#user_ID').val(user_ID);
}
})
});
fetch_single.php
include('db.php');
include('function.php');
if(isset($_POST["user_ID"]))
{
$output = array();
$statement = $conn->prepare(
"SELECT * FROM `user_accounts`
WHERE user_ID = '".$_POST["user_ID"]."'
LIMIT 1"
);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output["level_ID"] = $row["level_ID"];
$output["user_Name"] = $row["user_Name"];
$output["user_Pass"] = decryptIt($row["user_Pass"]);
$output["user_Email"] = $row["user_Email"];
$output["user_status"] = $row["user_status"];
}
echo json_encode($output);
}
or it's might be the cause of problem is the design template?
i solve this issue, in my requested php file i change my $_POST to $_REQUEST if your data in ajax look like
data:{user_ID:user_ID}
or
data: "fname="+fname+"&lname="+lname
this might work for you, then if your data look like this data:new FormData(this) maybe you should use this type
data:{user_ID:user_ID}
to work the request and execute your sql.
but the best solution i got is change your
method:"POST"
to
type:"POST"
to solve this problem.
if your data.success_variable is undefined add
header('Content-type: application/json.');
to your requested php file.
Related topic:
ppumkin5 answer to
JQuery Ajax is sending GET instead of POST

User Login With PHP PDO and AJAX

I have a form in a popup modal that should be used for user login there are two input fields one for ID card number and second for password .. The collected data are sent by ajax to a php page called login.php that should check the user user entered data and create a session for it if he is active user and transfers him to home page and if he is not active user transfers him to student-registration page and if the entered data are wrong a paragraph within the form should give a notification to the user .. now there is nothing happening when I submit the form where did missed up !!
html strcture:
<div id="std-login-modal" class="modal">
<header class="modal-header">
<h3>تسجيل الدخول كطالب</h3>
<i class="fa fa-times modal-close"></i>
</header>
<div class="modal-body">
<form id="std-login-frm" method="POST">
<div>
<input type="text" id="std-card" name="stdID" autocomplete required>
<label>رقم القيد</label>
<i class="fa fa-exclamation"></i>
<div class="input-desc">
<span>هذا الحقل خاص بادخال رقم قيد الطالب المكون من سبعة أرقام</span>
</div>
</div>
<div>
<input type="password" id="std-pass" name="stdPass" required>
<label>كلمة المرور</label>
<i class="fa fa-exclamation"></i>
<div class="input-desc">
<span>هذا الحقل خاص بكلمة المرور الخاصة بالطالب</span>
</div>
</div>
<div>
<input type="submit" value="تسجيل دخول" name="stdLoginBtn">
<p id="std-login-error"></p>
</div>
</form>
</div>
<footer class="modal-footer">
<p>لا يوجد لديك حساب في الموقع؟ قم بانشاء واحد</p>
<button id="create-std-account" class="modal-second-btn">انشاء حساب</button>
</footer>
</div>
My jquery code:
$(document).ready(function(){
// Student Login Operation
$("#std-login-frm").submit(function(e){
e.prvenetDefault();
// Get Student Entered Data From The Inputs
var stdID = $("#std-card").val().trim();
var stdPass = $("#std-pass").val().trim();
// Call AJAX Method And Specify Its Parameters
$.ajax({
url: "login.php?type=student",
type: "POST",
data: {ID:stdID,Password:stdPass},
dataType:"json",
error: function(data){
$("#std-login-error").html(data.fail);
}
});
});
});
login.php code:
<?php
include'connect.php';
if(isset($_POST['stdLoginBtn']))
{
$type = '';
if(isset($_GET['type']))
{
$type = $_GET['type'];
if($type == 'student')
{
// Get Data Sent By AJAX POST Request
$ID = $_POST['ID'];
$pass = $_POST['Password'];
// Check if the user exist in database
$stmt = $con->prepare("select ID,password,status,name,phone,
token from students where ID=?");
$stmt->execute(array($ID));
$info=$stmt->fetch();
if(password_verify($pass,$info["password"]))
{
if($info["status"] == 1)
{
$_SESSION['stdID'] = $info["ID"];
header('Location:home.php');
exit();
}
else
{
$_SESSION['mobile'] = $info["phone"];
$_SESSION['token'] = $info["token"];
$_SESSION['name'] = $info["name"];
header('Location:student-registration.php');
exit();
}
}
else
{
$fail = "خطأ في البيانات يرجى إعادة المحاولة";
$data = array('error' => $fail);
echo json_encode($data);
}
}
}
}
?>
I also will provide the connection code to mysql:
<?php
$dsn='mysql:host=localhost;dbname=vcm';
$user='root';
$pass='';
$option=array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
);
try{
$con= new PDO($dsn,$user,$pass,$option);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e){
echo 'Failed to connect' . $e->getMessage();
}
?>
You need to invoke session_start(); in your php program before you output anything to a page that uses or sets any session variables. That allows them to be saved in the session manager, and feeds a cookie to your user's browser identifying the session. In subsequent web requests the user's browser passes along the session cookie.
Additionally, if your ajax request goes to a different domain than the one served by your page, you should include this in your ajax options.
xhrFields: {
withCredentials: true
}
Finally, the browser doesn't look at any Location: header returned in a response to an AJAX request (only in a page response). You need to process that header yourself in your Javascript code.
Something like this may do the trick for you:
success: function(data, text, request){
document.location.href = request.getResponseHeader('Location');
}
Putting it all together, your ajax request might look like this (not debugged).
// Call AJAX Method And Specify Its Parameters
$.ajax({
url: "login.php?type=student",
type: "POST",
data: {ID:stdID,Password:stdPass},
dataType:"json",
xhrFields: {
withCredentials: true
},
success: function(data, text, request){
var target = request.getResponseHeader('Location');
alert('About to redirect to ' + target);
document.location.href = target;
},
error: function(data){
$("#std-login-error").html(data.fail);
}
});
Edit You are trying to do something very hard, involving a lot of moving parts: html, Javascript, php, ajax, sql, and redirection. It's admirable that you want to figure out how to do this; you'll learn a lot. If you need to just finish this task, forget about the ajax and just post the login form to php.
If you want to get this working, you should open up the developer tools on your browser ( on PCs, right-click/inspect on any platform).
The Console tab shows you diagnostic information about your pages. You can put console.log(whatever); lines in your Javascript and they'll show up on the console.
In the Network tab you can see the requests to and responses from your php AJAX endpoints including the Location header values and cookie values.
The Source tab is a debugger. You can set breakpoints on lines of Javascript so you can see what's happening. Suggestion: set breakpoints on the first lines of the success: and error: functions.
You can get yourself a browser web extension like Edit This Cookie, to help you inspect the cookies fed to your browser by your ajax and GET/POST responses.
If you have a debugger server-side for your php, that will help too. There's far more to learn about this than can appear in a Stack Overflow answer.

Why can't I seem to get Ajax to communicate with my PHP $wpdb delete file

thank you for taking a look at my question which goes as follows:
I'm trying to delete a record in an MYSQL database when I click a link which in HTML looks like this:
<li><a class="msg-action-delete" href="#" data-msgid="<?php echo $mesage_posts->msg_id; ?>">delete</a></li>
I don't want the page to reload after clicking the button so I use Ajax:
$('.msg-action-delete').click(function(e){
e.preventDefault();
var wp_directory = directory_uri.stylesheet_directory_uri;
var msg_id = $(this).attr('data-msgid');
$.ajax({
url : wp_directory+'/modules/messaging/delete-messaging.php',
dataType : 'JSON',
type : 'POST',
data: {
'msg-id' : msg_id
},
success: function(data) {
console.log(data);
console.log(msg_id);
alert('ajax worked');
}
});
});
I'm using WordPress as a CMS which has a class $wpdb that helps out with interactions to the db, for the delete scripts is in a file called elete-messaging.php :
<?php
global $wpdb;
$current_user = wp_get_current_user();
$msgid = $_POST['msg-id'];
echo $msgid;
$table_name = $wpdb->prefix . 'wpeddit_msg';
$wpdb->delete($table_name, array('msg_id' => $msgid));
$wpdb->show_errors();
When I click the delete link it does nothing, no errors in console.
I would appreciate any help I can get on this, thanks!

CodeIgniter AJAX: POST not working, GET works fine

Fiddling inside CodeIgniter and trying to get a grip on it all as I've never worked with AJAX before.
For some reason, my AJAX is working perfectly when I use the GET method, but if I switch it over to the POST method, it stops working.
My JS:
$(document).ready(function(){
$('.love').click(function(event) {
$.ajax({
type: 'GET',
url: base_url + '/ajax/love_forum_post',
data: { post_id: 2, user_id: 1, ajax: 1 },
});
return false;
});
});
And my CONTROLLER:
function love_forum_post()
{
$post_id = $this->input->get('post_id');
$user_id = $this->input->get('user_id');
$is_ajax = $this->input->get('ajax');
if ($is_ajax)
{
$this->load->model('forums_model');
$this->forums_model->add_love($post_id, $user_id);
}
// If someone tries to access the AJAX function directly.
else
{
redirect('', 'location');
}
}
If I switch the type to 'POST' inside my JS and then catch it on the other end with $this->input->post() it doesn't work.
Any suggestions?
I have tested your code in 2 scenarios:
first - without csrf protection, and I see no reason for your code not to run properly.
To be able to test it easier, append $.ajax call with success response.
Something like this
success: function(response) {
alert(response);
}
And add response to your love_forum_post method.
echo print_r($this->input->post(), true);
This would give you clean view of what it going on in your method.
In my installation everything works just fine.
Second scenario is with csrf protection.
In this case add new param to your post object.
<?php if ($this->config->item('csrf_protection') === true) : ?>
post_data.<?php echo $this->security->get_csrf_token_name()?> = '<?php echo $this->security->get_csrf_hash()?>';
<?php endif ?>
This would make CI accept post from this url.
Hopefuly it would help.
Cheers
By any chance you have csrf_protection enabled?
If yes you need to send the token and the value key as post parameter along with post request.
Try to use this
$post_data = $_POST;
and print the post data using this
print_r($post_data);die();
and you can see there if you catch the post data;
Gudluck!!

Load PHP function with jQuery Ajax

I have a file which is loaded at the top of my document, which is called Videos.php. Inside that file are several functions, such as getYoutubeVideos. On some pages, I need to call upon that function several times (up to 50), and it of course creates major lag on load times. So I have been trying to figure out how to call that function in, only when it is need (when someone clicks the show videos button). I have very little experience with jQuery's ajax abilities. I would like the ajax call to be made inside of something like this:
jQuery('a[rel=VideoPreview1).click(function(){
jQuery ("a[rel=VideoPreview1]").hide();
jQuery ("a[rel=HideVideoPreview1]").show();
jQuery ("#VideoPreview1").show();
//AJAX STUFF HERE
preventDefault();
});
Ok I have created this based on the responses, but it is still not working:
jQuery Code:
jQuery(document).ready(function(){
jQuery("a[rel=VideoPreview5]").click(function(){
jQuery("a[rel=VideoPreview5]").hide();
jQuery("a[rel=HideVideoPreview5]").show();
jQuery.post("/Classes/Video.php", {action: "getYoutubeVideos",
artist: "Train", track: "Hey, Soul Sister"},
function(data){
jQuery("#VideoPreview5").html(data);
}, 'json');
jQuery("#VideoPreview5").show();
preventDefault();
});
jQuery("a[rel=HideVideoPreview5]").click(function(){
jQuery("a[rel=VideoPreview5]").show();
jQuery("a[rel=HideVideoPreview5]").hide();
jQuery("#VideoPreview5").hide();
preventDefault();
});
});
And the PHP code:
$Action = isset($_POST['action']);
$Artist = isset($_POST['artist']);
$Track = isset($_POST['track']);
if($Action == 'getYoutubeVideos')
{
echo 'where are the videos';
echo json_encode(getYoutubeVideos($Artist.' '.$Track, 1, 5, 'relevance'));
}
$.post('Videos.php', {
'action': 'getYoutubeVideos'
}, function(data) {
// do your stuff
}, 'json');
In your php code, do something like this:
$action = isset($_POST['action'])? $_POST['action'] : '';
if($action == 'getYoutubeVideos')
{
echo json_encode(getYoutubeVideos());
}
Then data in your JavaScript function will be the array/object/value returned by getYoutubeVideos().
I would do the JS part like ThiefMaster describes, but the php part would i handle a little bit different.
I would do something like this:
if(isset($_POST['action'], $_POST['par1'], $_POST['par2'])
{
$action = $_POST['action'];
$result = $this->$action($_POST['par1'], $_POST['par2]);
echo json_encode(result);
}
But be careful, if you have some methods in the class which shouldn't be called by the user, trough manipulating POST data, then you need some way to whitelist the methods the JavaScript may call. You can do it by prefixing the methods i.e:
$this->jsMethod.$action(....);
or by simple if/switch condition.
Ok here is what ended up working:
PHP CODE
$Action = isset($_POST['action']);
if($Action == 'getYoutubeVideos')
{
getYoutubeVideos($_POST['artist'].' '.$_POST['track'], 1, 5, 'relevance');
}
JQUERY
jQuery.ajax({
type: "POST",
url: "/Classes/Video.php",
data: "action=getYoutubeVideos&artist=artist&track=track",
success: function(data){
jQuery("#VideoPreview1").html(data);
}
});
json encoding was annoying, not sure if json is hte better way of doing it, I could actually use the jQuery.post function as well, because the real problem was with the PHP. If anyone knows about any security problems with the method I am doing, please let me know. Seems fine though.

Categories