Jquery Add Argument to Function on $.ajax - javascript

I want to return my button value if ajax failure.
This HTML (on PHP):
<a href="javascript:void(0);" id="follow-topic" value="7">
<button class="btn btn-xs btn-primary pull-right"><?php echo $_LANGS['forum']['follow']; ?></button>
</a>
This JS (on PHP):
$("#follow-topic").click(function(event) {
var topicid = $(this).attr('value');
var button_follow_html = $(this).html();
if ($(this).is("a[disabled]")){ return false; }
$("#follow-topic button").html('<?php echo $_LANGS['system']['loading_button']; ?>');
$(this).attr({ disabled: true});
$.ajax({
url: "",
data: { follow_topic: topicid },
type: "POST",
success: function (data) {
$("#follow-topic").html(data);
$("#follow-topic").attr({ disabled: false});
},
error: function(data, button_follow_html) {
handleRequestError(data);
$("#follow-topic").attr({ disabled: false});
$("#follow-topic").html(button_follow_html);
}
});
});
I've change a button value to $_LANGS['system']['loading_button'] but i want return to $_LANGS['forum']['follow'] if ajax failure or client lost connection.
This system using multiple languages and if ajax is success, button will be replaced to followed button so i can't use $("#follow-topic button").html('<?php echo $_LANGS['forum']['follow']; ?>');.
Sorry for My English and Thank you

From jQuery documentation, the error function called if ajax call fails takes 3 parameters:
error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown )
So you are actually getting the textStatus respond in your button_follow_html variable in this code:
error: function(data, button_follow_html) {
handleRequestError(data);
$("#follow-topic").attr({ disabled: false});
$("#follow-topic").html(button_follow_html);
}
The parameters are optionnal, so instead you can just do:
error: function(data) {
handleRequestError(data);
$("#follow-topic").attr({ disabled: false});
$("#follow-topic").html(button_follow_html);
}
button_follow_html won't be redefined and will still have the same value as before the ajax call so you can use it as is.

Related

Data is empty when passing a variable from JS to PHP with Ajax

I'm trying to pass a simple string variable with an onclick event, the request is successful but I get an empty response on the console, and the xvar variable is no coming through so I get the "NO DATA" p tag. This is my first time using Ajax so I tried to make it very simple to start. Here's my code:
JS
var xvar = 'D';
$('.test').click( () => {
$.ajax({
data: { xvar : xvar },
type: "POST",
url: 'test.php',
success: function(data, textStatus, XMLHttpRequest)
{
console.log('Success: '+data)
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log("The request failed."+errorThrown);
}
});
});
test.PHP
$xvar = (isset($_POST['xvar'])) ? $_POST['xvar'] : '<p>NO DATA</p>';
echo $xvar;
I'm using JQuery 3.5.1 that is included with Wordpress. I'll appreciate any feedback.
EDIT
I managed to get the response on test.php as seen
here:
But I when I try to render the value with print_r is not shown.
$res = $_POST;
print_r($res);
On the data of your Ajax, try to add the quotes in the key of the data. Like this:
data: { "xvar" : xvar },

jQuery $.ajax and jQuery UI dialog: Uncaught TypeError: Illegal invocation?

