Not able to access the $.getJSON function - php

Here is a code which try to access the $.getJSON, but it doesn't responding. What may be the possible reason for this.
function getTerms()
{
alert("hello"); //it alerts hello
$.getJSON('http://localhost/context-search.php?callback=?', function(r) {
//not here
alert("Hello");
});
}
$(document).ready(function(){
alert("hello");
getTerms();
});
context-search.php returns json data in the form of
{"options":["osi","tcp","ip","http protcol","ethernet","network protocol","protocol meaning\n"]}
Where have I possibly gone wrong?? Please help me through this!
Thank You!! :)

Did you check your console log?
If it doesn't contain an error, do a json request like this instead
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(){},
error: function(jqXHR, textStatus, errorThrown) {
console.log("error " + textStatus);
console.log("incoming Text " + jqXHR.responseText);
}
});
Which will give you proper error handling.

Possibly the same origin policy. Assuming this is running on localhost have you tried
$.getJSON('/context-search.php?callback=?', ...);

use like this
$(document).ready(function(){
$.getJSON('/ITTA/SavePreference/?t=' + new Date(), { id: id3 },
function (data) {
if (data != null && data != undefined && data != '') {
top.location.href = '/ITTA/Entries/' + id3;
}
}); });

Related

Send variable to PHP using AJAX

