jquery ajax not sending data in code igniter - javascript

I'm new to Codeigniter MVC framework. when i send data through ajax from views to controller this error shows click here to view the image
here is my code :
views/ajax_post_view.php :
<!DOCTYPE html>
<html lang="en">
<head>
<title>Ajax Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
$(".submit").click(function(e){
e.preventDefault();
var user_name = $("input#name").val();
var password = $("input#pwd").val();
//alert(user_name);
//alert(password);
$.ajax({
type:'POST',
url:'<?php echo base_url();?>'+'index.php/ajax_controller/submit',
dataType:'json',
data:{name:user_name,pwd:password},
success:function(data){
console.log(data);
}
});
});
});
</script>
</head>
<body>
<div class="main">
<div id="content">
<h2 id="form-head">Pavan Code Igniter Ajax</h2>
<hr>
<div id="form_input">
<?php
echo form_open();
echo form_label('User Name');
$data_name = array(
'name'=>'name',
'class'=>'input_box',
'placeholder'=>'Please enter name',
'id'=>'name'
);
echo form_input($data_name);
echo "<br>";
echo "<br>";
echo form_label('Password');
$data_name = array(
'type'=>'password',
'name'=>'pwd',
'class'=>'input_box',
'placeholder'=>'Please enter Password',
'id'=>'pwd'
);
echo form_input($data_name);
?>
</div>
<div id="form_button">
<?php echo form_submit('submit','Submit','class="submit"');?>
</div>
<?php
echo form_close();
?>
</div>
</div>
</body>
</html>
controller : controllers/Ajax_controller.php
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ajax_controller extends CI_Controller {
// Show view Page
public function index(){
$this->load->helper('form');
$this->load->helper('url');
$this->load->view("ajax_post_view");
}
// This function call from AJAX
public function submit() {
$data = array(
'username' => $this->input->post('name'),
'pwd'=>$this->input->post('pwd')
);
echo json_encode($data);
}
}
?>
KINDLY HELP ME THANKS IN ADVANCE

In the controller, set Access-Control-Allow-Origin at the top of your php script :
header('Access-Control-Allow-Origin: *');

Related

Browser does not response to header redirect

please help... i am new to php. Thanks
php1 is to send a data ('1234') via method Post to php2. php2 is supposed to redirect using Header Location to php3 with a data ('invalid').
Developer Tools of Chrome indicate that everything went well (Post data sent and received. Get data sent and received).
Somehow, the browser does not response and stay at php1. I have tried Safari and Firefox. No response.
Would be really grateful if you could advise. Thanks
The 3 php files are:
php1
<?php
session_start();
$M = '';
if (isset($_GET['m'])) {
$M = $_GET['m'];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#send').click(function () {
var str = '1234';
$.post('php2.php',
{
email: str
},
function (data, status) {
}
);
});
});
</script>
</head>
<body>
<div>
<button id="send">SEND</button>
<br>
<?php echo $M; ?>
</div>
</body>
</html>
php2
<?php
session_start();
ob_start();
error_reporting(E_ALL);
if (!empty($_POST)){
$Email = $_POST['email'];
if (!filter_var($Email, FILTER_VALIDATE_EMAIL)) {
header('Location: php3.php?m=invalid');
exit();
}
} else {
header('Location: php1.php?m=nodata');
exit();
}
ob_end_flush();
?>
php3
<?php
session_start();
$M = '';
if (isset($_GET['m'])) {
$M = $_GET['m'];
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div>
<?php echo $M; ?>
</div>
</body>
</html>
Here is a screenshot of chrome developer:
You should change the code for php1.php like this
<?php
session_start();
$M = '';
if (isset($_GET['m'])) {
$M = $_GET['m'];
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#send').click(function () {
var str = '1234';
$.post('php2.php',
{
email: str
},
function (data, status) {
$("#content").html(data); // <----- ADDED
}
);
});
});
</script>
</head>
<body>
<div id="content">
<button id="send">SEND</button>
<br>
<?php echo $M; ?>
</div>
</body>
</html>

PHP fails to get $_POST from JS

