Ajax response inside a div - ajax

I am trying to show the value of ajax response inside a div and for that I have the following code in my view file.
<script type="text/javascript" src="MY LINK TO JQUERY"></script>
<script type="text/javascript">
$(function(){ // added
$('a.vote').click(function(){
var a_href = $(this).attr('href');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>contents/hello",
data: "id="+a_href,
success: function(server_response){
if(server_response == 'success'){
$("#result").html(server_response);
}
else{
alert('Not OKay');
}
}
}); //$.ajax ends here
return false
});//.click function ends here
}); // function ends here
</script>
<a href="1" title="vote" class="vote" >Up Vote</a>
<br>
<div class="result"></div>
my Controller (to which the ajax is sending the value):
function hello() {
$id=$this->input->post('id');
echo $id;
}
Now what I am trying achieve is get the server_response value (the value that is being sent from the controller) in side <div class="result"></div> in my view file.
I have tried the following code but its not showing the value inside the div.
Could you please tell me where the problem is?

The problem is that you have mixed arguments of Ajax success handler. First goes data which your script gives back, then goes textStatus. Theoretically it can be "timeout", "error", "notmodified", "success" or "parsererror". However, in success textStatus will always be successful. But if you need to add alert on error you can add error handler. And yes, change selector in $("#result") to class. So corrected code may look like this:
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>contents/hello",
data: "id=" + a_href,
success: function(data, textStatus) {
$(".result").html(data);
},
error: function() {
alert('Not OKay');
}
});​

success: function(server_response) {
$(".result").html(server_response);
}​
<div class="result"></div> // result is the class
The selector should be .result not #result

Try changing <div class="result"></div> to <div id="result"></div>, because that's what you're referencing in your ajax success function
$("#result").html(server_response);

Related

Admin ajax in wordpress is not working

I am using admin ajax but it is not working. Kindly, help me to find out the problem. Here is jquery code
jQuery(document).ready(function($) {
jQuery('#newPostsForm').submit(ajaxSubmit);
function ajaxSubmit(){
var newPostsForm = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
}
});
return false;
}
}):
If I alert the var "newPostsForm" , it shown the posted values.but it is now proceeding to ajax. Here is the from I am using
<form type="post" action="" id="newPostsForm">
<input type="hidden" name="action" value="addPosts"/>
<!-- input fields -->
</form>
An here is the WordPress function I am using. this function is another file. HTML and javascript are in same file
function addPosts(){
echo "<pre>";
print_r($_POST);
die();
}
add_action('wp_ajax_addPosts', 'addPosts');
add_action('wp_ajax_nopriv_addPosts', 'addPosts'); // not really needed
Check to see if the script is getting processed by PHP before it is sent to the client. Change the code to something similar to this:
jQuery(document).ready(function($) {
jQuery('#newPostsForm').submit(ajaxSubmit);
function ajaxSubmit() {
var newPostsForm = jQuery(this).serialize();
var url = "<?php echo admin_url('admin-ajax.php'); ?>";
alert("Submitting to URL: " + url);
jQuery.ajax({
type:"POST",
url: url,
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
},
error: function (xhr, status, err) {
alert("Got status " + status + " and error: " + err);
}
});
return false;
}
});
If you get an actual URL like https://mysite.example.org then check that the URL goes to a valid location. If you get <?php echo admin_url('admin-ajax.php'); ?> then your code is not getting processed by PHP, and the AJAX call will fail because you are not using a valid URL.
The problem seems that the AJAX URL is not accessible in JS code. If the JS code written into a PHP page then only the code will work. Because the PHP code cant be executed into the JS files.
NOW the solution is to localized the JS file. Please follow the code.
wp_localize_script( 'handle', 'settings', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
Write the above code just under where you have enqueued your js file.
NOW in JS file :
jQuery.ajax({
type:"POST",
**url: settings.ajaxurl,**
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
}
});
Hope it will work at your choice.

Why is my attempt at a basic Ajax script not working?