I am trying to send an AJAX request when I click a jQuery UI dialog Save button and this is how I am doing it:
$(function () {
var comment_dlg = $('#add_comment_dialog');
var quote_id = $('#comment_quote_id');
$('#order_push').click(function () {
quote_id.val($(this).data('id'));
comment_dlg.dialog('open');
});
comment_dlg.dialog({
title: "Write a comment",
autoOpen: false,
modal: true,
width: 600,
height: 300,
buttons: {
Cancel: function () {
$(this).dialog('close');
},
'Save': function () {
$.ajax({
url: Routing.generate('push_order_xml'),
method: 'GET',
data: { quote_id: quote_id },
cache: false
}).done(function (data, textStatus, jqXHR) {
if (data.success.length) {
alert(data.success);
} else {
alert('Something went wrong!');
}
});
}
}
});
});
But I am getting this error:
Uncaught TypeError: Illegal invocation
I am not sure where the issue is. I have checked jQuery UI Dialog and jQuery $.ajax docs several times and my code seems to be right.
Any ideas?
Ok, finally and thanks to this answer I figure it out where the problem was coming from.
First thing, because of this:
var quote_id = $('#comment_quote_id')
the value of quote_id was the whole HTML on not a value as I expected to be.
Second, I was assigning a value to $('#comment_quote_id') right here:
quote_id.val($(this).data('id'));
which is correct.
Third, again my mistake was to use quote_id here:
data: { quote_id: quote_id }
which is - again - wrong because is the whole HTML and not the value itself.
The solution, use quote_id.val() Ex:
data: { quote_id: quote_id.val() }
I can't use processData: false because I don't want to pass the HTML but the value.

How to pass hidden field value via ajax to codeigniter controller

