Difficulty displaying error message using AJAX jQuery API and PHP. - php

I'm using the jQuery AJAX function in order to retrieve data from my mySQL database without having to refresh the page. I have everything in working order, my query's are retrieving the correct data from my database. However, I am struggling to echo out an error message when no data can be retrieved based on the users input. I have a php file that provides the user interface for the user to search from, it also contains the following Scripts in the document head. Here is what I have so far:-
<script type="text/javascript">
$(function(){
$('#users').keyup(function(){
var inpvalue= $('#users').val();
});
});
</script>
<script type="text/javascript">
$(function(){
$('#users').keyup(function(){
var inpval=$('#users').val();
$.ajax({
type: 'POST',
data: ({p : inpval}),
url: 'data.php',
success: function(data) {
$('#output_div').html(data);
}
});
});
});
</script>
Any help would be greatly appreciated, sorry if I haven't explained myself very well.
Thankyou.

Modify your .ajax() call so you can detect error conditions:
$.ajax({
type: 'POST',
data: ({p : inpval}),
url: 'data.php',
success: function(data) {
$('#output_div').html(data);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
This is just to get you started: see http://api.jquery.com/jQuery.ajax/ for more details on what you can do with the error handler.
Of course, it's possible that you're getting a good HTTP status from the call, but this defensive programming will make sure.
A tool like Firebug running in your browser can also help you detect bad HTTP status code returns.

In data.php you have to output the error when the data is invalid.

The error setting for $.ajax will only get called if the actual ajax request has a problem like if the server returns a 404. You would have to return an error in your json and check for it like this:
$('#users').keyup(function(){
var inpval=$('#users').val();
$.ajax({
type: 'POST',
data: ({p : inpval}),
url: 'data.php',
success: function(data) {
if(!data.error) {
$('#output_div').html(data);
}
else {
// show error
}
}
});
});
And then you would return your normal json when the data is fine and then something like this for the error:
{"error": "Oh NOES!"}

Related

Ajax call returning empty data

I send an ajax call on the following URL and just echoing the response but unable to see in success function.
Where am i wrong ?
html file
$.ajax({
url: '{$PLUG_DIR}/cb_memcached/admin/ajax.php',
data: {
mode: 'videos'
},
type: 'post',
success: function(xhr) {
alert(xhr);
}
});
php file
<?php
echo "asasas";
?>
Your code seems OK. Please double check your URL. Hit your URL from browser to see response. This issue is only because of your PATH.
Issue seems to be some where in {$PLUG_DIR}. Still Call error and complete function to debug it.
$.ajax({
url: '{$PLUG_DIR}/cb_memcached/admin/ajax.php',
data: {
mode: 'videos'
},
type: 'post',
success: function(xhr) {
alert(xhr);
},
error: function(error) {
alert(error);
}
});
If you need to send data structure :
JS
$.ajax({
url: '{$PLUG_DIR}/cb_memcached/admin/ajax.php',
data: {
mode: 'videos'
},
type: 'post',
success: function(xhr) {
var param1 = xhr.param1;
alert(param1);
}
});
PHP
<?php
$response = array();
$response["param1"] = "param1";
echo json_encode($response);
?>
Please check below scenarios:
Make sure you include jquery plugin.
URL path should be correct.(In your case this may be wrong)
To check the error from ajax call please open inspect element from chrome and check the response in network tab.

Retrieving data from ajax call in controller

I have an ajax call that is sending some IDs to one of my controllers.
The jQuery that is running to do this is basically searching for elements that have an ID like notification-id- and then grabbing the IDs and storing them in a JavaScript variable.
When I alert() or console.log() this variable it prints out values like 1,2 for two notifications that I have on the page notification-id-1 and notification-id-2.
For my ajax call, I am simply doing the below:
$.ajax({
url: "{{ url('/notifications/read') }}",
method: "POST",
data: notifications, // Let jQuery handle packing the data for you
success: function(response) {
// The data was sent successfully and the server has responded (may have failed server side)
alert(notifications);
},
error: function(xhr, textStatus, errorThrown) {
// AJAX (sending data) failed
},
complete: function() {
// Runs at the end (after success or error) and always runs
}
});
I'm trying to test what my controller is receiving by doing dd($request->all()); however that is just returning:
array:1 [
"undefined" => ""
]
(The ajax call does run successfully)
How can I retrieve the ID values that are being sent in this ajax call inside my controller?
Edit: Full Script
<script type="text/javascript">
$(document).ready(function() {
var count = $('#notification-counter');
var new_notifications = $('#notification-new-counter');
$('#notification-drop-down').on('click', function() {
count.empty();
var notifications = $('[id^="notification-id-"]').map(function() {
return this.id.slice(16);
}).get();
$.ajax({
url: "{{ url('/notifications/read') }}",
method: "POST",
data: notifications, // Let jQuery handle packing the data for you
success: function(response) {
// The data was sent successfully and the server has responded (may have failed server side)
alert(notifications);
},
error: function(xhr, textStatus, errorThrown) {
// AJAX (sending data) failed
},
complete: function() {
// Runs at the end (after success or error) and always runs
}
});
});
});
</script>
$.ajax({
url: "{{ url('/notifications/read') }}",
method: "POST",
data: {'notifications':notifications},
Can you please use the following line and tell me what you get in controller ?
data: {notifications:2}. If you get this value correctly, then in your original post you are not sending notifications correctly and not getting anything in controller.

Ajax submit not working

I'll make it easy, I want to submit data without using a form, etc, etc, etc...
I have this code:
HTML
<span class="categ-edit">Edit</span>
<span class="categ-add">Add</span>
<span class="categ-delete">Delete</span>
JQUERY
$('.categ-edit').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'edit'},
});
window.location.href = "categoryactions.php";
});
$('.categ-add').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'add'},
});
window.location.href = "categoryactions.php";
});
$('.categ-delete').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'delete'},
});
window.location.href = "categoryactions.php";
});
And in categoryactions.php I have this:
PHP
<?php
$action = $_POST['action'];
echo $action;
?>
But when it redirects me to categoryactions.php I get nothing. I'm not sure if that's the way to submit data with AJAX but at least I tried. If someone knows how to fix this, I'll be grateful!
You click handler is making two separate requests. First, you are sending a request with AJAX, then you are going to the page. When you look at the page, you won't see the result because the result was given to the AJAX request.
The point of AJAX is to avoid changing the page.
Try this:
$('.categ-edit').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'edit'},
success: function(data) {
alert(data);
}
});
});
You are actually calling "categoryactions.php" twice. First as an asynchronous call (ajax) and the second time as a redirect: window.location.href = "categoryactions.php";
In the 2nd call, nothing is being posted so your output is empty. This line does not serve any purpose - you should remove it.
The ajax call happens in the background so you won't see the output from the echo in the browser. if you really want to verify it is working, replace the echo with a file call to write it to a file. Then check the file contents.
Using redirection with Ajax doesn't make sense. You need to use the success method.
$('.categ-delete').click(function() {
$.ajax({
url: 'categoryactions.php',
type: 'POST',
data: {action: 'delete'},
success: function(data){
alert(data);
//or, put response in a div
$('#someDivId').html(data);
}
});
});
The point of Ajax is to retrieve the response from a request to another page without changing the URL in the address bar. It retrieves the response for you in the variable that is the input to your success method, and then you do something with that.
Example AJAX with PHP
I can't exactly answer your question, but I will help you understand ajax requests to http server and how to handle responses accordingly.
Sample jQuery
$('.categ-edit').click(function() {
$.get('/path/to/file.php', function(data) {
console.log(data);
});
});
Sample file.php
<?php
echo json_encode('HELLO');

