Here when I submit my form and will check validation in js file and then that will call the kickerLogin() function
Got alert message of datastring, then this is not send to my url which is mentioned in ajax but that will submit..........
function kickerLogin(){
alert('hello friends');
dataString=$('form[name=kickerLog]').serialize();
alert(dataString);
$.ajax({
type:"POST",
url:"<?php echo $GLOBALS['base_url']; ?>ajax/user-ajax.php?mode=kickerLogin",
cache: false,
data: dataString,
dataType: "json",
success: function(data) {
alert(data);
if(data.success == "yes")
{
$('#kickerLog').submit();
}
else if(data.success == "no")
{
if(data.status=="emailfail"){
$('li.log_error').show();
$('li.log_error').html("Email id not verified");
}
else if(data.status=="rejected"){
alert("Your account is inactive by admin");
}
else{
$('li.log_error').show();
$('li.log_error').html("Invalid Email / Password");
$("#loginEmail").css("border","1px solid red");
$("#loginPassword").css("border","1px solid red");
}
}
else {
alert(" Occured internal Error.please check network connection" );
}
}
});
}
You can't use <?php echo $GLOBALS['base_url']; ?> in your js file. Include this in your view may work then. Instead of <?php echo $GLOBALS['base_url']; ?> use <?=base_url()?> in your view.
If your js function kickerLogin() is in a js file you can't use '',
Pass your url as one parameter while calling kickerLogin() function
It is not recommended to call external files in CI.
//Instead of this
url:"<?php echo $GLOBALS['base_url']; ?>ajax/user-ajax.php?mode=kickerLogin",
//Use this
//Where ajax is a controller ajax.php user_ajax is a function in it.
url:"<?php echo site_url();?>/ajax/user_ajax?mode=kickerLogin",
//ajax.php controller
function user_ajax(){
$data['mode'] = $this->input->get('mode');
//Here load the file
$this->load->view('user-ajax');
}
Related
So I am trying to build a single page application using PHP and AJAX but I am having some issues with my navigation.
I have a file controller.php that controls the page to be displayed. The code that handles a post request is as follows
EDIT: Forgot to mention that echoing $_POST['page'] shows nothing
if(!isset($_POST['page'])){
include('Pages/landing_page.php');
echo "empty";
}
else{
echo $_POST['page'];
if($_POST['page'] == 'landing_page'){
include('Pages/landing_page.php');
}
if($_POST['page'] == 'forum'){
include('Pages/forum.php');
echo "forum hit";
}
}
The post request is generated with $.ajax function as follows
$(document).ready(function(){
$("#home_link").on('click', ()=>{
alert("Working");
$.ajax({
type: "POST",
url: "controller.php",
data: "page=landing_page"
});
});
$('#forum_link').on('click', ()=>{
$.ajax({
type: "POST",
url: "controller.php",
data: "page=forum",
success: function(){
alert("Callback Works");
}
});
});
});
I know the jquery click is working because I get the original "Working" alert as well as the callback alert if I click on the forum link.
I am using the Netbeans built in PHP development server but I have also tested it on a proper apache2 server that is well configured for PHP and AJAX.
Any help would be appreciated, thanks!
As I understand the question, this should work:
PHP: (all the same)
if(!isset($_POST['page'])){
include('Pages/landing_page.php');
echo "empty";
}
else{
echo $_POST['page'];
if($_POST['page'] == 'landing_page'){
include('Pages/landing_page.php');
}
if($_POST['page'] == 'forum'){
include('Pages/forum.php');
echo "forum hit";
}
}
JS:
$(document).ready(function(){
$("#home_link").on('click', ()=>{
alert("Working");
$.ajax({
type: "POST",
url: "controller.php",
data: "page=landing_page"
});
});
$('#forum_link').on('click', ()=>{
$.ajax({
type: "POST",
url: "controller.php",
data: "page=forum",
success: function(data){
$("#container").html(data);
alert("Callback Works");
}
});
});
});
You need to take the data returned from the function and put it somewhere, presumably into a container element.
If this isn't what you are trying to do, please comment.
I am trying to POST simple data using AJAX. My HTML code is
<input type="text" value="myvalue" id="sweet" name="sweet">
<button type="submit" id="mybtn-1">
My JQuery code is
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== '')
{
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
alert('Success');
}
});
}
});
And my test_chat.php code is
<?php
echo $_POST["sweet"];
echo 'hello';
?>
I want to echo the POST data in a div with the name "test_wrap". The problem is after clicking the button, I can only echo "hello" on the page.
I know it's happening because the load function is reloading the PHP file but I am looking for a solution so that I can show the POST data on my page.
You could return the data directly from your test_chat.php file after the post request, no need for double request here, return data like :
<?php
echo $_POST["sweet"];
echo 'hello';
?>
Then append it to the div #test_wrap like :
$('#mybtn-1').click(function(){
var newSweet = $('#sweet').val();
if($.trim(newSweet) !== ''){
$.ajax({
url:"../test_chat.php",
method:"POST",
data:{sweet:newSweet},
dataType:"text",
success:function(data){
$('#test_wrap').html(data).fadeIn("slow");
alert('Success');
}
});
}
});
Hope this helps.
You don't need to echo it with PHP, you can display it directly from the jQuery success callback:
$.ajax({
url: "../test_chat.php",
method: "POST",
data:{
sweet: newSweet
},
success: function(data) {
$('#test_wrap').load("../test_chat.php").fadeIn("slow");
if (data !== null && data !== undefined) {
alert('Success');
// Here "data" is whatever is returned from your POST
$("#some_content").html(data);
}
}
});
do ajax request of this way in js file:
$.ajax({
data: {keys: values}/*keys you need to post (sweet: newsweet)*/
, type: 'post'
, dataType: 'json'
, url: './php/someFile.php'
, error: function (jqXHR, status, err) {
console.log(jqXHR, status, err);
}
, success: function (response) {
/*use response to innerHTML into a div here*/
}
});
use echo json_encode in php:
<?php
echo json_encode($_POST["sweet"] /*or some value from function in php*/);/*of this way, you can return a response
from server to client, echo just print something, but does not return...*/
?>
The input's value should go to PHP for validation dynamically on every keystroke. JS:
$("#coupon-code").on('keyup', function () {
var coupon = $("#coupon-code").val();
$.ajax({
url:"C:/xampp/htdocs/lessdoing/lessdoinglive.com/checkout/page-2/full-pay/coupons/coupons.php",
type: "POST",
data: {coupon: coupon}
}).done(function (data) {
if (data === "success") {
$('#coupon-code').css("background-color", "green");
}
else {
$('#coupon-code').css("background-color", "red");
}
})
});
PHP:
$coupons = array("foobar", "coupon");
foreach($coupons as $coupon) {
if ($_POST["coupon"] === $coupon) {
echo "success";
} else {
echo 'invalid';
}
}
I don't see the script echoing out anything in the console. The variable insn't posted.
1. The URL
url:"C:/xampp/htdocs/lessdoing/lessdoinglive.com/checkout/page-2/full-pay/coupons/coupons.php"
its not really an URL that is processed by your web server. File is opened from filesystem by your browser and does nothing, as its not pushed via php preprocessor. It must be an proper URI, let say, if you can visit you site with http://127.0.0.1/lessdoing/checkout/page-2/full-pay/coupons/coupons.php, your URL should be /lessdoing/checkout/page-2/full-pay/coupons/coupons.php. Full representation should work too, but is not necessary.
2. There will be no echo in console
as of PHP part of script is running on server-side, there will be no echo in browser console. To echo anything in your browser you will have to implement that in your .done() callback in your JS, eg:
.done(function (data) {
console.log(data);
if (data === "success") {
$('#coupon-code').css("background-color", "green");
}
else {
$('#coupon-code').css("background-color", "red");
}
})
3. Posting POST
Your JS script is not currently sending form format that PHP recognises and pust to $_POST array. This fix is quick, you need dataType: 'html'.
$.ajax({
url:"/lessdoing/lessdoinglive.com/checkout/page-2/full-pay/coupons/coupons.php",
type: "POST",
dataType: 'html',
data: {coupon: coupon}
})
4. PHP upgrade
if(in_array($_POST["coupon"], $coupons)) echo "success";
else echo "invalid";
As in other answer, hardly, but MAY be a situation, when you put coupon twice in your $coupons array and produce "successsuccess" instead of "success".
url:"C:/xampp/htdocs/lessdoing/lessdoinglive.com/checkout/page-2/full-pay/coupons/coupons.php",
This line must be url. You wrote server file path.
.done(function (data) {
alert(data);
if (data === "success") {
$('#coupon-code').css("background-color", "green");
}
else {
$('#coupon-code').css("background-color", "red");
}
})
If you add alert function, you can see data variable value.
$coupons = array("foobar", "coupon");
foreach($coupons as $coupon) {
if ($_POST["coupon"] === $coupon) {
echo "success";
break;
} else {
echo 'invalid';
}
}
And
If you add break in success area, performance upgraded. Or you can use in_array function.
$coupons = array("foobar", "coupon");
if (in_array($_POST["coupon"], $coupons)) {
echo "success";
} else {
echo "invalid";
}
i have a little problem with my script.
I want to give data to a php file with AJAX (POST).
I dont get any errors, but the php file doesn't show a change after AJAX "runs" it.
Here is my jquery / js code:
(#changeRank is a select box, I want to pass the value of the selected )
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
});
});
PHP:
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
header('Location:/user/'.$user);
die();
When i run the script, javascript comes up with an alert "success" which means to me, that there aren't any problems.
I know, the post request for my data is missing, but this is only a test, so im planning to add this later...
I hope, you can help me,
Greets :)
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success: ' + JSON.stringify(msg)) },
error: function (err)
{ alert(err.responseText)}
});
});
});
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
echo json_encode($user);
This sample code will let echo the username back to the page. The alert should show this.
well your js is fine, but because you're not actually echoing out anything to your php script, you wont see any changes except your success alert. maybe var_dump your post variable to check if your data was passed from your js file correctly...
Just return 0 or 1 from your php like this
Your PHP :
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
{
$_SESSION["user"] = $user;
echo '1'; // success case
}
else
{
echo '0'; // failure case
}
Then in your script
success: function (msg)
if(msg==1)
{
window.location = "home.php"; // or your success action
}
else
{
alert('error);
}
So that you can get what you expect
If you want to see a result, in the current page, using data from your PHP then you need to do two things:
Actually send some from the PHP. Your current PHP redirects to another URL which might send data. You could use that or remove the Location header and echo some content out instead.
Write some JavaScript that does something with that data. The data will be put into the first argument of the success function (which you have named msg). If you want that data to appear in the page, then you have to put it somewhere in the page (e.g. with $('body').text(msg).
Not sure if this is possible but I have a page that submits a form with AJAX and if it meets certain conditions it should automatically take the user to another page. NOTHING is outputted before the header tag its just a bunch of conditions.
Problem: Header redirect not working...
AJAX
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
$("input").val('Company Name');
$("form").hide();
getInfo();
}
});
});
add.php
$row = mysqli_fetch_array($result);
$id = $row['id'];
header("Location: http://localhost/manage/card.php?id=$id");
Headers can only be modified before any body is sent to the browser (hence the names header/body). Since you have AJAX sent to the browser, you can't modify the headers any more. However, you can have the add.php script called via AJAX return the $id parameter. Then that parameter can be used in JavaScript to redirect the page: window.location = 'http://localhost/manage/card.php?id=' + id.
More info on PHP header(): http://www.php.net/manual/en/function.header.php
AJAX
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
window.location = 'http://localhost/manage/card.php?id=' + data;
}
});
});
add.php
$row = mysqli_fetch_array($result);
$id = $row['id'];
echo $id;
exit;
You indicate in the question that under certain conditions, you want a redirect.
To do that, you would want to alter your javascript to contain an if condition, and to watch for certain responses.
I would recommend modifying your responses to be json, so that you can pass back different information (such as a success status, as well as a redirect url, or other information you might want).
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
var response = $.parseJSON(data);
if (response.redirect) {
window.location = response.redirect_url;
} else {
$("input").val('Company Name');
$("form").hide();
getInfo();
}
}
});
});
As for your add.php file, you'll want to change this to be something more like so:
$json = array(
'redirect' => 0,
'url' => '',
}
if (...condition for redirect...) {
$row = mysqli_fetch_array($result);
$id = $row['id'];
$json['redirect'] = 1;
$json['redirect_url'] = "Location: http://localhost/manage/card.php?id=$id";
}
echo json_encode($json);
die();
You seem to have a miss understanding of how AJAX works. Introduction to Ajax.
The reason why your redirect appears not to working is because an Ajax call doesn't directly affect your browser. It's a behind the scenes call.
To get the data out from the AJAX call you need to do something with the returned data.
success: function (data) {
$("input").val('Company Name');
$("form").hide();
//You need to do something with data here.
$("#myDiv").html(data); //This would update a div with the id myDiv with the response from the ajax call.
getInfo();
}