Why isn't AJAX working? - javascript

I'm trying to perform a simple ajax call to a simple php script to test that ajax is working.
HTML:
<button id="hi">hi</button>
JS:
<script type="text/javascript">
$( "#hi" ).click(function(){
var dataString = "hi";
$.ajax({
url: "custom_scripts/hi.php",
type: "POST",
dataType:'json',
data: dataString,
cache: false,
success: function(data){
if(data.auth==true){
alert("success: " + data.auth);
}
}
})
});
PHP:
<?php
$hi=$_POST['hi'];
$rVal=array("auth" => false);
if(isset($hi)){
$rVal['auth']=true;
} else {
$rVal['auth']=false;
}
echo json_encode($rVal);
?>
Are there any other scripts or libraries (from any language) that can interfere with ajax calls? When I step through, it's reaching the call, it's not returning any data (and no error in console) ...

You just need to pass Ajax data as:
data: "hi="+dataString,
Complete Ajax Example:
$( "#hi" ).click(function(){
var dataString = "hi";
$.ajax({
url: "custom_scripts/hi.php",
type: "POST",
dataType:'json',
data: "hi="+dataString,
cache: false,
success: function(data){
if(data.auth==true){
alert("success: " + data.auth);
}
}
})
});
In your example, if you check browser console, you are getting Undefined Index Notice.

Related

Ajax call to 500px api not working

I have an AJAX call made with jQuery to a 500px API:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"/>
<script type="text/javascript">
$(document).ready(function(){
$('#myButton').click(function() {
$.ajax({
url: "https://api.500px.com/v1/photos?feature=editors&page=2&consumer_key=<your-consumer-key>",
dataType: 'jsonp',
type: 'GET',
success: function(result){
alert("success");
for(x in result.data){
$('#myHtmlList').append('<li><img src="'+result.data[x].image_url+'"></li>');
}
},
error: function(result){
alert("Error: "+result);
console.log(result);
}
});
});
});
</script>
The result of this code is the "Error" alert. If I copy and paste the same url in browser it works and returns the json with the images. I don't understand why the javascript call doesn't work.
I also don't understand why if I make the same code call to an Instagram API, for example:
url: 'https://api.instagram.com/v1/users/' + userId + '/media/recent'
dataType: 'jsonp',
type: 'GET',
data: {access_token: <your-access-token>},
it works.

php sending values to ajax faild error

I Am trying to send value from ajax to php and retrieve it just to test that everything is work, when i click in a button to test i got error and alert('Failed') Appears , how can i fix it in order to get success? thanks
Ajax :
var a = "test";
$.ajax({
url: "search.php",
dataType: "json",
data: a ,
success: function(data) {
alert('Successfully');
},
error: function(data) {
alert('Failed');
}
})
PHP :
<?php
$pictures = "img1";
echo json_encode($pictures);
?>
I refined your code slightly and it works.
var a = "test";
$.ajax({
type: 'POST',
url: 'search.php',
data: 'a=' + a,
dataType: 'json',
cache: false,
success: function (result) {
alert('Successful');
},
error: function (result) {
alert('Failed');
}
});
If you're requesting a JSON, use the $.getJSON from jQuery, it's aready parse the JSON into a JSON object for you.
Seems that you're not return an actual JSON from server, maybe this is what is causing the error.
If you're seeing the 'Failed' message probably the problem is a 500 error which is a server error.
Try this code above.
Javascript:
var a = "test";
$.getJSON("search.php", {
a: a
}, function (json) {
console.log(json);
});
PHP:
<?php
$pictures = ["img1"];
echo json_encode($pictures);
The only way to this not work, is if you have a huge mistake on you webserver configuration.
Your ajax is wrong, it should be:
var a = "test";
$.ajax({
type: "POST",
url: "search.php",
dataType: "json",
data: {a:a},
success: function(data) {
alert('Successfully');
},
error: function(data) {
alert('Failed');
}
});

Parse JSON data in jQuery and display in textfield

I am going to print the response data from test.php in JSON format to print it on particular field
$.ajax({
type: 'POST',
url: 'test.php',
data: data,
success: function(response) {
var result = $.parseJSON(response);
$(document).ready(function(){
$("#test").click(function(){
$("#bemail").val(result.email);//when i prints only result than it displays [object object]
});
});
}
});
Try it like this . You have to put your ajax inside $(document).ready
$(document).ready(function(){
$.ajax({
type: 'POST',
url: 'test.php',
data: data,
success: function(response) {
var result = JSON.parse(response);
$("#bemail").val(result.email);
}
});
});
you are calling document.ready() inside the AJAX success handler which doesn't get invoked since AJAX call doesn't invoke the document loading again, DOM has already loaded and it loads only once in the life cycle of a page session.
This much should do
$.ajax({
type: 'POST',
url: 'test.php',
data: data,
success: function(response) {
var result = JSON.parse(response);
$("#bemail").val(result[0].email); //after you explained the JSON response
}
});
Your code is totally wrong, it should be
function displayEmail() {
$.ajax({
type: 'POST',
url: 'test.php',
data: data,
success: function(response) {
var result = $.parseJSON(response);
//Just Print the Result in Console using console.log(result)
$("#bemail").val(result.email);
}
});
}
$(document).ready(function() {
$("#test").click(function() {
displayEmail();
});
});