I'm currently trying to learn the basics of Ajax through example. By following a basic tutorial, I've managed to create the following script:
<!DOCYTPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
$(function(){
$('#mybtn').on('click', function(e){
e.preventDefault();
$('#mybtn').fadeOut(300);
$.ajax({
url: 'ajax-script.php',
type: 'post',
}); // end ajax call
});
</script>
</head>
<body>
<a href='#' id='mybtn'>click me</a>
</body>
</html>
Combined with a simple php file named ajax-script.php which contains the following code:
<?php
if($_POST) {
echo "<p>ok</p>";
}
?>
Can anyone identify what I might have done wrong? How can I make this work?
You don't have a success function - that's where the echo'd PHP data will be received.
Also, you need to close the script tag that loads the jQuery library, and use a different script tag to delineate the javascript code.
Try this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(function(){
$('#mybtn').on('click', function(e){
e.preventDefault();
$('#mybtn').fadeOut(300);
$.ajax({
url: 'ajax-script.php',
type: 'post',
success: function(d){
alert(d);
}
}); // end ajax call
});
</script>
Also, your if ( $_POST ) could cause problems -- either remove that, or post some data:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(function(){
$('#mybtn').on('click', function(e){
e.preventDefault();
$('#mybtn').fadeOut(300);
$.ajax({
url: 'ajax-script.php',
type: 'post',
data: 'test=Hello',
success: function(d){
alert(d);
}
}); // end ajax call
});
</script>
Then, you could get your PHP to echo what you sent, thus:
<?php
if($_POST) {
$recd = $_POST['test'];
echo 'PHP side received: ' . $recd;
}
?>
To prevent the first answer from becoming too monolithic, I will respond to your comment in this new answer.
A few things to try:
(1) Location of your ajax.php file -- is it in the same folder as the page with the javascript code?
(2) Name of the ajax.php file -- note that in your code it is ajax-script.php
(3) I added an alert after the button click -- did that come up?
(4) I removed the IF condition -- the ajax.php file will echo something back to the javascript success function no matter what.
(5) To ensure that jQuery is working, I added jQuery code to colorize the background. If background not slightly orangish, jQuery is not loading.
Did this fix it?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(function(){
$('body').css('background','wheat');
$('#mybtn').on('click', function(e){
alert('Button clicked'); //<==========================
e.preventDefault();
$('#mybtn').fadeOut(300);
$.ajax({
url: 'ajax.php',
type: 'post',
data: 'test=Hello',
success: function(d){
alert(d);
}
}); // end ajax call
});
</script>
Then, you could get your PHP to echo what you sent, thus:
<?php
$recd = $_POST['test'];
echo 'PHP side received: ' . $recd;
?>

Yii :My view file does not opens on ajax call

I have a button in my form .i am passing some parameters to another form on button click.
My code is
<?php echo CHtml::link('newForm',"",
array('class'=>'btn btn-success',
'onclick'=>'test()'
));?>
My js code is like this:
<script type="text/javascript">
function test(){
$.ajax({
type: 'POST',
url: '<?php echo $this->createUrl('company/registration'); ?>',
data:{ids:values},
success:function(data){
}
error: function(data) {
alert("Error occured.please try again");
}
});
</script>
My controller code is:
public function actionRegistration()
{
$arrList=array();
$arrList=$_POST;
$model=new Registration;
$this->render('_newRegistration',array('model'=>$model,));
}
Here my view doesnot open.What is problem with my code???
If i understood you correctly, this few things does matter
1.Do you want open another file in modal popup (bootstrap)?
2.And in your controller you should use renderPartial instead of render.
3.and in your ajax success function you should render the data to the modal popup body
so your code in controller something like .
public function actionRegistration()
{
$arrList=array();
$arrList=$_POST;
$model=new Registration;
$this->renderPartial('_newRegistration',array('model'=>$model));
}
and in your ajax success function (if you are using modal popup),then your code something like
$.ajax({
type: 'POST',
url: '<?php echo $this->createUrl('company/registration'); ?>',
data:{ids:values},
success:function(data){
$("#your_modal_popup_id").html(data);//bootstrap modal popup
$("#your_modal_popup_id").modal('show');//bootstrap modal popup
}
error: function(data) {
alert("Error occured.please try again");
}
});
hope this help you

when ajax post success i want to refresh a particular <div> in page

i want to refresh a particular div on ajax success, im using the below code but the whole page getting refreshed.
<script type="text/javascript">
$('#post_submit').click(function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('#post_text').val()
};
$.ajax({
url: "<?php echo site_url('/post_status'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
return false;
});
return false;
});
</script>
you have an extra return false which is inside the $.ajax block which most probably causes an error so your form isn't submitted via ajax. If you remove that, you shouldn't have any issues.
Use the submit event of the form and remove the return false from the ajax callback:
$('#myFormId').on('submit', function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('#post_text').val()
};
$.ajax({
url: "<?php echo site_url('/post_status'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
});
return false;
});
Remove the return false from inside your $.ajax function. Its a syntax error. The $.ajax function only expects a json object as an argument. "return false" cannot be part of a json object. You should keep the JavaScript console open during testing at all times - Press Ctrl-Shift-J in Chrome and select console to see any JS errors.
Also suggest you use <input type=button> instead of <input type=submit> or <button></button>

ASP.NET MVC invoking webservice through AjaxOptions.Url

Say I wanted to invoke the following url that returns Json through an Ajax call:
http://open.mapquestapi.com/nominatim/v1/search?format=json&json_callback=renderBasicSearchNarrative&q=westminster+abbey"
How does on go about doing this?
I tried using the AjaxOptions.Url like this:
<span id="status">No Status</span>
<div>
#Ajax.ActionLink("Test", null, null,
new AjaxOptions
{
UpdateTargetId = "status",
Url = "http://open.mapquestapi.com/nominatim/v1/search?format=json&json_callback=renderBasicSearchNarrative&q=westminster+abbey"
})
</div>
but the url does not get invoked when i click on "Test" link.
I also tried:
<div>
<button value="get closest POI" onclick="testNominatim()"></button>
</div>
<script type="text/javascript">
function testNominatim() {
alert("called");
$.ajax(
{
type: "GET",
url: "http://open.mapquestapi.com/nominatim/v1/search?format=json&json_callback=onGetNominator&q=westminster+abbey",
contentType: "application/json; charset=utf-8",
dataType: "json",
failure: function (msg) {
alert(msg);
},
success: function (msg) {
alert(msg);
} });
function onGetNominator(msg) {
alert(msg);
}
</script>
When I click on button, message box shows but webservice does not get invoked.
I am probably missing something trivial but what is it?
TIA.
Edit 1 Changes to reflect actual script.
Using the second form would be my proposed solution. Note that the service requires a parameter named json_callback instead of the standard callback parameter for the callback function. This requires a bit of extra set up in the AJAX call.
Try the following. Note that I've changed the handler to apply it using code rather than in the markup. That's a better practice. I'm also using jQuery 1.7+. JSFiddle can be found at: http://jsfiddle.net/xVBBN/
<div>
<button>get closest POI</button>
</div>
<script type="text/javascript">
$(function() {
$('button').on('click',function() {
alert('called');
$.ajax({
type: 'GET',
url: 'http://open.mapquestapi.com/nominatim/v1/search?format=json&q=windsor+[castle]&addressdetails=1&limit=3&viewbox=-1.99%2C52.02%2C0.78%2C50.94&exclude_place_ids=41697',
dataType: 'jsonp',
jsonp: 'json_callback',
success: function(data) {
alert(data[0].place_id);
}
});
});
});
</script>
Try the following:
<div>
<button onclick="testNominatim()">get closest POI</button>
</div>
<script type="text/javascript">
function testNominatim() {
$.ajax({
type: "GET",
url: "http://open.mapquestapi.com/nominatim/v1/search?format=json&json_callback=onGetNominator&q=westminster+abbey",
dataType: "jsonp"
});
}
function onGetNominator(msg) {
alert(msg[0].place_id);
}
</script>
Things to notice (compared to your original code):
dataType: "jsonp"
you don't need a success callback because the success callback is your onGetNominator function
you don't need contentType: 'applicatin/json' because you are not sending a JSON request
or if you wanted to use an anonymous success callback:
<div>
<button onclick="testNominatim()">get closest POI</button>
</div>
<script type="text/javascript">
function testNominatim() {
$.ajax({
type: "GET",
url: "http://open.mapquestapi.com/nominatim/v1/search?format=json&json_callback=?&q=westminster+abbey",
dataType: "jsonp",
success: function (msg) {
alert(msg[0].place_id);
}
});
}
</script>
Things to notice (compared to your original code):
json_callback=? in the query string which will be replaced by jQuery with a random name allowing to invoke the anonymous success callback
you no longer need the onGetNominator function because we use the anonymous success callback
you don't need contentType: 'applicatin/json' because you are not sending a JSON request
And as far as the Ajax.ActionLink helper is concerned, I don't think that it support JSONP.

Resources