Retrieving data from ajax call in controller - php

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.

Related

Sending one Jquery AJAX request, but receiving multiple requests on PHP side

I have researched dozens of answers but can't find the solution.
I have jQuery Ajax call on mouseover.
I see one log in a browser console.
But PHP side receives 2 requests.
My JS code:
$('.df_word').off("mouseover").on("mouseover", function(){
console.log("open translation_box"); //fires once on hover
get_translation($(this),$(this).html());
}
function get_translation(word_el,word_html){
console.log('get_translation'); //fires once on hover
var params = {}
params['api'] = "2.0";
params['page'] = "translate";
params['q'] = ""+word_html+"";
console.log(params); //fires once on hover
$.ajax({
type: "GET",
crossDomain: true,
contentType: 'application/json; charset=utf-8',
url: window.api_link,
data: params,
error: function( xhr, textStatus ) {
console.log(xhr.status);
},
success: function(data){
console.log(data); //fires once on hover
}
});
}
On PHP side I see 2 requests within the same second (I save every request to the database).
What am I missing?

Ajax form not being submitted

I am attempting to send a very simple login form from a jQuery Modal form.
$( "#dialog-form" ).dialog({
var url = "../scripts/sign_up.php";
$.ajax({
type: "POST",
url: url,
data: $("#dialog-form").serialize(),
success: function(data){
alert("it works")
}
});
});
This is my first real shot at trying Ajax and I am having issues getting the success method to go through. I have checked that my script is in the right place and that the dialog_form has the right id.
Am I sending this information incorrectly? Is there a good way to troubleshoot Ajax requests?
Right now I am just trying to get the info to go through and, to simply the question, removed other code for the form.
First, I might reccommend adding an error function to your Ajax request as well - it may help with error handling:
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
Second, how are you sending data back from the script to the Ajax request? If you're not echoing back any data from your script, the request is not going to know that the script ran sucessfully.
Therefore, you may want to add the following to your AJAX call:
dataType: "json",
And then return data from your PHP script like so:
$data = array("success"=> true);
echo json_encode($data);
exit;
In full (using your script):
$( "#dialog-form" ).dialog({
var url = "../scripts/sign_up.php";
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: $("#dialog-form").serialize(),
success: function(data) {
if (data.success) {
alert("it works")
}
else {
alert("it failed, but no server error!");
}
}
error: function (jqXHR, textStatus, errorThrown) {
alert("server error");
alert(textStatus);
alert(errorThrown);
}
});
});

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();
}
....
....
});

Difficulty displaying error message using AJAX jQuery API and 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!"}

How to return a value to javascript after posting via ajax (Jquery)

I'm sending data via ajax (jquery) to php where it will be processed. I'd like to return a value from the php script, but I'm not sure how.
How do I return the result back?
$(document).ready(function() { //This script sends var Score to php
Score=100; //Dummy variable
$.ajax({
type: "POST",
url: "returnresults.php",
data: { 'Score':Score },
success: function(){
$('#box2').html(Score);
}
})
});
Very simple PHP CODE
<?php
$Score=$_POST['Score'];
if (isset($_POST['Score'])) {
$Score=80;
}
?>
Your PHP page should output the html or text that you want returned, so at its simplest perhaps add this to the end of your PHP:
echo $Score;
If you want to pre-format it a bit within your PHP then:
echo "<div>" . $Score . "</div>";
Where you can make the html markup as simple or complicated as appropriate (the <div> in this case being just an example, obviously).
Then your jQuery ajax call will automatically pass the response through as a parameter to your success handler, so:
$.ajax({
type: "POST",
url: "returnresults.php",
data: { 'Score':Score },
success: function(data){ // <-- note the parameter here, not in your code
$('#box2').html(data);
}
});
(data will be the response).
Note: if you know that the only thing you want to do with the response from the ajax call is to take the data/text/html and put it into a particular element you can simplify things by just using the jquery .load() method instead of $.ajax():
$('#box2').load("returnresults.php", { 'Score':Score });
Check the documentation. In particular with respect to the success handler function:
success(data, textStatus, jqXHR)
A function to be
called if the request succeeds. The function gets passed three
arguments: The data returned from the server, formatted according to
the dataType parameter; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object.
So jQuery will pass three parameters to your success function. The first one contains the data that you want. If you just want to pass exactly what the server returns on into your success handler, you can do:
$(document).ready(function() { //This script sends var Score to php
$.ajax({
type: "POST",
url: "returnresults.php",
data: { 'Score':Score },
dataType: "text", //set the dataType to 'text' so that jQuery passes it verbatim
success: function(newScore){ //the first parameter will contain the response the server sent, we ignore the other two parameters in this example
$('#box2').html(newScore);
}
})
});
And then in your PHP code, just write the desired value straight to the response.
$(document).ready(function() { //This script sends var Score to php
Score=100; //Dummy variable
$.ajax({
type: "POST",
url: "returnresults.php",
data: { 'Score':Score },
success: function(response){
alert(response);
$('#box2').html(Score);
}
})
});

Categories