Trying to call php function with ajax doesn't work - javascript

I'm trying to pass some variables to a php file with ajax
$(document).ready(function(){
$("button").click(function(){
var id = this.id;
var name=this.name;
console.log(id+" "+name);
$.ajax({
type: 'GET',
url: 'utility.php',
dataType: 'text',
data: {id: id, name: name},
success: console.log('aa'),
//error: function( jqXhr, textStatus, errorThrown ){ console.log( errorThrown ); },
//complete: alert(id+' '+name)
}); // Ajax Call
}); //event handler
}); //document.ready
<?php
warning('getting something');
if($_GET['id'] && $_GET['name']){
$id=$_GET['id'];
$name=$_GET['name'];
if($id=='delete'){
my_remove($name);
}
if($id=='modify'){
retrieve($name);
my_remove($name);
modify($name);
}
}
else {
warning('unable to get information');
}
function my_remove($name){
warning('deleting');
//mysqli_query($con,"DELETE FROM `book`.`".$page."` WHERE `".$page."`.`name` =\'".$name."\'");
//echo "<script type='text/javascript'>alert('$name');</script>";
}
function modify($name){
warning('modified');
}
function retrieve($name){
warning('fetching');
}
function warning($message){
echo "<script type='text/javascript'>alert('$message');</script>";
}
?>
The .js part seems to run smoothly, it sets the name and id as it should and returns a success message, but nothing else happens, not even the alert('getting something') which should run regardless of parameters.
Printing out the data gives [object Object] which I'm not even sure what it means.
Please help!

