jQuery getJSON not working - javascript

I am trying to get some data back from a server using jQuery $.getJSON, and the code seems to work fine, until it gets to $.getJSON, it doesn't seem to be triggering that at all, there are no console logs when I press the button, here is the code below,
$(document).ready(function(){
var funk;
$('#button').live('click', function(){
var funk = "";
var query = "";
$('#wrapper > [data-custom="field"]').each(function(i, data){
if(i == 0){
funk = query + $(this).attr('id')+" = '"+$(this).val()+"'";
}else{
funk = funk + " AND " + $(this).attr('id')+" = '"+$(this).val()+"'";
};
});
$.getJSON('test.php', {query: funk}, function(json){
console.log(json)
});
});
});
the PHP file test.php in the same folder,
$weo = $_GET['query'];
echo $weo;
Any ideas on what could be causing the problem?
Thanx in advance!

I expect that getJSON is falling over because the server is not returning nice JSON syntax.
Try doing
echo json_encode($weo);
in your PHP file. If you don't ultimately want to use JSON, but plain text instead, use $.get:
$.get('test.php', {query: funk}, function(data){
console.log(data)
});

If you are debugging using:
-> Firefox: open Firebug and look at the Net tab to make sure the request is firing, and to see what the response from the server is.
-> IE: Fire up Fiddler2 to see the request/response.
-> Chrome: use the Resources tab.
Once you see what the server is returning (if anything), you can figure out how to proceed.

For sure your Test.php is not working as expected. To debug what is being returned back from the server try this code
function AjaxDebug() {
$.ajax({
type: "GET",
url: "test.php",
dataType: "jsonp",
data: ({query: funk}),
success: function(results) {
alert("Success!");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
}); }
Then try having the break point in error and examine the XMLHttpRequest.getresponseText, getresponseXML etc to have a better understanding of what the problem is.

I had the same problem with getJSON not working. I noticed that data gets loaded but is not available to use.
The solution is to use JSONP and in the url querystring add a callback function variable.
$.getJSON("http://www.example.com/test.php?callback=?",function(json){
console.log(json);
});
Note that we put a ? as the callback function name instead of a real function name. This is because jQuery replaces the ? with a generated function name (like jsonp1232617941775) that calls the inline function.
In your PHP you will need to output with the callback function.
echo $_GET['callback'] . '(' . $jsonData . ');';
// prints: jsonp1232617941775({"name" : "Gaurav", "age" : "91"});
This will output valid JSONP object and you will be able to load and use in your jQuery code.

Related

Trying to pass variable from JavaScript to PHP using Ajax but got error " Undefined array key"

I have had this error for multiple days now, I have tried searching this error up but whenever I search this error up it gives a different reason for the error and when I try to add what other sites say it doesn't work which is why I am asking here as I don't see what else I can do.
I am trying to pass a variable from JavaScript to PHP but it is not working and I have no idea why.
Here is my JavaScript code:
<head>
<script type="text/javascript" src="jquery.js"> </script>
</head>
<script>
var variable = "hello";
console.log(variable);
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function() {
alert("Success");
}
});
</script>
Here is my PHP code:
$variable = $_POST['pass'];
echo($variable);
Everything seems to work perfectly. It writes the variable to the console, it comes up with the alert saying success. However I get an error message saying: 'Undefined array key "pass"'
What is causing this? Thank you?
Edit: People have told me to use isset, I have added that it removed the error however it still does not echo the PHP variable, meaning it is still not been passed to PHP, I am still trying to find how to fix this.
Your front end code looks OK, but I don't know your target PHP environement, but maybe your environnement doesn't accept formData.
By default, jQuery send ajax POST data as formData.
Try to send data as JSON
$.ajax({
url: "ajax.php",
type: "POST",
data: JSON.stringify({pass : variable}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data){alert(data);},
});
And then you will probably have to adapt your php code:
$json = file_get_contents('php://input');
// Converts it into a PHP array
$data = json_decode($json, true);
$variable = $data['pass'];
echo($variable);
Can you please use the developer tools in chrome browser that will help you to find if data is properly sent to php file.
Also you can try $_REQUEST instead of post just to check what data is coming in REQUEST as it works for GET & POST both. If it still does not help you.
Also can you please use
data: {'pass':variable}
instead of
data: {pass:variable}
let me know if it works for you.
If you get this error in your ajax.php file which you Post the data to it, I say it's normal because when you open that file (ajax.php) it's like that there is no $_POST['pass'] because you just opened that file without running JS to send data.
If you want to receive data that you send you can do this:
Your JS code I call this file index:
var variable = "hello";
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function(res) {
alert(res);
}
});
The PHP file:
$variable = $_POST['pass'];
echo($variable);
Then if You open up that index file, after running the JS code it'll send that post data to your PHP file and your PHP file will echo that, then the value will store in that res variable which when every thing went fine, you can see the alert of that res in the page (index file).
Notice that as I said you can't open up the PHP file lonely because it doesn't receive a post data on its own, it is normal for undefined to return.
Re: #puckloe your code is working, php echo wouldn't be printed with ajax(correction echo is working but wouldn't show on page if you don't print it with JS too), you have to catch the response in ajax success function ( like success: function(response) ) and print or alert the response --> success: function(response) { alert("hi look this is echo from php"+response) }
you ajax code should look like
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function(response) {
alert("hi look this is echo from php" + response);
}
});

jQuery ajax not working properly