Ajax not being called in javascript function

In the success function I want to call a function. The problem is that ajax does not fire, so the data is never triggered and display. Here is my ajax call with a javascript function call in the success function.
$.ajax({
type: "POST",
url: "./api/login.php",
data: dataString,
cache: false,
success: function(data){
if(data){
//FUNCTION CALL WHEN USER LOGGING IN
retrieveUserBlogData();
window.location = "api/home.php";
}else{
$('.alert').show();
}
}
});
function retrieveUserBlogData(){
$.ajax({
type: "GET",
url: 'retrievePostData.php',
data: "",
dataType: 'json',
success: handleData
});
}
function handleData(data) {
alert(data);
var blog_file = data[3];
$('#imageDiv')
.append('<img id="blog_img" src="upload/' + blog_file + '"><br>');
}
I cant figure out why the ajax in the retrieveUserBlogData() function is not being triggered.
Any help would be appreciated Thanks.
Even if the AJAX succeeds, you are redirecting the browser to a different page after the first AJAX request:
window.location = "api/home.php";
So I would suggest removing that.
Try the following code for redirecting to another window
window.location.assign(URL);
then it may work.
Try it like this
$.ajax({
type: "POST",
url: "./api/login.php",
data: dataString,
cache: false,
success: function(data){
if(data){
//FUNCTION CALL WHEN USER LOGGING IN
retrieveUserBlogData();
}else{
$('.alert').show();
}
}
});
function retrieveUserBlogData(){
$.ajax({
type: "GET",
url: 'retrievePostData.php',
data: "",
dataType: 'json',
success: function(data){
alert(data);
var blog_file = data[3];
$('#imageDiv')
.append('<img id="blog_img" src="upload/' + blog_file + '"><br>');
window.location = "api/home.php";
}
});
}

ajax send form request to the same page to run SQL/PHP queries

<script type="text/javascript">
$(document).ready(function(){
$("#message").hide();
$("#please_wait_box").hide();
$("#addnotification").submit(function(e){
$("#message").hide();
$("#please_wait_box").show();
e.preventDefault();
dataString=$("#addnotification").serialize();
$.ajax({
type: "POST",
url: "menu.php?addnotification=yes",
cache: false,
data: dataString,
success: function(res){
$("#please_wait_box").hide();
$("#message").html(res);
$('#message').fadeIn('slow');
$('.overlay').fadeOut();
if(res.indexOf("success")!=-1)
{
window.location.href = res.substr(8);
}
}
});
});
});
</script>
i am trying to run this ajax code to POST data to menu.php page from a submitted form
on menu.php i have
if($_GET["addnotification"] == 'yes') {
//do stuff here
echo 'form submitted';
}
but i cannot see the text form submitted
UPDATE
i have changed to this code:
<script type="text/javascript">
$(document).ready(function(){
$("#message").hide();
$("#please_wait_box").hide();
$("#addnotification").submit(function(e){
$("#message").hide();
$("#please_wait_box").show();
e.preventDefault();
dataString=$("#addnotification").serialize();
$.ajax({
type: "POST",
url: "addnotification.php",
cache: false,
data: dataString,
success: function(res){
$("#please_wait_box").hide();
$("#message").html(res);
$('#message').fadeIn('slow');
if(res.indexOf("success")!=-1)
{
window.location.href = res.substr(8);
}
}
});
});
});
</script>
and put the SQL queries on a different page, but now the please_wait_box shows and does not hide, the queries are not running at all
In your url you've got no blank, but in your php document there is a blank.
menu.php?addnotification=yes
vs
$_GET["add notification"]
You are sending a POST request and then reading the $_GET response, try changing the
type: "POST",
for
type: "GET",
in your ajax call.
and also read addnotification and not add notification (probably a typo)
Check your this part of code:
if(res.indexOf("success")!=-1)
{
window.location.href = res.substr(8);
}
You are searching for success in res whereas i think your res will be a string "form submitted". You can try calling alert(res); or console.log(res) to see what is being returned in your response.
Additional debugging process:
change your code for ajax to below:
var request = $.ajax({
type: "POST",
url: "addnotification.php",
cache: false,
data: dataString
});
request.done(function( msg ) {
$("#please_wait_box").hide();
$("#message").html(msg);
$('#message').fadeIn('slow');
if(msg.indexOf("success")!=-1)
{
window.location.href = msg.substr(8);
}
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});

Categories

Resources