you're using GET not POST so under the line
if($_GET['id'] && $_GET['name']){
should be get, not post as you have it
$id=$_GET['id'];
$name=$_GET['name'];

since your php script runs in the background with your ajax call, I don't think the alert code in that page will work. Instead try returning the plain text to the ajax function and alert it there
$(document).ready(function(){
$("button").click(function(){
var id = this.id;
var name=this.name;
console.log(id+" "+name);
$.ajax({
type: 'GET',
url: 'utility.php',
dataType: 'text',
data: {id: id, name: name},
}).done(function(text){
alert(text);
}); // Ajax Call
}); //event handler
}); //document.ready
and your php file like this.I changed your warning function
<?php
warning('getting something');
if($_GET['id'] && $_GET['name']){
$id=$_GET['id'];
$name=$_GET['name'];
if($id=='delete'){
my_remove($name);
}
if($id=='modify'){
retrieve($name);
my_remove($name);
modify($name);
}
}
else {
warning('unable to get information');
}
function my_remove($name){
warning('deleting');
//mysqli_query($con,"DELETE FROM `book`.`".$page."` WHERE `".$page."`.`name` =\'".$name."\'");
//echo "<script type='text/javascript'>alert('$name');</script>";
}
function modify($name){
warning('modified');
}
function retrieve($name){
warning('fetching');
}
function warning($message){
echo $message;
}
?>

Related

AJAX request is sent, but $_POST doesn't update

The AJAX request goes through correctly, I checked with chrome's developer tools, there is a request on quiz.php page, but when I check for $_POST['risultato'] it looks doesn't exist. I noticed though that in Chrome's dev tools there's 2 quiz.php elements (one xhr the other document)
I tried changing the code in several ways, but it seems like it doesn't work
<?php
if(isset($_POST['risultato'])){
print($_POST['risultato']);
}
?>
<script>
function inviaRisultati(ris){
$.ajax({
url: "quiz.php",
type: "POST",
cache: false,
data: {risultato: ris},
success: function(){
alert("INVIATI");
}
})
}
The program is expected to return the result on quiz.php page (the same page where ajax request is fired), and it's supposed to print it somewhere
EDIT: I fixed it
<?php
file_get_contents('php://input');
if(isset($_POST['risultato'])){
print($_POST['risultato']);
}
?>
function inviaRisultati(param) {
return $.ajax({
url:"quiz.php",
method:"POST",
data:{action: "SLC", risultato :param},
dataType:"text"
});
}
inviaRisultati(1).done(function(response){``
document.open();
document.write(response);
});
In Ajax, the data attribute is in JSON format.
your data attribute will be like this
data: {risultato: ris}
Hi you can do it this way:
your php script:
if (isset($_POST["action"])) {
$action = $_POST["action"];
switch ($action) {
case 'SLC':
if (isset($_POST["risultato"])) {
$response = $_POST["risultato"];
echo $response;
}
}
break;
}
Where action is a command you want to do SLC, UPD, DEL etc and risultato is a parameter
then in your ajax:
var param = $('#yourinputid').val();
function getInfo(param) {
return $.ajax({
url:"quiz.php",
method:"POST",
data:{action: "SLC", risultato :param},
dataType:"text"
});
}
call it like this:
getInfo(param).done(function(response){
alert(response);
//do something with your response here
})
Hope it helps
HTML CODE
<script>
jQuery(document).ready(function(){
ris = 'abcd';
jQuery.ajax({
url: "quiz.php",
type: "POST",
cache: false,
data: {risultato: ris},
success: function(){
}
})
});
</script>
PHP CODE
<?php
file_get_contents('php://input');
print($_POST['risultato']);
Console Output

How to post a value to a controller function on button click using Ajax and also redirect to new page at the same time?

I have a button Next that changes the page -
<a class="disabled" href="step">
<button class="btn btn-primary launch-btn disabled next">NEXT</button>
</a>
Also, when this button is clicked, I have an Ajax function that sends data to a controller function -
<script type="text/javascript">
$(function(){
$('.next').click(function() {
var a = $('#box').data('val');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>study/CreateData",
data: a,
success: function(data)
{
console.log(data);
},
error: function()
{
console.log("fail");
}
});
});
});
</script>
And I'm using this to receive the value from Ajax -
public function CreateData() {
$data = $this->input->post('data');
return $data;
}
When the Next button hits its controller where it changes to a new page, I'm trying to retrieve the value posted by Ajax to the CreateData() function -
public function step()
{
$data = $this->CreateData();
if(!empty($data)){
print_r($data); exit;
}
else {
echo "blank"; exit;
}
$this->load->view('step2');
}
However, this keeps echoing blank. This obviously means that the $data being returned is empty but I'm not sure why. The success function in my Ajax script is logging data, so it's posting the value to CreateData(). What am I doing wrong here?
Your javascript should be something like this
<script type="text/javascript">
$(function(){
$('.next').click(function() {
var a = $('#box').data('val');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>study/CreateData",
data: {my_data: a},
success: function(data)
{
console.log(data);
},
error: function()
{
console.log("fail");
}
});
});
});
</script>
Notice the data property. I have changed it to an object containing the variable a.
Now you should be able to retrieve this in your php function using
public function CreateData() {
$data = $this->input->post('my_data');
return $data;
}
Adr's answer solved part of the problem. In order to actually store and access the data, storing it in the session instead of a variable did the trick -
public function CreateData() {
$data = $this->input->post();
$this->session->unset_userdata('createData');
$this->session->set_userdata('createData', $data);
}
This prevented the $data variable from being overwritten when called the second time.

How I can locate page in jquery ajax if php return location header?

I send a form with jquery ajax like this:
$("#login").submit(function(e) {
e.preventDefault();
var url = "login";
$.ajax({
url:url,
type:'POST',
data:$(this).serialize(),
success:function(result){
$("#response").text(result)
});});
I wanna locate page if login was successful.
This is my php condition:
if(islogin())
header("Location:".$home_url."home");
}
else{
echo "Oops! Something is wrong!";
}
How can I change my jquery script to locate page? thanks.
Change your ajax success statements with:
success: function(data, status, xhr) {
console.log(xhr.getResponseHeader('Location'));
}
So your complete script would be:
$("#login").submit(function(e) {
e.preventDefault();
var url = "login";
$.ajax({
url:url,
type:'POST',
data:$(this).serialize(),
success: function(data, status, xhr) {
console.log(xhr.getResponseHeader('Location'));
}
});});
And your php script would change to:
<?php
header("Access-Control-Expose-Headers: Location");
if(islogin())
echo $home_url."home";
}
else{
echo "Oops! Something is wrong!";
}
?>
Try this:
JS
$("#login").submit(function(e) {
e.preventDefault();
var url = "login";
$.ajax({
url:url,
type:'POST',
data:$(this).serialize(),
success:function(result){
if (result.indexOf('Oops') !=-1) {
$("#response").text(result)
} else {
window.location.href = result;
}
});
});
PHP
if(islogin())
echo $home_url."home";
}
else{
echo "Oops! Something is wrong!";
}
Why would you use Ajax at all if you change the page anyway?
If you still want to, echo the actual new location instead of setting a header and do
success:function(result){
if (result.indexOf("Oops") !=-1) $("#response").text(result);
else location.replace(result);
});

