What could be wrong with this request in AJAX and PHP? - php

I'm trying to call a PHP page passing parameters with AJAX. I can see that the page is called, but the $_REQUEST doesn't take any parameters. If anyone can help me, I'd appreciate it. Thanks!
My AJAX is that:
<script>
$(document).ready(function(){
$('.c_x').change(function(){
var href = $(this).val();
$.ajax({
type: "POST",
url: "utils/inc_iscrizione.php",
data: 'cod_evento=' + href,
success: function (data) {
alert("data:" + data);
}
});
})
});
</script>
In the PHP Page, I have this.
if(isset($_REQUEST["cod_evento"]))
{
$search = $_REQUEST["cod_evento"];
echo "<script>alert('OK');</script>";
}
else
{
$search = "";
echo "<script>alert('FAIL');</script>";
}
Always the answer is failure. Thank you!

1- change your data format in ajax request from data:'cod_evento=' + href, to data : {code_evento:href}
2 - change your php echo from echo "alert('OK');" to echo "OK"; and same for else clause
Recommended
1 - change $_REQUEST to $_POST
2 - change alert('data:'+ data) to console.log(data)

Related

Execute php using jquery post

I've tried to go to php file using jquery.
Here is my code.
This is index.php
$.post('test.php',data,function(json){},'json');
This is test.php
//set session variable from passed data
$_SESSION['data1'] = $_POST['data1'];
<script>
window.open('test1.php','_blank');
</script>
This is test1.php
echo $_SESSION['data1'];
But this code is not working.
I want to pass data from index.php to test1.php.
How can I do this? I don't want to use GET method because of too long url.
Anyhelp would be appreciate.
I am not quite clear from you explanation right now. But I am here trying to resolve you problem as you can use the jquery post method as follows :
$.post('test1.php',{param1:value1,param2=value2,...},function(data){
//Here you can take action as per data return from the page or can add simple action like redirecting or other
});
Here is a simple example of register :
$.post('', $("#register_form").serialize(), function(data) {
if (data === '1') {
bootbox.alert("You have registered successfully.", function() {
document.location.href = base_url + '';
});
} else if (data === '0') {
bootbox.alert("Error submitting records");
} else {
bootbox.alert(data);
}
$("#user_register_button").button("reset");
});
Try this:
$.ajax({
url: 'test.php',
type: 'POST',
data: {
myData : 'somevalue'
},
success: function(response){ // response from test.php
// do your stuff here
}
});
test.php
$myData = $_REQUEST['myData'];
// do your stuff here
I like use jQuery post a url like this.
$('form').on('submit', function(e) {
e.preventDefault();
var $this = $(this);
$.ajax({
url: $this.attr('action'),
method: $this.attr('method'),
data: $this.serializeArray(),
success: function(response) {
console.log(response);
}
})
});
I you a beginner, you can reference this project
php-and-jQuery-messageBoard

The best way passing value from jQuery to PHP