I've got a variable that I want to send to my PHP code that is on top of the code but I keep getting an error and undefined. dTotaal is the variable name and it contains a number. All this code is in the same page, so i am posting to the same page.
$('#emailVerzenden').click(function() {
$.ajax({
url: "content.php",
type: "post",
data: ({
totaal: dTotaal
}),
success: function(msg) {
alert('Data saved: ' + msg);
},
error: function(error) {
alert("couldnt be sent " + error);
}
});
On top of my page I've got this code. I'm not sure if it's correct, I am new at this.
if(isset($_POST['emailVerzenden']))
{
$totaal = $_POST['totaal'];
var_dump($totaal);
}
What I wanted was to put the value of the totaal data in $totaal but that is not working. The data is not being sent. I keep getting the error alert().
In your PHP code, you are checking the presence of a variable to use another. For me it should be:
if(isset($_POST['totaal']))
{
$totaal= $_POST['totaal'];
var_dump($totaal);
}
You are on right track but seperate PHP codes with jQuery codes then you will have full control of processing data asynchronously.
index.php
$('#emailVerzenden').click(function()
{
$.ajax
({
url: "content.php",
type: "post",
data:{totaal: dTotaal},
success: function(msg)
{
alert('Data saved: ' + msg);
},
error: function(error)
{
alert("couldnt be sent ".error);
}
});
And in your php file first check whether $_POST data is set
content.php
if(isset($_POST))
{
$totaal= $_POST['totaal'];
var_dump($totaal);
}
Mention your data which you wanna send in html & give it an ID.
<div id="total"> HERE COMES THE VARIABLE YOU WISH TO SEND </div>
Then pick up the data in that <div> by its ID document.getElementById('total').value like below:
var total=document.getElementById('total').value;
<script> var total=document.getElementById('total').value;
$.post('content.php',
{'total':total},
function(response){
if(response == 'YES'){}
});
</script>
Hope this will resolve your problem. Good Luck!
Kind of look like i didnt use preventDefault() thats why it wasnt working.
$('#emailVerzenden').click(function(e)
{
cms=$('#sCms').val();
templates= $('#templates').val();
onderdelen = $('input:checkbox:checked').map(function() {
return this.value;
}).get();
email = $('#email').val();
e.preventDefault();
$.ajax
({
type: "POST",
url:"test.php",
data:{postEmail : email,postOnderdelen : onderdelen,postCms : cms,postTotaal : postTotaal, postTemplates : templates},
success: function(rs)
{
alert("Data saved:" + rs);
},
error: function(error)
{
alert("couldnt be sent" + error);
}
});
e.preventDefault();
});

jQuery AJAX can't work with JSON response

I have a JSON response from my php file like:
[
{"id":"1"},
{"archiveitem":"<small>26.06.2015 12:25<\/small><br \/><span class=\"label label-default\">Bug<\/span> has been submitted by Admin"}
]
And try to fetch this response into a div after button was clicked, however firebug is telling me the message from the error-handler. I can't figure out the problem?
$('#loadarchive').click(function(){
$.ajax({
type: 'post',
url: '/src/php/LoadAdminDashboardArchive.php',
dataType: 'json',
data: {
action : 'getArchive'
},
success: function(results) {
var archiveelements = JSON.parse(results);
console.log(results);
$.each(archiveelements, function(){
$('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + this.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + this.archiveitem + '</div>');
});
},
error: function(){
console.log('Cannot retrieve data.');
}
});
});
I tried to run your Code and I get
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
By defining dataType: 'json' your result is parsed already as an Array. So you can do something like:
success: function (results) {
if (results["head"]["foo"] != 0) {
// do something
} else if (results["head"]["bar"] == 1) {
// do something
}
}
this works on my computer:
$.ajax({
type: 'post',
url: '/src/php/LoadAdminDashboardArchive.php',
dataType: 'json',
data: { action : 'getArchive' },
success: function(results) {
console.log(results);
$.each(results, function(){
$('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + this.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + this.archiveitem + '</div>');
});
},
error: function(){
console.log('Cannot retrieve data.');
}
});
You can get more information from the console if you dive into it a bit more. Or by logging these two parameters:
error: function(xhr, mssg) {
console.log(xhr, mssg);
}
First
your response is not correct,Correct response should look like this
[{
"id":"1",
"archiveitem":"<small>26.06.2015 12:25<\/small>
<br \/><span class=\"labellabel-default\">Bug<\/span> has been submitted by Admin"
},
{
...
}]
Second
You dont have to parse result ie.JSON.parse is not required since dataType:'json' will probably take care of json.
Finally your success method should look like this:
success: function(results) {
$.each(results, function(ind,el){
$('#archivecontent').html('<div class="mark-read-container"><span class="btn-mark-unread" id="' + el.id + '">Unarchive</span></div><div class="bs-callout bs-callout-default">' + el.archiveitem + '</div>');
});
},
As you are saying message from error-handler is showing.
That means AJAX is never sent to server because of incorrect URL or any other reason.
Use Firebug in Firefox and see the error in console tab.
Also I see your code
dataType: 'json',
data: { action : 'getArchive' },
success: function(results) {
var archiveelements = JSON.parse(results);
}
Do not use JSON.parse(results) because you have already written dataType: 'json', and any type of response is parsed automatically.
I was able to get it working and the problem was quite simple...
I forgot to paste the "button" - source code that initiated the ajax request. It was an Input of type "submit" and therefore the page reloaded by default after the response was retrieved successfully... so e.preventDefault(); was the way to go.
Thanks to all of you.

Error: Syntax error, unrecognized expression: <a/> Jquery UI

i tried to build an autocomplete search. Therefore i used the jquery ui and this little snippet of code:
$(function() {
$("#search").autocomplete({
source: function( request, response ) {
$.ajax(
{
url: 'autocomplete.php',
dataType: "json",
data:
{
term: request.term,
},
success: function (data)
{
response(data);
},
error: function (err) {
console.log("AJAX error in request: " + JSON.stringify(err, null, 2));
}
});
},
minLength: 2,
select: function(event, ui) {
var url = ui.item.id;
if(url != '#') {
location.href = '/blog/' + url;
}
},
html: true,
open: function(event, ui) {
alert("open");
$(".ui-autocomplete").css("z-index", 1000);
}
});
});
The file autocomplete.php returns json encoded data.
My Problem is, that for every valid response and result i get a "Error: Syntax error, unrecognized expression: " error and my results aren't displayed in a list. What does that error mean?
Thanks a lot!
Try to use
$(document).ready(function () {
/*here comes your code*/
});
Also, in your success function, try to change it to
success: function (data)
{
alert(data.d);
},
because you are returning the d, not data. d represents a property of data object.
You did not give all information to identify the problem, but you should call
console.log(data);
at the start of your success function and look at the response in your console. You must have used the bad syntax of <a/> instead of </a> either in your PHP generating your request response or in the function you pass as response.

Ajax Doesn't give me anything in the console?

Updated Question to better reflect the communities support
Based on community support I have changed the Ajax function to be as such:
(function($){
$(document).ready(function(){
$('a').click(function(e){
var el = $(this).prev('input[type="checkbox"]');
if(el.is(':checked')){
el.prop('checked',false);
}
$.ajax({
url : "http://localhost/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/AdminPanel/Template/Helper/UncheckPackageThemeHelper.php",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
e.preventDefault();
});
});
})(jQuery);
The resulting PHP Class is as such:
class CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper{
private $_element_name = null;
public function __construct(){
if(isset($_GET['element_name'])){
$this->_element_name = $_GET['element_name'];
echo $this->_element_name;
}
}
}
The network tab shows that I have some out put from activating the Jquery which I have shown below:
The Console is spitting out no errors, yet not echoing the element name. I have read up on the Jquery Ajax API and everything I have been doing, thus far, seems to be correct. Yet I am not getting the desired out put.
Note: The response tab is empty.... In other words I am not getting a response back.
You're not passing in the event to your click handler.
Use.
$('a').click(function(e){
// Your code
});
$.ajax({
url : "<?php echo CORETHEME_ADMIN_TEMPLATE_HELPER_URL . 'UncheckPackageThemeHelper.php'; ?>",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(result) {
console.log(result)
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
Simplify the situation. Just for a moment, change your AJAX processor file (UncheckPackageThemeHelper.php) to read like this:
UncheckPackageThemeHelper.php
<?php
$test = $_POST['element_name'];
$r = 'PHP received: [' .$test. ']';
echo $r;
die();
Also, change your AJAX success function to read like this:
success: function(result) {
alert(result);
},
At least, this will show you that your AJAX is getting through.
Then, start adding things back into your AJAX processor file (one or two at a time) and keep echoing something out so that you can discover where the error is happening.
So I was doing a lot of things wrong. But this is the only way it works, for me - please post your comments if you have better solution.
In the class, I have to do this:
class CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper{
private $_element_name = null;
public function __construct(){
if(isset($_GET["element_name"])){
$this->_element_name = $_GET["element_name"];
echo json_encode($this->_element_name);
}
}
}
new CoreTheme_AdminPanel_Template_Helper_UncheckPackageThemeHelper();
The class cannot be instantiated in the .phtml file with the resulting Ajax or the request is never sent back. Also notice the json_encode You cannot pass regular variables back to Ajax - when in a class (I think) - How ever when not in a class it seems to work - clarification is needed.
The Ajax then looks like this:
(function($){
$(document).ready(function(){
$('a').click(function(e){
var el = $(this).prev('input[type="checkbox"]');
if(el.is(':checked')){
el.prop('checked',false);
}
$.ajax({
url : "http://localhost/wordpress/wp-content/themes/Aisis-Framework/CoreTheme/AdminPanel/Template/Helper/UncheckPackageThemeHelper.php",
type : 'GET',
data : { 'element_name' : el.prop('name') },
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown ){
console.log(jqXHR, textStatus, errorThrown);
}
});
e.preventDefault();
});
});
})(jQuery);
The Data that comes back is what I expect: "aisis_options[package_RelatedPosts]"
There ar a couple of issues with this answer - One I dont understand why I have to instantiate the class inside the file its written in, and two not sure why I have to encode the response in a class, but not when its just a "script kiddy" file.

jQuery AJAX loads twice

I'm programming a site, and I've got a problem.
I have the following jQuery code:
$('input[type="text"][name="appLink"]').keyup(function() {
var iTunesURL = $(this).val();
var iTunesAppID = $('input[name="iTunesAppID"]').val();
$.ajax({
type: 'POST',
url: jsonURL,
dataType: 'json',
cache: false,
timeout: 20000,
data: { a: 'checkiTunesURL', iTunesURL: iTunesURL, iTunesAppID: iTunesAppID },
success: function(data) {
if (!data.error) {
$('section.submit').fadeOut('slow');
//Modifying Submit Page
setTimeout(function() {
$('input[name="appLink"]').val(data.trackViewUrl);
$('div.appimage > img').attr('src', data.artworkUrl512).attr('alt', data.trackName);
$('div.title > p:nth-child(1)').html(data.trackName);
$('div.title > p:nth-child(2)').html('by '+data.sellerName);
$('span.mod-category').html(data.primaryGenreName);
$('span.mod-size').html(data.fileSizeBytes);
$('span.mod-update').html(data.lastUpdate);
$('select[name="version"]').html(data.verSelect);
$('input[name="iTunesAppID"]').attr('value', data.trackId);
}, 600);
//Showing Submit Page
$('section.submit').delay('600').fadeIn('slow');
} else {
$('.json-response').html(data.message).fadeIn('slow');
}
},
error: function(jqXHR, textStatus, errorThrown) {
//$('.json-response').html('Probléma történt! Kérlek próbáld újra később! (HTTP Error: '+errorThrown+' | Error Message: '+textStatus+')').fadeIn('slow');
$('.json-response').html('Something went wrong! Please check your network connection!').fadeIn('slow');
}
});
});
Sometimes (randomly) the content fades out-in twice.
Could you let me know what's wrong?
Thanks in advance.
I guess the page is dynamically generated from javascript,
If you execute the following function twice, then there be two events since it executes twice,
so a better way is to unbind all previus 'keyup' event and bind it again.
Try this,
$('input[type="text"][name="appLink"]').unbind('keyup').keyup(function() {
});

Categories