How to determine what a PHP page posts back to an AJAX call

I've used ajax quite a bit to send data off to a php page and get something back, but I'm not sure how to determine what specifically gets sent back. I understand what most of the fields here do, but I have a few questions as well.
My current code looks like this:
$.ajax({
url: "search.php",
type: "post",
dataType: "json",
data: {partNumber: q , newType:newType},
success: function(data) {
console.log(data);
}
});
One thing I don't fully understand is how the success: line works. When I say success: function(data), it's my understanding that I'm saying "upon success (of something? I'm not sure what), the information that is returned to this ajax function will be called data," and then inside the brackets, I'm choosing to console.log that data.
Please correct me if I'm wrong in that assumption.
Ultimately, my php page will do a ton of work and return an array with data in it. If the last line of my php code is:
$myArray = array("bob","dan","carl","mike");
how do I choose for that to be returned to ajax? The php page is working fine, but right now my console.log(data) line of code is not returning anything.
You are not supposed to return anything from the php page called by your ajax, you're supposed to echo it (i.e. write it to the response).
echo json_encode($myArray);
And if what you're echoing is not JSon, then take out dataType: "json". The success function means that the request was successful, i.e. a response was received back from the server with status 200. There is also an error method you can use for when you don't get a successful response back.
success: function(data) {
console.log(data);
},
error: function(data) {
console.log("Error: "+data);
}
1) Your on "success" is basically saying when there is not an error that occurs.
Here is testing error
$.ajax({
url: 'search.php',
success: function(){
alert('success');
},
error: function(){
alert('failure');
}
});
2) For your "data" what you echo on the php side gets returned into the variable defined in your
function(results) {
for example if you want to return an array you may want to return "echo" json
your array should include a key and a value
$myArray = array("key" => "value");
echo json_encode($myArray);
and on the jquery side parse the json object returned.
function(data) {
var obj = jQuery.parseJSON(data);
alert(obj.key);
3) Pass JSON Objects
var JSONObject= {"partNumber":q, "newType":newType};
var jsonData = JSON.parse( JSONObject );
var request = $.ajax({
url: "search.php",
type: "POST",
data: jsonData,
dataType: "json"
});

How to show Loading message instantly while using jquery ajax?

Below is my Ajax code I have made using jQuery Ajax method.
$(".loading_msg").show();
$.ajax({
type: "POST",
url: "submit_ops.php?action=submit_form",
data: $( "#frmMyForm" ).serialize(),
success: function(result){
if(result=='Success'){
$("#msgContainer").html('<div style="color:#3CA322;font-weight:bold;font-size:14px;padding:10px;">Thank you.</div>');
$("#msgContainer").fadeIn();
}
else{
$("#msgContainer").html('<div style="color:red;font-size:12px;padding:10px;">' + result + '</div>');
$("#msgContainer").fadeIn();
}
},
error: function(){
//console.log('error');
},
complete: function(){
//console.log('complete');
$(".loading_msg").hide();
$("#submit").attr("disabled", false);
}
});
So the logic is, whenever the Ajax request is about to made,
the .login_msg container is displayed first
then ajax call made
and when it is completed, again the .loading_msg is hidden.
Now the problem, it is not working smoothly as it should be. So when the ajax call is made, the browser hangs for a seconds but it doesn't show the loading message. But when the request is completed, the login message appears like for half a second and then it goes away as I have set it hidden on request completion.
So I want that the .login_msg should be shown before the request is made.
Any suggestions for this? Thanks in advance.
try using beforeSend and complete settings of $.ajax:
$.ajax({
type: "POST",
url: "submit_ops.php?action=submit_form",
data: $( "#frmMyForm" ).serialize(),
beforeSend:function(){
$(".loading_msg").show();
}
complete:function(){
$(".loading_msg").hide();
}
....
....
});

Categories