Reload jquery plugin after ajax call - javascript

I've this code
jQuery('#select_set').on("change", function() {
var data_id = {
action: 'yasr_send_id_nameset',
set_id: jQuery(this).val()
}
//Send value to the Server
jQuery.post(ajaxurl, data_id, function(response) {
jQuery('#yasr_rateit_multi_rating').html(response);
});
});
The response that i got from ajax is something like this
Qualità birra <div class="rateit" id="yasr_rateit_multi_0" data-rateit-value="" data-rateit-step="0.5" data-rateit-resetable="true" data-rateit-readonly="false">
</div> <br />
I can output just the simple text but i can't output the div: that div call a jquery plugin called "rateit". I think that i should reload the plugin after ajax response but I've not idea how to do this. I'm a total noob in js

jQuery's post() method takes the success function as a parameter, as you've done. Just include your plugin init statement there:
jQuery.post(ajaxurl, data_id, function(response) {
jQuery('#yasr_rateit_multi_rating').html(response);
jQuery('#myElement').rateIt();
});
https://api.jquery.com/jQuery.post

Related

Wp_admin ajax request returns with response "0"

I am new to code, and trying to learn things by doing them.
Currently, I am trying to do something very simple using wordpress. which I am trying to create some posts in wordpress, using some external data.
I can fetch the data using CURL. No problem with that and post it using Wp_insert_post, directly.
But, What I want to do is trigger the wp_insert_post function on click of a button in the admin panel ( I have created this as a plugin and a separate plugin dashboard, where the button Is embedded). I have been messing around with the code, and sending the data to wp-admin-ajax.php work fine, and gives the response code 200. But, the response receiving is "0" . if the data passed through are correct, I presume, the response should be "1" ?
I have the following code at the moment.
//Button
<form id="formtesting">
<input type="text" id="name" placeholder="Name">
<input type="submit" id="user-submit" value="user-submit">
//Ajax Call
$(document).ready(function() {
var userSubmitButton = document.getElementById('user-submit');
var adminAjaxRequest = function(formData, myaction) {
$.ajax({
type: 'POST',
dataType: 'json',
url: '/wpdevelopment/wp-admin/admin-ajax.php',
data: {
action: myaction,
data: formData
},
success: function(response) {
if (true === response.success) {
alert('success');
} else {
alert(response);
}
}
});
};
userSubmitButton.addEventListener('click', function(event) {
event.preventDefault();
var formData = {
'name': document.getElementById('name').value
};
adminAjaxRequest(formData, 'data_submission');
});
});
And here is my test function // to test whether the function initiate properly, i try to send a Json error, So then I can include wp_insert_post details.
function data_submission(){
wp_send_json_error( 'I am an error' );}
add_action( 'wp_ajax_data_submission', 'data_submission' );
add_action( 'wp_ajax_nopriv_data_submission', 'data_submission' );
Could not locate where the faulty is. Some help would be appriciated
tks
Use add_action(' wp_ajax_myaction', 'yours_callback_fanc');
wp_ajax_
Remain part is yours action name that is defined into yours ajax call. In yours case it's myaction.
First this is not a standard way to use ajax in wordpress,
use wp_localize_script for embedding the global ajax_url variable,
wp_register_script('plugin-ajaxJs', plugins_url('/js/ajax-call.js', __FILE__));
wp_enqueue_script('plugin-ajaxJs');
wp_localize_script('plugin-ajaxJs', 'my_ajax_url', array('ajax_url' => admin_url('admin-ajax.php')));
Now as url in ajax you can add my_ajax_url.ajax_url,
this will send a request to admin-ajax.php.
Now coming to your question
you are returning an wp_json_error so the result is 0,
use this and return whatever data you wants in ajax success,
$responce['result'] = 1
wp_send_json( $response );

I can't set value or get value from select elements created via Ajax

