I am trying to get a jQuery variable to a PHP variable. I have looked it up but can't find a solution. I have the following jQuery:
$('.eventRow').click(function(){
var eventID = $(this).attr('id');
$.ajax(
{
url: "index.php",
type: "POST",
data: {'phpEventId': eventID },
success: function (result) {
console.log('success');
}
});
When I console.log te "eventID" it correctly displays the number.
My PHP code is in the index.php. This is also where the .eventRow class is.
<?php
$phpEventId = $_POST['phpEventId'];
echo "<script>console.log('Nummer: ".$phpEventId."')</script>";
print $phpEventId;
?>
However nothing happens. The console.log just displays: "Number: " Is there something wrong with the code? Thanks for your help!
EDIT: Could it be the problem that the index.php is already loaded before I click on the button? Because this php code is in the index.php and thus the $phpEventId is not yet set.
In your Ajax, the type: "POST" is for jQuery prior to 1.9.0. If you're using the latest jQuery, then use method: "POST".
If you're using the latest jQuery and you don't specify method: "POST", then it defaults to method: "GET" and your PHP needs to capture it with $_GET['phpEventId'];.
After reading your update, let's try one thing. Change your PHP to return something meaningful to Ajax:
<?php
$phpEventId = $_POST['phpEventId'];
echo $phpEventId;
?>
Then try to capture the PHP response in your Ajax:
$.ajax({
url: "index.php",
method: "POST",
data: {'phpEventId': eventID },
success: function (result) {
alert("result: " + result);
}
});
This is just a part of your code, and the problem is somewhere else. In this context your code works just fine:
<div class="eventrow" id="1">This</div>
<div class="eventrow" id="2">That</div>
<script>
$('.eventRow').click(function(){
var eventID = $(this).attr('id');
$.ajax(
{
url: "index-1.php",
type: "POST",
data: {'phpEventId': eventID },
success: function (result) {
console.log('success: '+eventID);
}
});
});
</script>
With the matching index-1.php:
<?php
$phpEventId = $_POST['phpEventId'];
echo "<script>console.log('Nummer: ".$phpEventId."')</script>";
print $phpEventId;
?>
Not sure though why do you print javascript code (console.log) into an ajax response here...
Error Is Visible Even Here
According to WebZed round statistic report, this error was visible over 84% of web-developers.
Failed to post data to PHP via JQuery while both frameworks and codes were updated.
Possible Solutions Available Today
Try using other methods for posting because JQUERY and AJAX libraries are not as efficient as shown in the surveys.
New frameworks are available which can do better with PHP.
Alternative method is to create a post request via $_GET method.
Regular HTML5 supports <form></form> try method="post". For security reasons try using enctype="" command.
Try using React Native https://nativebase.io/
Related
I'm trying to implement a custom suggestion engine using jquery.
I take the user input, call my codeigniter v2 php code in order to get matches from a pre-built synonyms table.
My javascript looks like this:
var user_str = $("#some-id").val();
$.ajax({
type: "POST",
url: "http://localhost/my-app/app/suggestions/",
data: {"doc": user_str},
processData: false
})
.done(function (data)
{
// Show suggestions...
});
My PHP code (controller) looks like this:
function suggestions()
{
$user_input = trim($_POST['doc']);
die("[$user_input]");
}
But the data is NOT posted to my PHP :( All I get as echo is an empty [] (with no 500 error or anything)
I've spent 2 days looking for an answer, what I've read in SO / on google didn't help. I was able to make this work using GET, but then again, this wouldn't work with unicode strings, so I figured I should use POST instead (only this won't work either :()
Anyone can tell me how to fix this? Also, this has to work with unicode strings, it's an important requirement in this project.
I'm using PHP 5.3.8
Try using the $.post method, then debug. Do it like this:
JS
var user_str = $("#some-id").val();
var url = "http://localhost/my-app/app/suggestions";
var postdata = {doc:user_str};
$.post(url, postdata, function(result){
console.log(result);
});
PHP
function suggestions(){
$user_input = $this->input->post('doc');
return "MESSAGE FROM CONTROLLER. USER INPUT: ".$user_input;
}
This should output the message to your console. Let me know if it works.
For those interested, this works for me, even with csrf_protection being set to true
var cct = $.cookie('csrf_the_cookie_whatever_name');
$.ajax({
url: the_url,
type: 'POST',
async: false,
dataType: 'json',
data: {'doc': user_str, 'csrf_test_your_name': cct}
})
.done(function(result) {
console.log(result);
});
I have two PHP files with one posting via ajax to the other one. The post works great in chrome. But it doesnt work in firefox. A debug with firebug shows "POST error" in red color. I am pasting my codes below.
Ajax:
var data_val={'user_name' : response.name,
'user_id' : response.id,
'user_first' : response.first_name,
'user_email' : response.email,
'user_birthday': response.birthday,
'user_location': response.location.name,
'user_hometown':response.hometown.name,
'user_bloodGroup':window.bloodGroup,
'user_bloodRare':window.user_bloodRare,
'user_phone_no':window.user_phone,
};
$.ajax({
type: "POST",
url: "buddha.php",
data: data_val,})
});
The file into which it is being posted, buddha.php.
$name1 = $_POST['user_name'];
$email1 = $_POST['user_email'];
$birthday1=$_POST['user_birthday'];
$location1=$_POST['user_location'];
$hometown1=$_POST['user_hometown'];
$fbbloodgroup=$_POST['user_bloodGroup'];
$fbuserid=$_POST['user_id'];
$user_phone=$_POST['user_phone_no'];
$user_bloodRare=$_POST['user_bloodRare'];
$user_email=$_POST['user_email'];
The above ajax is inside a javascript function,
function fetchUserDetail()
It is called in a buttonclick as follows.
<a class="button_for_me" onclick="checkFacebookLogin()" >Register Me </a>
I have to repeat, this works perfectly and pleasantly in chrome. Initially i thought it was the problem of the success alerts shown at he return of the ajax function, but its not.
Assuming from your question that "response" is an object returned by FB API call, I would like to say that the problem is with the Facebook API. Sometimes, the user doesn't have value for variables like "Hometown" and "CurrentTown". In that case, the following assign operations in your code would fail.
'user_location': response.location.name,
'user_hometown':response.hometown.name,
'user_bloodGroup':window.bloodGroup,
Try changing the ajax from:
$.ajax({
type: "POST",
url: "buddha.php",
data: data_val,})
});
to remove the extra closing tags and comma after data_val like
$.ajax({
type: "POST",
url: "buddha.php",
data: data_val
});
Check out this jsFiddle i created for you with an event binding on the class to trigger the ajax request when clicked.
Hello: I am working on a project where I am going to have divisions from a league listed as buttons on a page. And when you click on a button a different team list shows for each division. All divisions and teams are stored in a mysql database and are linked together by the "div_id". The plan was have the buttons use javascript or Jquery to send the 'div_id" to a function; which would then use ajax to access an external php file and then look up all the teams for that division using the div_id and print them on the page. I have been piecing this all together and getting the various pieces to work. But when I put it all together; it seems like the ajax part - does not pull in fresh data from the database if the data is changed. In fact, if I change the PHP file to echo some more data or something, it keeps using the original unaltered file. So, if the data is changed that is not updated, and if the file is changed that is not updated. I did find if I actually copied the file with a new name and then had my ajax call use that file instead; it would run it with new code and the new data at that time. But then everything is now locked in at that point and cannot get any changes.
So - I do not know much about ajax and trying to do this. I am not sure if this is totally normal for what I am using and for a dynamic changing team list, it cannot be done this way with ajax calling a PHP file.
OR - maybe there is something wrong with the ajax code and file I have which is making it behave this way? I will paste in the code of my ajax code and also the php fileā¦
here is the ajax call:
var answer = DivId;
$.ajax({
type: 'GET',
url: 'path_to_file/gscript2.php',
data: 'answer=' + answer,
success: function(response) {
$('#ajax_content').html(response);
}
});
and here is the script.php file that it calls (removed db credentials):
<?php
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
) {
// AJAX request
$answer = $_GET['answer'];
$div_id=$answer;
echo "div id is: " . $div_id . "<br/>";
mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db($dbname);
$result_g1 = mysql_query("SELECT * FROM teams WHERE div_id=$div_id");
while($row = mysql_fetch_array($result_g1, MYSQL_BOTH))
{
$team_id=$row[team_id];
$team_name=$row[team_name];
echo $team_id . " " . $team_name . "<br/>";
}
}
?>
So - to sum up - is there something wrong with this making it do this? Or is what it is doing totally normal and I have to find a different way?
Thanks so much...
Most likely your browser is caching.
Try adding cache: false as such:
$.ajax({
cache: false,
type: 'GET',
...
The jQuery documentation explains that by doing so, it simply adds a GET parameter to make every request unique in URL.
It works by appending "_={timestamp}" to the GET parameters.
I believe this is caused by your browser's cache mechanism.
Try adding a random number to the request so the browser won't cache the results:
var answer = DivId;
$.ajax({
type: 'GET',
url: 'path_to_file/gscript2.php?r=' + Math.random(),
data: 'answer=' + answer,
success: function(response) {
$('#ajax_content').html(response);
}
});
Or turning jQuery's caching option off by:
var answer = DivId;
$.ajax({
type: 'GET',
url: 'path_to_file/gscript2.php',
data: 'answer=' + answer,
success: function(response) {
$('#ajax_content').html(response);
},
cache: false
});
Or (globally):
$.ajaxSetup({ cache: false });
I know this question has been asked a lot as I have been googling since morning but I just can't think what's going on in my code.
I have a index.php (which is my website) that uses forms to receive information from user, then invokes a javascript file separately which in turn invokes another backend php file (this backend php file queries a database using mysql and does some stuff).
The problem is I am not sure what information is getting passed to the backend php from my js. I have just learnt jQuery and Ajax so I really don't know what is that small mistake I am making.
From my understanding, the backend php does its stuff and passes the value to javascript to be displayed on the web page. But my data is not getting sent / displayed. I am getting a error 500 internal server error.
Here are the pieces of code that are currently is question:
Javascript:
var data1 = {week:week, group:grp_name};
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php",
success : function(response){
alert ("success !");
},
error : function(response){
console.log(response);
alert("fail!");
}
})
});
PHP backend (remindUsers.php):
<?php
if (isset($_POST['week'])) {
$week = $_POST['week'];
}
if (isset($_POST['group'])) {
$group_name = $_POST['group'];
}
echo $week;
?>
I am ommiting out the sql code pieces because they work fine.
Edit: Now my status code is 200, response text is also ok . My response text shows a weird "enter' sign next to the actual response text expected. Is this normal ? And it is still going into the error block , not the success block of code.
I can not fully answer your question because I need more debug information about whats going on but theres 2-3 things about your code bugging me a little that might fix your bug.
First, use isset in your backend like this:
if (isset($_GET['your_input_name'])) {
$someData = $_GET['your_input_name'];
}
The isset part is very important here. Set it up and try it again. If you stop having a 500 error. Its probably because your data was never send to your backend or because your not checking the good input name.
Second, About input name. I can see in your code that you send:
var data1 = {week:week, group:grp_name};
So in your backend you should use the name of the value like this to retrieve your data:
$week = $_POST("week");
Third, I am not a json pro but maybe your json is not valid. Even if he is ok I suggest you build a "cleaner" one like this:
var data = [
{ 'name' : 'week', 'value' : week}
];
And finally, if you are using forms to send data to php then you can use something like that :
var myForm = $("#myForm").serializeArray();
$.ajax({
url: 'yourUrl',
type: "GET",
data: myForm,
dataType: 'json',
success: function(res){
//your success code
},
error: function(){
//your error code
}
});
I hope this helps.
You can't have these tags <body>,... in your PHP response over json.
It must be only:
<?php
$week = $_POST("data");
$json = json_decode($week);
echo json_encode($json);
?>
Remove the comment on
//data : {week :week}
And set a variable week with a valid value:
data : {week :week}
and so:
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php",
data : {week :week} ,
success : function(response){
console.log(response);
},
In order to see what is the shape of response.
You are doing a couple things wrong. First, you don't want to stringify your data before sending it to the server. You want to send JSON, so your commented line is the correct one. There is also a problem with the PHP. The data going to the server will look like:
{week: "Something"}
So in your PHP, you want to access the data like:
$_POST["week"];
USE THIS
PHP
$week = $_POST['data'];
$json = json_encode($week);
echo $json;
JS
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php"
//data : {week :week} ,
data: {data:{week:'week', group:'grp_name'}} ,
success : function(response){
alert ("success !");
},
error : function(response){
alert("fail!");
}
})
I would say wrap the php in a function and echo the json. Also its good to check if there was POSTed data, and if not return an error message. This is not tested, but will hopefully point you in the right direction.
<?php
function getJSON() {
if (isset($_POST["data"] && !empty($_POST['data']) ) {
$week = $_POST["data"];
$json = json_decode($week);
echo $json;
} else {
echo "There was a problem returning your data";
}
}
getJSON();
?>
Actually as I write this, I realized you could try these headers in your AJAX POST:
accepts: 'application/json',
contentType: 'application/json',
dataType: 'json'
Hope that helps.
It worked. I figured out the answer thanks to another SO post.
TIL : Even if server response is ok, the error condition will be triggered because the data returned to javascript from php is not json,since i had explicitly mentioned dataType: "json" in the ajax request.
Link here:
Ajax request returns 200 OK, but an error event is fired instead of success
Thanks folks for helping me and steering me in the right direction. Cheers!
i'm trying to send an js object to a php function using jquery.ajax.
This is what i have so far:
js side:
$.ajax({
type: "GET",
dataType: "json",
url: url,
data: {persoon : persoon2},
async: false,
success: function(){
alert(data);
return true;
}
});
php side:
$decode = json_decode($_GET["persoon"]);
$verzekering->setVoornaam($decode->persoon_voornaam);
in js this works: persoon2.persoon_voornaam
but i can't get to the value in php, what am i doing wrong?
few fixes
data: "persoon=persoon2", // check input format
success: function(data) { // missing data argument
EDIT your ajax code is working (check URL or php code)
http://jsfiddle.net/ish1301/KZndE/
Found the problem(s)
I was using this inside Drupal and the Jquery version was still 1.2.6. Upgrading it resolved a lot of the problems
The string i tried to catch with the $_GET["persoon"] was mall formated becaus i just send along a js object. Changing
data: {persoon : persoon2},
to
data: {persoon:JSON.stringify(persoon2)},
fixed the problem