I have created an HTML page and am attempting to use AJAX via JS to echo from a PHP page:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>User Retrieval</title>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
function getid(){
var userid = document.getElementById('userid').value;
$.post('Users2.php', {postname:userid},
function(data){$('#results').html(data);});
};
</script>
</head>
<body>
<h1>User Retrieval</h1>
<p>Please enter a user ID:</p>
<input type="text" id="userid" placeholder="Please insert user ID" onkeyup="getid()" />
<div id="results"></div>
</body>
</html>
I have tested the JS and see that userid indeed gets the information from the HTML.
I then wrote the following PHP:
<?php
if (isset ($_POST['postname'])) {
$name = $_POST['postname'];
echo name;
}
else
{
echo "There is a problem with the user id.";
}
?>
However, I am always getting the else echo statement.
What am I missing here?
I am using XAMPP for local host checks.
Try this, It might help
<?php
if ($_POST[]) {
$name = $_POST['postname'];
echo $name;
}
else
{
echo "There is a problem with the user id.";
}
?>
var userid = $("#userid").val();
$.ajax
({
type:'post',
url:'user2.php',
data:{
get_id:"user2.php",
userid:userid,
},
success:function(data) {
if(data){
$("#results").html(data);
}
});
Php File
<?php
if (isset ($_POST['userid'])) {
$name = $_POST['userid'];
echo $name;
}
else
{
echo "There is a problem with the user id.";
}
?>

using ajax call to empty the div

Making a ajax, so when i click on this Link1 Button, i need to empty the contents in the products_list div
<button type="w3-button">Link1</button>
Please help me on how to make a ajax call when clicking link1 button it empty the products in product_list
The below code contains a javascript to clear the contents of products_list but it do not work
PHP File
<?php
session_start(); //start session
include("config.inc.php"); //include config file
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Stores</title>
<link href="style/style1.css" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
</head>
<body>
<div align="center">
<h3>Products</h3>
</div>
<script>
$(document).on("click", ".w3-button", function() {
$('.products-wrp').html('')
// $("#products_list").html();
});</script>
<?php
//List products from database
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code, product_image, product_price FROM products_list");
//Display fetched records as you please
$products_list = '<ul id ="products_list" class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div>
<img src="images/{$row["product_image"]}" height="62" width="62">
</div>
<div>Price : {$currency} {$row["product_price"]}<div>
</form>
</li>
EOT;
}
$products_list .= '</ul></div>';
echo $products_list;
?>
</body>
</html>
Check Code below that will empty the div On Failure on Ajax Request -
function getFailOutput() {
$.ajax({
url:'myAjax.php',
success: function (response) {
console.log(data, response);
$('#output').html(response);
},
error: function () {
//Empty Output Div ON Error Returned From Ajax Request
$('#output').html('');
},
});
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
test success | test failure
<div id="output">waiting for action</div>

How to catch an Isset, or POST information, with a form in JQuery?

So I am trying to do something simple. There is a form, it does a self post and I want to get that post information from JQuery and put it into a div.
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
JQuery here to catch button click and do a "PHP_self":
<script>
$(document).ready(function(){
$(".gettingpostbutton").click(function(){
$.post( "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>", function( data ) {
$("#add_post_information_html_here").append(data+" number from $_POST");
});/**/
});
});
</script>
</head>
<body>
<?php
// define variables and set to empty values
$number = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$number = test_input($_POST["number"]);
}
For SQL Injection:
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Basic Form:
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
put a number: <input type="text" number="number">
<br><br>
<input type="button" name="action" class="btn btn-success gettingpostbutton" value="Add Number" />
</form>
Put info to page either through PHP but prefer to do it through JQuery:
<?php
echo "<h2>Your Input:</h2>";
echo $number;
?>
<div id="add_post_information_html_here"></div>
</body>
</html>
Result:

Simple ajax post Uncaught ReferenceError

Hello I have a simple ajax call but I can not see the result. What am I doing wrong ? Thank You.
index.php
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function prova(SelectedFriend){
$.post("result.php", {Selected:Selected});
return false;
}
</script>
</head>
<body>
<?
$user="name1";
?>
<div onclick="prova(<? echo $user; ?>)" style="cursor:pointer;">
<? echo $user; ?>
</div>
<?
$user="name2";
?>
<div onclick="prova(<? echo $user; ?>)" style="cursor:pointer;">
<? echo $user; ?>
</div>
<?
$user="name3";
?>
<div onclick="prova(<? echo $user; ?>)" style="cursor:pointer;">
<? echo $user; ?>
</div>
<div id="Result"></div>
</body>
</html>
and result.php
<?
echo $_POST['Result'];
?>
The console of my browser says "Uncaught ReferenceError: name1 is not defined" when I click on name1.
The $user must be placed inside simple quotes:
<div onclick="prova('<? echo $user; ?>')" style="cursor:pointer;">
Also your function is not using the parameter as it should:
function prova(SelectedFriend){
$.post("result.php", {SelectedFriend:SelectedFriend});
return false;
}
And the result.php file must be corrected as well:
<?php
echo $_POST['SelectedFriend'];

Categories

Resources