I'm working on this ajax request with CodeIgniter 3. What I'm doing is press on checkbox and the event calls the function changVisib(). as you will see in the snippet, everything goes well because alert() is called.
But $.ajax() call is completely ignored. I tried $.post(). but no response.
I have searched the web for similar issues, but mine seems different. That's why I'm obliged to ask.
function changVisib(elem, picId) {
if (elem.type === 'checkbox') {
var cva = 0;
if (elem.checked) {
cva = 1;
} else {
cva = 0;
}
alert('ok up to here');
$.ajax({
type: "POST",
url: "<?php echo base_url()?>admin/gallery_update",
data: {id: picId, shown: cva},
dataType: "json"
});
}
}
Other jQuery functions work perfectly well. But the call to ajax, post, get seems not to work.
You need to add a success handler so that you know that the ajax request finished
function changVisib(elem, picId) {
if (elem.type === 'checkbox') {
var cva = 0;
if (elem.checked) {
cva = 1;
} else {
cva = 0;
}
alert('ok up to here');
$.ajax({
type: "POST",
url: "<?php echo base_url()?>admin/gallery_update",
data: {id: picId, shown: cva},
dataType: "json",
success: function(data){
alert( "success" );
}
});
}
}
data - the return data from the ajax request
Read more about the ajax jquery method here
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration#for...in_statement
I just discovered where the issue was. ajax queries were ignored because I was using the slim version of jQuery.
I have come to learn that jquery-3.5.1.slim.min.js does not include ajax and effects, according to https://jquery.com/download/.
Related
i am creating two ajax functions one in the traditional method and one with jquery. but when i do this the traditional method gets called first and in return i dont get some of my desired outcomes. how can i make the traditional ajax method to be translated into jquery?
here is my traditional ajax method:
function countFollowers() {
var xmlHttp = GetXmlHttpObject();
var url = "checkFollowers.php?username=" + document.followForm.follow_id.value;
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var r = xmlHttp.responseText.trim();
if (r != "error") {
document.getElementById('followersCount').innerHTML = xmlHttp.responseText;
error = true;
return false;
}
}
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
if (error == true) {
return false;
}
}
here is my jquery ajax:
jQuery(document).ready(function($) {
$('.msg-icon').on('click', function(e) {
e.preventDefault(); //prevent a normal postback and allow ajax to run instead
var follow_id = $(this).find('input[name="follow_id"]').val();
$.ajax({
data: follow_id,
type: "post",
url: "followingsystem.php?follow=" + follow_id,
success: function(data) {
}
});
});
});
here is what i come up with so far to make the two ajax functions in the same on click function:
jQuery(document).ready(function($){
$('.msg-icon').on('click', function(e){
e.preventDefault(); //prevent a normal postback and allow ajax to run instead
var follow_id = $(this).find('input[name="follow_id"]').val();
$.ajax({
data: follow_id,
type: "post",
url: "followingsystem.php?follow="+follow_id,
success: function(data) {
}
});
$.ajax({
data: follow_id,
type: "post",
url: "checkFollowers.php?username="+follow_id,
success: function(data) {
}
});
});
});
but it is still not executing the response text that is coming from my php file
php code:
<?php
include("functions.php");
include("session.php");
require("connection.php");
if(isset($_GET['username'])){
$username =$_GET['username'];
$result= $db->prepare("SELECT * FROM users WHERE username=?");
$result->bindValue(1,$username);
$result->execute();
$row = $result->fetch();
if($result){
echo "Followers </br>". $row["followers_count"];
}
else{
echo "error";
}
}
?>
how will i get it to echo the $row["followers_count"] inside my span element?
You said in the comments you wanted to run the two requests sequentially instead of in parallel. Here's an all-round better way to organise your code which both allows that, and makes the code more re-usable, more maintainable and testable, and easier to understand in general.
I've used the Promise/Deferred interface provided by jQuery and AJAX as the way to chain the requests in sequence. Notice how each call is separated into each own function (so it's re-usable), but that function returns the Deferred object from the AJAX request, so you can use it to do something else when the request finishes.
Also based on your PHP I think the call to checkfollowers needs to be a GET (because PHP checks $_GET for the input value, and that's what your original XHR call was), and also you need to set the data with an explicit "username" parameter name so it'll be recognised.
It's not clear whether your call to followingsystem.php is correct or not because I can't see the PHP code for it.
jQuery(document).ready(function($) {
$('.msg-icon').on('click', function(e) {
e.preventDefault(); //prevent a normal postback and allow ajax to run instead
var follow_id = $(this).find('input[name="follow_id"]').val();
var request = follow(follow_id); //run the initial request, get back the Deferred object representing that request.
request.done(function() { //when the first request is done, run the second one.
checkFollowers(follow_id);
});
});
});
function follow(follow_id) {
return $.ajax({
data: { follow: follow_id},
type: "post",
url: "followingsystem.php?follow=" + follow_id
});
}
function checkFollowers(follow_id) {
return $.ajax({
data: { username: follow_id },
type: "get",
url: "checkFollowers.php",
success: function(data) {
document.getElementById('followersCount').innerHTML = data;
}
});
}
I run the PHP code by ajax method with the click of a button.
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
}
});
});
I would like the file.php to be able to run the js code, for example:
if ($time < $_SESSION['time']) {
[...]
}
else {
echo '<script>alert("lol");</script>';
}
And that when the button .btn_ranking on the page is pressed, an 'lol' alert will be displayed. If it is possible?
you can echo a response to the AJAX call and then run the JS according to the response..
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time },
success: function (data) {
if(data==1){
//do this
}else if(data==2){
//do that
alert('LOOL');
}
}
});
});
PHP CODE:
if ($time < $_SESSION['time']) {
echo '1';
}
else {
echo '2';
}
You can't said to a server-side script to use javascript.
What you have to do is to handle the return of you'r ajax and ask to you'r front-side script to alert it. Something like that :
file.php :
if ($time < $_SESSION['time']) {
[...]
}
else {
echo 'lol';
exit();
}
Front-side :
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: {
name: name,
time: time
},
success : function(data) {
alert(data);
}
});
});
When you used ajax for call php script, everything will be print in the return of the php code will be return to the HTTP repsonse and so be on the Ajax return function as params.
Ok .. First change your js code to handle answer from php script:
$(".btn_ranking").one('click', function(e) {
e.preventDefault();
var name = localStorage.getItem('name');
var time = localStorage.getItem('timer_end');
$.ajax({
url: "php/file.php",
method: "POST",
data: { name: name, time: time }
success: function(data) {
console.log(data);
// check if it is true/false, show up alert
}
});
});
Then change php script (file.php), something like that:
$response = [];
if ($time < $_SESSION['time']) {
$response['data'] = false;
}
else {
$response['data'] = true;
}
return json_encode($response);
Something like that is the idea :) When u send ajax with POST method get variables from there, not from $_SESSION :)
U can see good example here
Bear with me I'm my javascript is a little rusty. So I'm trying to use a call by ajax to a PHP file and give it a plan type then make sense of it check to see if it then return a true or false if some allowed slots are less than some slots used up for the plan. Here is the Form in XHTML.
<form method="post" action="/membership-change-success" id="PaymentForm">
<input type="hidden" name="planChosen" id="planChosen" value="" />
</form>
On the same file. The ( < PLAN CHOICE > ) gets parsed out to the current plan.
<script>
var hash = window.location.hash;
var currentPlan = "( < PLAN CHOICE > )";
$(".planChoice").click(function(event){
var isGood=confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: function (data) { //This is what is not working I can't get it to return true
success = data;
}
});
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
});
My PHP for the ajax response looks like this.
<?php
require ('../includes/common.php');
include_once ('../includes/db-common.php');
require ('../includes/config.php');
$membership = new membership($dbobject);
$listing = new listing($dbobject);
$totalAvailableListings = ($membership->get_listingsAmount($_POST['plan']));
if($totalAvailableListings>=$listing->get_active_listings($user->id)){
echo json_encode(true); // I've tried with out jason_encode too
} else {
echo json_encode(false);
}
And that's pretty much it if you have any suggestions please let me know.
So I've tried to do it another way.
$(".planChoice").click(function (event) {
var isGood = confirm('Are you sure you want to change your plan?');
var success;
$("#planChosen").val($(this).data("plan"));
if (false) {
if (isGood) {
$("#PaymentForm").submit();
alert('you did it');
}
} else {
alert(isSuccessful($(this).data("plan")));
//alert('Please make sure you deactivate your listings to the appropriate amount before you downgrade.');
}
});
and I have an ajax function
function isSuccessful(plan) {
return $.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: plan}
});
}
The alert tells me this [object XMLHttpRequest]
any suggestions?
$.ajax() returns results asynchronously. Use .then() chained to $.ajax() call to perform task based on response
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: {plan: $(this).data("plan")}
})
.then(function(success) {
if (success) {
$("#PaymentForm").submit();
}
// if `form` is submitted why do we need to set `.location`?
// window.location = '/membership-change-success';
} else {
alert('Please make sure you deactivate your listings to the appropriate amount before you Downgrade.')
}
}, function err(jqxhr, textStatus, errorThrown) {
console.log(errorThrow)
})
You should use the following form for your ajax call
$.ajax({
url: '/ajax/planCheck.php',
type: "POST",
dataType: 'json',
data: ({plan: $(this).data("plan")}),
success: success = data
})
.done(function(response) {
if(success) {
if (isGood) {
$("#PaymentForm").submit();
}
window.location = '/membership-change-success';
}
else {
alert('Please make sure you deactivate your listings to the
appropriate amount before you Downgrade.')
}
});
the .done() clause ensures that you perform that code after the ajax call is finished and the response is obtained.
Ajax code
$("#login_btn").click(function() {
var url = "core/login.php";
$.ajax({
type: "POST",
url: url,
data: $("#sr").serialize(),
success: function(data) {
var responseData = jQuery.parseJSON(data);
$('.oops').html('<div class="error">'+responseData.oops+'</div>');
alert(responseData.good);
if(responseData.good === 1) {
alert(good)
location.reload();
}
}
});
});
Php code if everything passes
else {
$_SESSION['id'] = $login;
$good = 1;
exit();
}
How come it's not freshing the page with location.reload? Should I be using .done .try?
Dont refresh, the whole idea of using ajax is that you dont need to.
You can set your sessions in the ajax php script and pull new content based on the change in session.
That being said, you are missing a ';' at
alert(good);
So I have this JavaScript which works fine up to the $.ajax({. Then it just hangs on the loader and nothing happens.
$(function() {
$('.com_submit').click(function() {
var comment = $("#comment").val();
var user_id = $("#user_id").val();
var perma_id = $("#perma_id").val();
var dataString = 'comment='+ comment + '&user_id='+ user_id + '&perma_id=' + perma_id;
if(comment=='') {
alert('Please Give Valid Details');
}
else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax-loader.gif" />Loading Comment...');
$.ajax({
type: "POST",
url: "commentajax.php",
data: dataString,
cache: false,
success: function(html){
alert('This works');
$("ol#update").append(html);
$("ol#update li:first").fadeIn("slow");
$("#flash").hide();
}
});
}
return false;
});
});
Try replacing:
var dataString = 'comment='+ comment + '&user_id='+ user_id + '&perma_id=' + perma_id;
with:
var dataString = { comment: comment, user_id: user_id, perma_id: perma_id };
in order to ensure that the parameters that you are sending to the server are properly encoded. Also make sure that the commentajax.php script that you are calling works fine and it doesn't throw some error in which case the success handler won't be executed and the loader indicator won't be hidden. Actually the best way to hide the loading indicator is to use the complete event, not the success. The complete event is triggered even in the case of an exception.
Also use a javascript debugging tool such as FireBug to see what exactly happens under the covers. It will allow you to see the actual AJAX request and what does the the server respond. It will also tell you if you have javascript errors and so on: you know, the kinda useful stuff when you are doing javascript enabled web development.