Not recieving values sent via AJAX POST to PHP

I'm trying I'm trying to send a specific section of my URL string, to my php file, to then populate my page accordingly. Everything is working fine, except for the AJAX POST method. I've tried doing var_dump of the POST variable in my PHP, and my array is empty (so I know nothing is getting through).
The success DOES return as being passed, so I don't know where the data is going. I'm testing locally on XAMPP, and I've combed through SoF and no luck on any of the fixes. My code is below.
Screen shot of page:
jQuery AJAX Request:
$(document).ready(function() {
str = window.location.href;
pos = str.search("pages/"); //42
send = str.slice(42, -5);
console.log(send);
console.log(pos);
$.ajax({
type: "POST",
url: "retrieve.php",
data: {
tom: send
},
success: function() {
$.get("retrieve.php", function(data, status) {
$("#main").html(data);
}) //ends GET function
},
error: function() {
console.log(arguments)
}
}); //ends POST request
}); //ends DOC-READY function
PHP:
echo "<i>hello</i>";
echo var_dump($_POST);
$url = $_POST['tom'];
json_decode($url);
echo $url;
Try the below,
Also you don't need to json_decode unless you send a json request,And please make sure all the post values are passing.
Ajax:
$(document).ready(function() {
var str = window.location.href;
var pos = str.search("pages/"); //42
var send = str.slice(42, -5);
console.log(send);
console.log(pos);
$.ajax({
type: "POST",
url: "retrieve.php",
data: {
'tom': send//make sure this is not empty
},
success: function(data) {
console.log(data);
},
error: function(arguments) {
console.log(arguments)
}
}); //ends POST request
}); //ends DOC-READY function
PHP:
if($_SERVER['REQUEST_METHOD'] == 'POST'){
//echo "<i>hello</i>";
//echo var_dump($_POST);
$url = $_POST['tom'];
json_encode($url);
echo $url;
}

ajax request to codeigniter controller from javascript

I am making an ajax request from my codeigniter view in javascript function but nothing happens and the success alert (ok) pops up
function show_drop_downn(){
document.getElementById("drop_downn").style.visibility = "visible";
$.ajax({
type: "POST",
url: "http://localhost/ok/index.php/search/ajax_delete_ntify",
success: alert('ok'),
});
}
This is my controller it is working perfect, when i copy paste the url (used in ajax request) in my browser every thing goes good, controller makes a call to the model and it works perfect
function ajax_delete_ntify()
{
echo "incontroller";
$email=$this->session->userdata('email_of_user');
$this->load->model('search_peoplee');
$data['userid']= $this->search_peoplee->get_userid_from_email($email);
foreach ($data['userid'] as $row)
{
$one=$row->userid;
}
$this->search_peoplee->delete_notifications($one);
return;
}
View :
function show_drop_downn(){
document.getElementById("drop_downn").style.visibility = "visible";
$.ajax({
type: "POST",
url: "http://localhost/ok/index.php/search/ajax_delete_ntify",
success:function(
console.log("success");
)
});
}
Controller :
function ajax_delete_ntify()
{
echo "incontroller";
$email=$this->session->userdata('email_of_user');
$this->load->model('search_peoplee');
$data= $this->search_peoplee->get_userid_from_email($email);
$res=$this->search_peoplee->delete_notifications($data[0]->userid);
if($res){
echo json_encode(array('success'=>true));
}else{
echo json_encode(array('success'=>false));
}
}

Categories