I have a view file which contains a button (link):
<a href id="savebutton" class="btn btn-warning">Save</a>
Somewhere else in this view I have also declared some hidden fields in a form that contain my userid and vacancyid.
echo form_input(dataHiddenArray('userid', $this->auth_user_id));
echo form_input(dataHiddenArray('vacancyid', $vacancydetails[0]->vacancy_id));
These hidden fields translate to:
<input type="hidden" value="2" class="userid">
<input type="hidden" value="1" class="vacancyid">
Now I want to be able to send these values to my controller (via AJAX) so that I can insert them in my database.
My JS file looks like this:
$(function() {
var postData = {
"userid" : $("input.userid").val(),
"vacancyid" : $("input.vacancyid").val()
};
btnSave = $('#savebutton'),
ajaxOptions = {
cache: false,
type: 'POST',
url: "<?php echo base_url();?>dashboard/vacancy/saveVacancy",
contentType: 'application/json',
dataType: 'text'
};
btnSave.click(function (ev) {
var options = $.extend({}, ajaxOptions, {
//data : $(this).closest('form').serialize()
data: postData
});
ev.preventDefault();
// ajax done & fail
$.ajax(options).done(function(data) {
alert(data); // plausible [Object object]
//alert(data[0]); // plausible data
console.log(data); // debug as an object
}).fail(function (xhr, status, error) {
console.warn(xhr);
console.warn(status);
console.warn(error);
});
});
And my controller looks like this (it is not doing much because it doesn't return anything):
public function saveVacancy() {
//$this->load->model('user/usersavedvacancies_model');
/*$data = array(
'userid' => $this->input->post('userid'),
'vacancyid'=>$this->input->post('vacancyid')
);*/
echo $this->input->post('userid');
}
Minor changes to javascript
$(function () {
var postData = {
"userid": $("input.userid").val(),
"vacancyid": $("input.vacancyid").val()
};
btnSave = $('#savebutton'),
ajaxOptions = {
type: 'POST',
url: "<?php echo base_url('dashboard/vacancy/saveVacancy);?>",
dataType: 'json'
};
btnSave.click(function (ev) {
var options = $.extend({}, ajaxOptions, {
//data : $(this).closest('form').serialize()
data: postData
});
ev.preventDefault();
// ajax done & fail
$.ajax(options).done(function (data) {
console.log(data); // debug as an object
if (data.result === 'success') {
alert("Yeah, it saved userid " + data.userid + " to vacancy id " + data.vacancyid);
}
}).fail(function (xhr, status, error) {
console.warn(xhr);
console.warn(status);
console.warn(error);
});
});
});
In the controller
public function saveVacancy()
{
//assigning a more useable object name to the model during load
$this->load->model('user/usersavedvacancies_model', 'save_vacancy');
$data = array(
'userid' => $this->input->post('userid'),
'vacancyid' => $this->input->post('vacancyid')
);
//send data to model and model returns true or false for success or failure
$saved = $this->save_vacancy->doSaveId($data); //yes, I made up the method, change it
$result = $saved ? "success" : "failed";
echo json_encode(array('result' => $result, 'userid' => $data['userid'], 'vacancyid' => $data['vacancyid']));
}
You need to understand that $.ajax takes two methods i.e GET and POST and from the documentation you can see that default method is GET so Since you have not defined method as GET/POST probably the method is taken GET so first change define ajax method to POST as well as you need to be clear about dataType of ajax it may be one of JSON/html and default is json.
$.ajax({
method: "POST",
url: url,
data: data,
dataType:'html'
});
I guess this helped you can learn detail from
Learn more.

Laravel ajax delete request

so here is my delete button
<button class="btn btn-danger btn-xs btn-delete delete" value="{{$post->id}}">Delete</button>
then the ajax request
<script type="text/javascript">
$(document).ready(function(){
$('.delete').click(function(){
var id = $(this).val();
alert(id);
$.ajax({
type: "DELETE",
url: "{{route('delete_post')}}",
data: { id: 1 },
success: function (data) {
console.log(data);
$("#task" + id).remove();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
the route
Route::get('delete_post','PostController#getDeletePost');
then the controller:
public function getDeletePost($post_id)
{
$post = Post::where('id', $post_id)->first();
$post->delete();
return redirect()->route('dashboard')->with(['message' => 'Successfully deleted!']);
}
so please help me identfy why nothing really happens when i press the delete button
I have modified you javascript, first issue in your code is,you must either use get request or post request, second issue you are not using named route in order call url for ajax like {{ route() }} , it should be {{ url('path') }} or name your route..
<script type="text/javascript">
$(document).ready(function(){
$('.delete').click(function(){
var id = $(this).val();
alert(id);
$.ajax({
type: "get",
url: "{{ url('/') }}",
data: { id: 1 },
success: function (data) {
console.log(data);
$("#task" + id).remove();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
You are sending a DELETE request type in your Ajax call, which would require a _method parameter with a value of DELETE added to your AJAX data. Your route is a GET route, so that is why you are seeing no action
Another problem is in your blade syntax you are referencing a named route 'delete_post', but that is your URL, not the route name. You have not named the route from what you have posted
Try updating this line in your routes file and that should allow the request to make it to your controller method.
Route::post('delete_post','PostController#getDeletePost')->name('delete_post');
Now you have to change your Ajax request type to
type: "POST"

How do I go back in controller?

I have forms with id's formularregister and formularadresa and one button to submit with id comanda.
I want to submit both forms with one button (<a type="submit" id="comanda" class="btn btn-default" onclick="submitForms()">Finalizare comanda</a>) and go back to controller action (zend framework 2) to validate the values from post.
My JS function is this:
function submitForms() {
$(document).ready(function() {
$("#comanda").click(function() {
$.post($("#formularregister").attr("afisarecos.phtml"), $("#formularregister").serialize() + $("#formularadresa").serialize(), function() {
});
});
});
}
You need to make an AJAX request to your controller action. You'll find a lot of examples on the Web, but the most important parts to know for using Ajax in ZF2 are:
Enable ViewJsonStrategy in your /module/Application/config/module.config.php
'view_manager' => array(
// ....
'strategies' => array(
'ViewJsonStrategy',
),
),
Ajax request in your view
$.ajax({
url : 'url/to/yourController/action',
type: 'POST',
dataType: 'json',
data : fromData,
async: true,
success:function(data, textStatus, jqXHR)
{
//success function
}
error : function(xhr, textStatus, errorThrown)
{
// error function
}
});
In your controller action
if ($request->isXmlHttpRequest()) { //ajax call
// your logic here
$jsonModel = new JsonModel(
//...
);
return $jsonModel;
}
Please see this simple example (Code + Demo) for more details.

Categories

Resources