I'm trying to implement some ajax function in my php website. I basically know how to use jQuery, but for some reason, the returned value is always empty when I alert() it. This is the code I use:
PHP:
if(_POST('ajax'))
{
$ajax_action = _POST('ajax');
if($ajax_action == "gwonline")
{
return 'test';
}
}
JS / jQuery:
$.ajax({
url: './include/ajax.php',
data: {ajax: 'gwonline'},
type: 'post',
success: function(output) {
alert(output);
}
});
I debugged it and it does call the file with an ajax request and returns the value, but not received apparently.. What am I doing wrong here? I sincerely don't know..
The response should be pass by echo function, not return. So you must use echo 'test'; instead of return 'test';
Don't forget using $ sign in front of every variable in php.

Why doesn't this function load after a successful ajax call in jquery? (updated)

I'm using the tutorial here, that used to work last month, but now it isn't. I've copied the relevant code below.
<script>
(function($) { //In case jQuery no conflict is being used
$(document).ready(function() { //wait for document ready
$("#loaddaold").click(function () {
alert("123");
//$( "#duplicateshere" ).empty();
$.ajax({
type: "GET",
url: "ajax-oldmessages.php",
dataType: "xml",
success: xmlParser
});
});
});
function xmlParser(xml) {
alert("456");
//$("#rev2").slideDown();
$(xml).find("result").each(function () {
$("#appendhere").append('' + $(this).find("title").text() + '<br>');
//$(".book").fadeIn(1000);
});
}
})(jQuery);
// http://www.webdevdoor.com/jquery/javascript-delay-input-field-change/
// http://papermashup.com/parse-xml-with-jquery/
// (not used) http://www.paulund.co.uk/process-each-node-of-xml-in-jquery
</script>
The problem is that the xmlParser() function isn't being called after the successful ajax request. It shows a 123 alert but not a 456 alert. Am I doing something wrong, or is the tutorial wrong?
Previously on the other question I was told it was a CORS issue, but I was calling the file off my computer, and in my example, so what is the problem now?
if youre using
dataType: "xml"
and if you have an invalid xml in youre response then success wont triger
check youre response because its invalid... if you want to test your code just change
dataType: "html"
and you will see your alert(456) that confirms invalid xml data
I've duplicated your issue and by placing in my response a valid xml, code was running fine
Also if youre expected data is just an string that contains an id, try using
dataType: "xml text"
NOTE: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require

Jquery ajax success, not working no return data

I really need your help.
I got this problem in my jQuery, i try to make a ajax call to a Javascript there keep an array inside in this file.
test-ajax.js
var data = ["kategori", "Alarm"];
return data;
But it come not with an array or anything not a single error.
Here is the ajax call.
$(document).ready(function() {
$(".tip").mouseover( function() {
$.ajax({
url: "http://localhost:8080/kraftvaerk/falck/FalckAlarmWeb/FalckAlarmWeb.Website/js/test-ajax.js",
dataType: "javascript",
succes: function(resultat) {
console.log("here");
$(".tip").append("<span>Katagori: " + resultat[0] + " <br /> Beskrivelse: "+ resultat[1] +"</span>");
}
});
});
});
In Html i got a table inside that table is there an a tag with class tip.
When the user mouse over that tag it should make the ajax call.
WARNING.
I use jQuery 1.2.2 the customer site i canĀ“t upgrade it
Json is not ALLOW on thit project.
You don't need to define and return a variable in your test-ajax.js file. You can simply define it as follows:
["kategori", "Alarm"]
Also, you had an extra bracket on the end that was invalid syntax.
The method you are using is more similar to jsonp. jsonp works by including a script tag on your page that points to a js script that executes a function containing the data.
For example, your test-ajax.js would be:
testajax(["kategori", "Alarm"]);
and to request it, simply do this:
window.testajax = function(data) {
console.log(data[0],data[1]);
};
$.getScript("test-ajax.js");
There you go. you just performed your first JSONP request, and it didn't involve any "json".
i try to do the same like you but from $.ajax it is not returning the result but if you use the below example then you will get the result but your file should like this :
JScript1.js ["kategori", "Alarm"]
JScript1.json ["kategori", "Alarm"]
1. $.getJSON("JScript1.js", function (data) {
console.log(data);
});
2. $.getJSON("JScript1.json", function (data) {
console.log(data);
});
result:
Array[2]
0: "kategori"
1: "Alarm"
length: 2

I want to parse json , but unsuccessful. Can any one check my code

I created a php page which print this from the database
[{"sha_id":"2","sha_text":"This is 1st sha."},{"sha_id":"4","sha_text":"this is 2nd sha"}]
now i want to extract each variable out of this.. after googling for a while i got this
$(document).ready(function(){
var output = $('#output');
$.ajax({
url: 'http://xxxx.com/android_sha/index.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var landmark = '<h1>'+item.sha_id+'</h1>'
+ item.sha_id+'</p>';
output.append(landmark);
});
},
error: function(){
output.text('There was an error loading the data.');
alert("error");
}
});
});
but it always alert error for me. I could be something wrong at $.each(data, function(i,item){ but can't figure out what should be the correct format.
If the alert("error") is triggered, it doesn't mean that the $.each function failed, it means that jQuery was unable to load the url specified or there was another problem with the ajax request. That triggers the error function, which alerts the error message.
Check that the request is working correctly, such as by using Chrome's developer tools to look at network traffic. If the page returns a non-200 status code, that is why the success function isn't triggering.
JSONP isn't actually JSON. JSONP is a "hack" to get crossdomain data. JSONP is actually JavaScript file.
You need to wrap the JSON in a function call. In your example, you're sending the jsoncallback callback, so you need to wrap the JSON in the value of that.
$callback = $_GET['jsoncallback'];
while($row = mysql_fetch_assoc($result)){
$records[] = $row;
}
echo $callback . '(' . json_encode($records) . ');';

Categories