I created "omarkasec" as a function and I get car brands from database via ajax and I added at the select element this car brands as options via ajax --> success.
But I can't set a value this select element.
I tried this codes for set value:
$('select[name=marka]').val('Lada');
$('select[name=marka] option[value=Lada]').prop('selected', true);
$('select[name=marka] option[value=Lada]').attr('selected', 'selected');
this codes don't work. But if I add alert(""); in "omarkasec" function the codes do work and if I remove alert(""); the codes don't work.
<div id="marka" class="gizle" >
Marka: <br>
<select name="marka" onchange="omodelsec()" size="10" ></select>
</div>
<script language='javascript' type='text/javascript'>
function omarkasec() {
$.ajax({
type: "POST",
url: "aracsor.php",
dataType: "json",
data: {
otomobilmodelyili : $("select[name=modelyili]").val(), //This work, because i created php.
},
success: function(donen){
$("#marka").removeClass("gizle");
$("#model").addClass("gizle");
$("#yakit").addClass("gizle");
$("#sanziman").addClass("gizle");
$("#cekis").addClass("gizle");
$("#kasatipi").addClass("gizle");
$("select[name=marka]").empty();
$.each(donen, function (index, otomarka) {
$("select[name=marka]").append($("<option>", {
text : otomarka,
value : otomarka,
}));
});
},
});
//if I add here alert(""); The following code works.
}
</script>
<script language='javascript' type='text/javascript'>
omarkasec();
$('select[name=marka]').val('Lada');
alert($('select[name=marka]').val()); //if I add alert(""); this code work but if I remove alert(""); this code get null value.
</script>
Ajax calls are asynchronous. Your code executes the $.ajax() call passing it a call back function, but that call back function is not executed at that very moment.
The execution immediately proceeds with the statement after $.ajax() but at that moment the content has not been loaded.
However, if you perform an alert(), the call back might eventually be triggered while the alert dialog is open, and thus content is loaded by your call back function. If you then close the popup, any code following it will find the content is there.
One way to solve this, is to use the return value of the $.ajax call, which is a promise, and chain a then call to it:
function omarkasec(oncomplete) {
return $.ajax({
// ^^^^^^
type: "POST",
url: "aracsor.php",
dataType: "json",
data: {
otomobilmodelyili : $("select[name=modelyili]").val(),
},
success: function(donen){
$("#marka").removeClass("gizle");
$("#model").addClass("gizle");
$("#yakit").addClass("gizle");
$("#sanziman").addClass("gizle");
$("#cekis").addClass("gizle");
$("#kasatipi").addClass("gizle");
$("select[name=marka]").empty();
$.each(donen, function (index, otomarka) {
$("select[name=marka]").append($("<option>", {
text : otomarka,
value : otomarka,
}));
});
},
});
}
// provide (anonymous) callback function to the `then` method:
omarkasec.then(function () {
// this code will only be executed when content is loaded:
$('select[name=marka]').val('Lada');
alert($('select[name=marka]').val());
});
You have a race condition. You are calling omarkasec() and not waiting for it to finish to execute the select.val() action. When you add the alert it "works" because it gives the code some extra time to complete the ajax call an fill the values. When you alert it, the values are already filled.
All your code that depends on the result from the ajax call must be inside the success callback.

Run JS after div contents loaded from AJAX

There are a ton of proposed answers to my question, but even with all the answers I have found, I can not seem to get any to work. I can make the JS work by adding a delay in execution of the code, but I can't rely on a delay to execute the JS after div has finished loading it's HTML.
I'm creating a page where users can search for an item, and the results are displayed in a div using AJAX. I need some JS to run after the div's html has finished loading. Some of the results data will be hidden until a user clicks on it. The JS code to accomplish this is what I am trying to run once the div finishes loading.
I have tried the following extensively with no luck anywhere:
.load
.ajaxComplete
.complete
.success
.done
Document.ready
I'm sure there are a few others as well, but my brain is just too beat up from dealing with this to remember everything I've tried so far.
My HTML:
<form name ="CardName" method="post" action="">
<div "class="w2ui-field">
<div> <input type="list" Name="CardName" id="CardName" style="width: 80%;"></div>
</div>
<div class="w2ui-buttons">
<input type="submit" name="search" style="clear: both; width:80%" value="Search" class="btn">
</div>
</form>
<div class="Results" id="Results" name="Results"></div>
My JS:
$(function() {
$("#CardSearch").bind('submit',function() {
var value = $('#CardName').val();
$.ajax({
method: "POST",
url: "synergies.php",
data: {value}
})
.success(function(data) {
$("#Results").html(data);
})
.complete(function() {
alert("div updated!"); //Trying to run JS code AFTER div finishes loading
});
return false;
});
});
If there is anything else that could help with this request just let me know!
Thanks in advance!
Note that success and failure are options that you should provide to the $.ajax call, not the returned promise. Also, bind is deprecated in favour of on since jQuery 1.7. Finally, you need to give the value that you're posting to your PHP page a key so that it can be retrieved via $_POST. Try this:
$("#CardSearch").on('submit', function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "synergies.php",
data: {
CardName: $('#CardName').val()
},
success: function(data) {
$("#Results").html(data);
},
complete: function() {
alert("div updated!"); //Trying to run JS code AFTER div finishes loading
}
})
});
You can then retrieve the value sent in your synergies.php file using $_POST['CardName'].
If you prefer to use the method provided by the returned promise, you can do that like the below, although the result is identical.
$("#CardSearch").on('submit', function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "synergies.php",
data: {
CardName: $('#CardName').val()
}
}).done(function(data) {
$("#Results").html(data);
}).always(function() {
alert("div updated!");
})
});
you can try Synchronous Ajax request, demo code is given below:
$(function() {
$("#CardSearch").bind('submit',function() {
e.preventDefault();
sendData = $('#CardName').val();
reqUrl = "synergies.php";
// this will wait until server request complete
var ajaxOpt = AjaxSyncRequest(reqUrl, sendData);
// after complete server request
ajaxOpt.done(function(data) {
$("#Results").html(data);
});
});
});
function AjaxSyncRequest(reqUrl, sendData) {
var ajaxData = $.ajax({
method: "POST",
url: reqUrl,
data: {
data: sendData
}
});
return ajaxData;
}

