Hey everyone. This one is puzzling me. I'm using PHP and Jquery. I am making an ajax request to a PHP file containing a get url. Eg. Path/to/file/?ID=369
The request goes out fine, I've watched it in fire bug.
However in the PHP file, the ID variable doesn't exist. When I do
var_dump($_GET)
I can see that there are two arrays inside the GET array. These are JSON and action.
Can anyone explain to me what's going on here and how I can receive my ID variable?
here are my codes:
<?php
$program_price_id = $_GET['id'];
$programDepatures = getProgramDepaturesGreaterThanToday($program_price_id);
echo "[{optionValue: 0, optionDisplay: 'Select a date'}";
while ($programDepartureData = mysql_fetch_array($programDepatures)) {
echo ", {optionValue: ".
$programDepartureData['id'].", optionDisplay: '".
tidyDateEnglish($programDepartureData['departure_date'])."'}";
}
echo "]";
?>
Best wishes,
Mike
i think you need to specify the ajax method you are using.It might be a $.ajax, $.get or $.getJson.
but i use $.ajax and here is a snippet
$.ajax({
url:"event/service_ajax_handler.php",
type: "GET",
data: {action:"getTime"},
dataType : "json",
success: function(data) {
$("#cmbTimeRange").html("<option value='-1'>Please select time range</option>");
$.each(data, function(){
$("#cmbTimeRange").append("<option value='"+ this.id +"'>" + this.hours +"</option>")
});
},
error: function(){
alert("error");
}
});
pay attention to the data parameter. see also
getJSON
This may be obvious, but I noticed in the sample URL you have ID capitalized, but in your PHP code you have it lowercase. PHP is case sensitive, so it could be as simple as that.
Related
Trying to send a post request from ajax to php.
I did many trial and errors based from the answers including making sure that the "type" is set to post, specifying "dataType", correct "url". I think I miss something important but I can't figure out what it is.
main.php
<script>
$(document).ready(function(){
$(".editContact").on("click", function(){
let dataID = $(this).attr("data-id");
console.log(dataID);
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
dataType: "text",
data:{data:dataID}
});
});
});
</script>
functions/phonebook.php
if(isset($_POST["data"])){
$res = array($data=>var_dump($_POST["data"]));
}
else{
$res ='null';
}
Then print the $res variable containing the dataID from ajax to my html element in main.php
<label class="m-label-floating">Contact name <?php echo $res; ?> </label>
The console.log in my main.php prints the data what I want to send in ajax but when I try to send the dataID to my phonebook.php, I get a null value.
Your problem is here:
$res = array($data=>var_dump($_POST["data"]));
You are using var_dump the wrong way.
From the docs:
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
This function does not return any value, so, in your case, $data=>var_dump($_POST["data"]) will always be null.
What you need to is:
$res = array($data => $_POST["data"]);
If you are sending data to a different page altogether and need to use jquery / JS to do it, it might be simpler to send via window replace:
window.location.replace(...)
If you need to stay on the same page, you might want to include a success function in your ajax query, as this will return to the page you are calling from:
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
data:{data:dataID},
success: function (html) {
// do your HTML replace / add stuff here
},
});
I'm new to jQuery and Ajax and I have run into a problem. Im getting the error on my console that:
NS_ERROR_XPC_BAD_CONVERT_JS: Could not convert JavaScript argument # http://localhost
/jquery.js:7065
Why am I receiving this error?
this is the code Im Using:
function upload_file(){
var file = document.form1.file_upload;
var date = document.form1.date_added;
var author = document.form1.author;
var user = document.form1.user;
var semester = document.form1.semester;
var class1 = document.form1.class;
var subject = document.form1.subject;
$.ajax({
type:"get",
url:"upload_file.php",
data:{
"file":file,
"date":date,
"author":author,
"user":user,
"semester":semester,
"class":class1,
"subject":subject
},
success:function(result){
$("#result").html(result);
}
});
}
Im waiting for your replies.
PS: I Did search the forum but did not get what i want, so if i missed something, sorry in advance.
I think the problem is you are trying to pass complete objects to the JSON.
You should use values instead of objects. For example, replace:
var subject = document.form1.subject;
with:
var subject = document.form1.subject.value;
Use this , i guess bracket mismatch --
$.ajax(
{
type:"get",
url:"upload_file.php",
data:{
"file":file,
"date":date,
"author":author,
"user":user,
"semester":semester,
"class":class1,
"subject":subject
},
success:function(result)
{
$("#result").html(result);
}
);
I ran into the same error, but my problem was different.
Turns out, I was passing a parameter in the ajax call that wasn't present in my DOM at all.
In #ZackValentine-s case (or for someone reading this in the future), please check the value of all the data items you are about to pass to the ajax call, BEFORE the actual call itself.
We had the same error.
Upgraded to the latest version of JQuery and problem solved.
This one seems to work for some people seen that solution here too
I can't get the following PHP + jQuery to work - all I want the script to do is pass the value through ajax, and get the php to grab it, check it matches and add 1 to score.
This is the code I've written:
<?php
$score = "1";
$userAnswer = $_POST['name'];
if ($_POST['name'] == "145"){
$score++;
}else{
//Do nothing
}
echo $score;
?>
<script type="text/javascript">
$(document).ready(function() {
$("#raaagh").click(function(){
var value = "145";
alert(value);
$.ajax({
url: 'processing.php', //This is the current doc
type: "POST",
data: ({name: value}),
success: function(){
location.reload();
}
});
});
});
</script>
<p id="raaagh">Ajax Away</p>
Thanks for the help, I've changed GET to POST in both instances, and no joy - there's something else wrong.
First of all: Do not go back to the dark ages... don't use the same script to generate HTML and to respond to an ajax request.
I can't make any sense of what you are trying to do... Let me change your code so it at least makes some sense and document what's going on. It seems like the problem is the fact that you are calling location.reload from your success handler.
// ajax.php - Outputs 2 if the name parameter is 145, 1 otherwise (????)
<?php
$score = "1";
$userAnswer = $_POST['name'];
if ($_POST['name'] == "145"){
$score++;
}
echo $score;
?>
// test.html
<script type="text/javascript">
$(document).ready(function() {
$("#raaagh").click(function(){
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
// Why were you reloading the page? This is probably your bug
// location.reload();
// Replace the content of the clicked paragraph
// with the result from the ajax call
$("#raaagh").html(data);
}
});
});
});
</script>
<p id="raaagh">Ajax Away</p>
You use POST in your jQuery, but you try and get a GET in you php.
BTW it is good practice to check if a GET/POST variable is set before reading it.
using the isset() function.
Replace $_GET with $_POST and there you are.
Basically POST and GET are two different way to pass variables to a script. The get method in php can also be attached at the end of a url : script.php?variable=value and it is really easy to hack. While the post method can be submitted with forms or ajax calls and it is pretty safe, at least more than the get.
Also i'd suggest you to check whatever a GET or POST variable is set before calling it, so that you can prevent stupid notice errors.
Just use the following code:
if (isset($_POST['var']) and !empty($_POST['var'])) { // do something }
You can also delete the
}else{
// do nothing
}
part of the script, since the else clause it is not necessary always.
You're submitting the data with an Ajax POST, but trying to read it out of a GET. Either use type: "GET" in your Ajax call or $_POST['name'] in your PHP.
The problem is you are using jQuery to POST your value, yet you are reading it with GET.
You should be able to fix your problem by changing your $_GET['name'] to $_POST['name']
Here is a piece of code :
$username="anant";
$name="ana";
echo $username;
echo $name;
Now if using jquery $.post() i want to retrieve $username and $name ,how would I do it ?
Thanks!
I assume the code is your php based response to the $.post call. If all you are returning are values then the easiest thing to do is to return a json response. For example...
PHP Script:
$values = array(
'username' => 'anant'
'name' => 'ana'
);
header('Content-type: application/json');
echo json_encode($values);
JS $.ajax call:
$.ajax(
url: '/path/to/script.php',
type: 'post',
dataType: 'json',
success: function(data){
alert('Username: '+data.username);
alert('name: '+data.name);
}
);
Or if you wanna stick with $.post then follow kovshenin's answer for the syntax using $.post. But be sure you use my php code witht he header() call to properly set the content type of the http response. I just prefer to use the long hand.
I'm not a php expert but try something like:
php
$username="anant";
$name="ana";
echo json_encode(array("username"=>$username,"name"=>$name));
js
$(function() {
$.get('test.php', function(data) {
alert(data.username + ':' + data.name);
});
});
I hope this helps!
You will be better off with json_encode which javascript will understand just fine:
$res = array('username' => 'anant', 'name' => 'something');
echo json_encode($res);
Then use the following code in jQuery to retrieve the values:
$.post('/something', function(response) {
alert("Username is: " + response.username + " and name is: " + response.name);
}, "json");
Cheers.
Now that I know what you are trying to do post expects a fourth parameter the encoding type. If you set it to JSON you would encode your data like so
echo '{"username": ".'$username.'", name":"'.$name.'"}'; //Json may not be perfect
you can access it in jQuery using
data.username
First thing is you have to do a GET not a POST. You may need to change your server side code a little bit so that front end had a clue of how to identify different values (JSON will be better) but a simple , should work fine.
$username="anant";
$name="ana";
echo "$username,"
echo "$name";
your output will be then something like Anant001,Anant your username, name.
Then use a simple jQuery call to get it and split it by , and here is an example..
$.get('/getnames', function(data){
var tokens = data.split(",");
var username = tokens[0];
var name = tokens[1];
});
I hope you'll able to help me. I'm fed up of trying things without any solution and php it's just driving me crazy. I'm looking for help because I have a html document where I use ajax thanks to jquery api. Inside this file, in a js function I have:
$.ajax({
type: "GET",
url: "c.php",
data: "dia="+matriz[0]+"&mes="+matriz[1]+"&ano="+matriz[2]+"&diaa="+matriz2[0]+"&mess="+matriz2[1]+"&anoo="+matriz2[2]+"&modo=0&semana=0",
success: Mundo,
error: function(e){
alert('Error: ' + e);
}
});
This code allows me to send the information that I want to the file c.php where I have:
include('funciones.php');
include('config.php');
$mierda = array();
$mierda[0] = $_GET['modo'];
$mierda[1] = $_GET['dia'];
$mierda[2] = $_GET['mes'];
$mierda[3] = $_GET['ano'];
$mierda[4] = $_GET['diaa'];
$mierda[5] = $_GET['mess'];
$mierda[6] = $_GET['anoo'];
$mierda[7] = $_GET['semana'];
As you see it's very simple. My crazy problem is that with firebug I've seen that the data is sent well but for some reason I can't use it. I have tried with $_Get, $_post and $_request and always is the same problem. But this can be stranger... If I put:
echo json_encode($mierda);
then miraculously, the php returns the data that I have passed so in conclusion I have:
I can send the data to the php file well
I can print all the data that I have sent well just accessing yo $_GET, $_POST, $_REQUEST
I can't use any value separatly like $_GET['dia']
What's going wrong there?
PS. The include php files are functions that access to my database so there's no interaction with them.
Your data is not URL-encoded. Try do something like this,
$.ajax({ type: "GET",
url: "c.php",
data: {"dia":matriz[0], "mes":matriz[1] ....},
success: Mundo,
error: function(e){ alert('Error: ' + e); }
});
If you are returning a json value use json to read that.
See
http://api.jquery.com/jQuery.getJSON/
http://pinoytech.org/blog/post/How-to-Use-JSON-with-jQuery-AJAX
Here is an example to read json value
$('document').ready(function(){
$('#submit).click(function(){
$.post('your_php_page.php', {employee_id: '456'},
function(data){
console.log(data.first_name);
console.log(data.last_name);
}, 'json');
})
});
Hope it helps
You have a crazy problem. According to your question:
$mierda = array();
$mierda[0] = $_GET['dia']; //... and so on
echo json_encode($mierda);
works while:
echo $_GET['dia'];
doesnt. Try:
$mierda = array();
$mierda[0] = $_GET['dia'];
echo $mierda[0];
echo $_GET['dia'];
It will show you whether the problem is in the PHP, or the javascript.
I have encoded the data as ZZColer said and the error is still.
Starx, it's not a question of the returning.
digitalFresh, in fact the error is from PHP because I can copy $_POST, $_GET array to a new array and print all this information but if I put after all things like:
If( mierda[0] == 0) {... The element is empty! and if I try directly $_GET['dia'] it says that this element doesn't exist in the array. Also I have tried $_GET[dia] or $_GET[0] without a solution.
PD:
I don't know how but PROBLEM SOLUTIONED!
Thanks to all!