I wonder how I can pass value from Jquery to PHP. I found similar codes but not even one of them work.
Everytime alert shows value of variable but when I open site there is not any. Var_dump shows that $_POST is null. I am ran out of ideas do you have any?
jQuery code:
$("#password-button").click(function(){
var password="";
var numbers =[0,0,0,0,0,0];
for(var i=0;i<=5;i++){
numbers[i] = Math.floor((Math.random() * 25) + 65);
password += String.fromCharCode(numbers[i]);
}
$(".LoginError").text("Nowe haslo: " + password);
$.ajax({
type: 'post',
url: 'dzialaj.php',
data: {'password': password},
cache:false,
success: function(data)
{
alert(data);
console.log(result)
console.log(result.status);
}
});
});
PHP:
if(isset($_POST['password'])){
$temp = $_POST['password'];
echo $temp;
}
Since it looks like you are new on ajax, let's try something more simple ok? Check this js:
<script>
var string = "my string"; // What i want to pass to php
$.ajax({
type: 'post', // the method (could be GET btw)
url: 'output.php', // The file where my php code is
data: {
'test': string // all variables i want to pass. In this case, only one.
},
success: function(data) { // in case of success get the output, i named data
alert(data); // do something with the output, like an alert
}
});
</script>
Now my output.php
<?php
if(isset($_POST['test'])) { //if i have this post
echo $_POST['test']; // print it
}
So basically i have a js variable and used in my php code. If i need a response i could get it from php and return it to js like the variable data does.
Everything working so far? Great. Now replace the js mentioned above with your current code. Before run the ajax just do an console.log or alert to check if you variable password is what you expect. If it's not, you need to check what's wrong with your js or html code.
Here is a example what i think you are trying to achieve (not sure if i understand correctly)
EDIT
<script>
var hash = "my hash";
$.ajax({
type: 'post',
url: 'output.php',
data: {
'hash': hash },
success: function(data) {
if (data == 'ok') {
alert('All good. Everything saved!');
} else {
alert('something went wrong...');
}
}
});
</script>
Now my output.php
<?php
if(isset($_POST['hash'])) {
//run sql query saving what you need in your db and check if the insert/update was successful;
// im naming my verification $result (a boolean)
if ($result) echo 'ok';
else echo 'error';
}
Since the page won't redirect to the php, you need a response in you ajax to know what was the result of you php code (if was successful or not).
Here is the others answers i mentioned in the coments:
How to redirect through 'POST' method using Javascript?
Send POST data on redirect with Javascript/jQuery?
jQuery - Redirect with post data
Javascript - redirect to a page with POST data

Unable to pass data to php using ajax

First i echo images for which i set ID with php function. Now im tyring to get the ID value with jQuery click function and pass it to another php function, but unfortunately i always get the undefined index error. Can the reason be in xampp config or something else? Becasuse the code seems to be "right".
jQuery
$(function postImgId() {
$('img').click(function() {
var imgId = $(this).attr('id');
$.post('functions.php', {postId:imgId},
function(data) {
$('#content').html(data);
console.log(imgId);
});
});
});
php
function showPlayer() {
$number ='';
$number = $_POST['postId'];
if(isset($_POST['postId'])) {
echo "<h2>";
echo $_POST['postId'];
echo "</h2>";
}
}
Try:
Put this in your click function:
var imgId = $(this).attr('id');
$.ajax({
type: "GET",
url: "functions.php",
data: 'playerId=' + imgId,
success: function(data){
$('#content').html(data);
}
});
now check with isset($_GET['playerId']) and so on in your php:
if(isset($_GET['playerId'])) {
echo "<h2>";
echo $_GET['playerId'];
echo "</h2>";
}
This playerId should not be something important in your database like the unique AI id.
Whole thing also works with POST see: http://api.jquery.com/jquery.post/

jquery post not passing all parameters

i have this jquery code:
var idd = $(this).attr("id");
var page = $(this).attr("page");
var data = "lastmsg="+idd+"&page="+page;
$.ajax({
type: "POST",
url: "ajax_more.php",
data: data,
success: function(html){
$("ol#live_updates").append(html);
$("#more"+idd).remove(); // removing old more button
}
});
and this is the "ajax_more.php" code:
if(isset($_POST['lastmsg']))
{
$lastmsg = mysql_real_escape_string($_POST['lastmsg']);
$page = mysql_real_escape_string($_POST['page']);
echo $lastmsg . " " . $page;
}
Only ($lastmsg) passed, but any other parameter like ($page) is not passed. Where is the problem ??
i tried ($.post) and ($.ajax) with "POST" type, both not working...
data should be an object.
var data = {lastmsg: idd, page: page};
You need to properly encode all of your ajaxed parameters using encodeURI.
See my answer here for more information. Also, use your browser's console to debug.

Passing Javascript Variable to PHP using Ajax

I wanna pass a JavaScript variable in to php using Ajax... coz I wanna pass it onclick. I'm getting the onclick value to variable row. Help would b gratefull :) Thank You
<script type="text/javascript">
function updateTable(row) {
alert (row);
var row = (row);
}
</script>
Did u try this?
$.ajax({
url: 'do.php',
type: 'POST',
data: "userID=" + onlyID,
success: onMemberSucces,
error:onMemberError
});
function onMemberSucces(data) {
alert(data);
}
function onMemberError() {
alert("Error!!");
}
where do.php is your php file and onlyID is your javascript variable.
Is this what you were looking for?

Categories