Div content load using Ajax and MVC 4

I have several buttons which should change content of region on the page. I've read numerous tutorials how can lazy load can be implemented using ajax, but unfortunately with no success. Here is my html:
<div>
<div>
<button id="btn_goals">Goals</button>
<button id="btn_achievements">Achievements</button>
</div>
<div id="region_content"></div>
</div>
and here is my js:
$(document).ready(function () {
$('#btn_goals').on('click', function () {
$.ajax({
url: '#Url.Action("Index", "Goals")',
success: function (data) {
$('#region_content').html(data);
}
});
});
$("#btn_achievements").on("click", function () {
......
});
});
what is the problem?
********** EDIT ************
Well, I changed url in ajax parameters from url: '#Url.Action("Index", "Goals")' to url: '/Goals/Index' and it starts work fine. What is the reason?
Try following the following steps:
Use console.log("Inside Success function"+ data); to test whether the required data is being returned from the controller method.
Use Ctrl+Shift+I in your browser to view the console. If Successful:
Use:
var div = document.getElementById("region_content");
div.innerHTML = div.innerHTML + data;
Make sure your type conversions are done right.
Also specify type: POST in your ajax function.
If you do not see 'Inside Success function' on your console, there might be something wrong with your controller function.

Put json result from php script into divs jQuery

I have two divs, each one should have a record name from a json result.
<div class="first"></div>
<div class="second"></div>
My json file is as follows :
[{"Name":"name1","Instruction":"instr"},
{"Name":"name2","Instruction":"instr again"}]
I want to put in the first div's value, the ‘Name‘ value of the first record, same for the second div but with the second record.
I'm using jQuery :
<script>
$(document).ready(function() {
$.post("data/result.php",
function(data) {
//alert("Data: " + data);
$('div.first').append(data.Name); //data.Name returns undefined
}
);
});
</script>
Any help would be appreciated.
as far as you are using post for you ajax call, the data returns as a json string, do this:
$(document).ready(function() {
$.post("data/result.php",
function(data) {
data = JSON.parse(data);
$('div.first').append(data[0].Name);
$('div.second').append(data[1].Name);
}
);
});
As previously mentioned you need to parse the result as json. You could use the built in parser in jquery. Like this:
<script>
$(document).ready(function() {
$.ajax({
url: 'data/result.php',
type: 'POST',
dataType: 'json',
success : function (data) {
$('div.first').append(data[0].Name);
}
});
});
</script>
First of all, you can give a datatype with a request:
$.post('data/result.php',function(data) { },'JSON');
If you are not posting any information, why not just use $.get ? (it's the same syntax btw)
$.post('data/result.php',function(data) {
var $first = $('div.first'),
$second = $('div.second');
$first.text(data[0].Name);
$second.text(data[1].Name);
},'JSON');
Also, if you use .append(..) it will be appended to whatever is already in the div. If that is your intention, use .append(...). However, if you want to replace the content of it, even if it is empty, use .text(...) or .html(...)

Categories

Resources