Calling AJAX is not working onclick of button - javascript

I am calling an API from AJAX,
When I am Calling AJAX like this,
$(function (){
$.ajax({
type:'GET',
url :"/tournament",
dataType: 'json',
success: function(data) {
console.log('success',data);
},
error:function(exception){
alert('Exception:'+exception);
}
});
});
This is working fine without any errors but when I am using this..
$('#btnadad').on('click',function (){
alert("ok");
$.ajax({
type:'GET',
dataType: 'json',
url :"/tournament",
success: function(data) {
console.log('success',data);
},
error:function(exception){
alert('Exception:'+exception);
}
});
});
This popups "error" alert,
can anybody help me whats the error?
HTML Body is Like this,
<form>
<h2>
<font color="#FFFFFF">
<br><br><input type="text" name="name" placeholder ="Tournament Name"><br>
<table>
<?PHP
//print_r($teams);
for ($i = 0; $i < $count; $i++) {
?>
<tr>
<td><input type="checkbox" name=<?php echo $taemId[$i] ?></td>
<td><?php echo $teamname[$i] ?></td>
</tr>
<?php
}
?>
</table>
<button id="btnadad">ADD</button>
</form>
<script src ="/js/myjs.js"></script>
here I am calling one API and Displaying the Checkboxes Dynamically.
I am checking The Console...when I am clicking button ,the alert box is popping up and in networks tab tournament path's status is cancelled .when I am clicking it on to see the response it shows fail to load response data.
I have Tried calling this function in same html file in tag but it is also not working.
<script>
function getOnClick()
{
alert("ok");
$.ajax({
type: 'GET',
url: "http://harshal:8888/tournament",
success: function(data) {
alert("no error in alert");
console.log('success', data);
},
error: function() {
alert("error in alert");
}
});
}
and calling it on button's onclick Event ut it also gives me the same result

Thanks For the Help Friends,your Efforts matters a lot to me,I am feeling glad to tell you that I just found the answer for this the below code makes it happened ..
$('#btnadad').on('click',function (e){
alert("ok");
$.ajax({
type:'GET',
url :"/tournament",
dataType: 'json',
success: function(data) {
console.log('success',data);
},
error:function(exception){alert('Exeption:'+exception);}
});
e.preventDefault();
});

$ajax error function takes 3 parameters. Jquery ajax error
A function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred.
try changing like this
$('#btnadad').on('click',function (){
alert("ok");
$.ajax({
type:'GET',
dataType: 'json',
url :"/tournament",
success: function(data) {
console.log('success',data);
},
error:function(jqXHR,textStatus,errorThrown ){
alert('Exception:'+errorThrown );
}
});
});

I got the same issue. If you use onclick, do not use a form. In local environment, it is working, but when you go to production, the ajax request is cancelling. The solution is removing the form tag and adding a div tag.

Related

Javascript function returning with a hash in the url despite returning false

I have this link that is supposed to delete an entry and refresh a div via ajax. However, for some reason it isn't working at all and its just shifting the page up and adding a # to the url.
If I add an alert to output the id and user_id, it shows up and no # is added to the url.
This is the code
<script>
function removeExistingBranch(id,user_id){
$.ajax({
method: "POST",
url: "<?php echo site_url($this->data['controller'].'/RemoveUserBranch/'); ?>",
data:'id='+id+,
'&user_id'+user_id,
beforeSend: function () {
$('.loading').show();
},
success: function(data){
// $( "#existing_branch_container" ).load( "<?php echo site_url($this->data['controller']);?>/LoadUserBranches" );
$('.loading').fadeOut("slow");
},
});
return false;
}
</script>
Remove
Could someone take a look and see if I am missing something?
You have syntax error in the ajax call. Change it
data:'id='+id+,'&user_id'+user_id,
to
data:'id='+id+'&user_id'+user_id,

pass js variable to php using ajax on the same page

this is my html code:
<form id="form" action="javascript:void(0)">
<input type="submit" id="submit-reg" value="Register" class="submit button" onclick="showtemplate('anniversary')" style='font-family: georgia;font-size: 23px;font-weight: normal;color:white;margin-top:-3px;text-decoration: none;background-color: rgba(0, 0, 0, 0.53);'>
</form>
this is my javascript code:
function showtemplate(temp)
{
$.ajax({
type: "POST",
url: 'ajax.php',
data: "section="+temp ,
success: function(data)
{
alert(data);
}
});
}
this is my ajax.php file:
<?php
$ajax=$_POST['section'];
echo $ajax;
?>
The above html and javascript code is included in a file named slider.php. In my index file i have included this slider.php file and slider.php is inside slider folder. So basically index.php and slider.php are not inside the same folder.
Javascript code alerts the data properly. But in my php code (ajax.php file) the value of $_POST['section'] is empty. What is the problem with my code. I tried googling everything and tried a few codes but it still doesn't work. Please help me out
Try this instead:
$.ajax({
type: "POST",
url: 'ajax.php',
data: { 'section': temp},
success: function(data)
{
alert(data);
}
});
It is quite possible that your server does not understand the string you have constructed ( "section="+temp ). When using ajax I prefer sending objects since for an object to be valid it requires a certain format.
EDIT1:
Try this and let me know if it doesn't work either:
$.post('ajax.php', {'section': temp}, function(data}{
alert(data);
});
Add jquery plugin(jQuery library) ,then only ajax call works
for eg
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
check your input data , whether it contain '&,/' charators,then use encodeURIComponent()
for Ajax Call Eg:
var gym_name = encodeURIComponent($("#gym_name").val());
$.ajax({
type: "POST",
url: "abc.php",
data:string_array,
success: function(msg) {
console.log(msg);
}
});
In abc.php
<?php
$id = $_POST['gym_name'];
echo "The id is ".id;
?>
Give a try to the following (although I cannot work out why #Grimbode's answer is not working):
$("#submit-reg").on( "click", function() {
$.ajax({
type: "POST",
url: 'ajax.php',
data: {'section': 'anniversary'},
success: function(data)
{
alert(data);
}
});
});
Note: I don't know what your underlying code is doing. However, I would suggest not using HTML element properties to handle events for numerous reasons, but separate the JS/event handling appropriately (separate js file(s) (recommended) or inside <script> tags). Read more...

Ajax call (before/success) doesn't work inside php file

I have a form that when clicked the submit button makes a call via ajax. This ajax is inside a php file because I need to fill in some variables with data from the database. But I can not use the calls before / success. They just do not work, I've done tests trying to return some data, using alert, console.log and nothing happens. Interestingly, if the ajax is isolated within a file js they work. Some can help me please?
File:
<?php
$var = 'abc';
?>
<script type="text/javascript">
$(document).ready(function() {
$('#buy-button').click(function (e){
var abc = '<?php echo $var; ?>';
$.ajax({
type: 'POST',
data: $('#buy-form').serialize(),
url: './ajax/buy_form.php',
dataType: 'json',
before: function(data){
console.log('ok');
},
success: function(data){
},
});
});
});
</script>
HTML:
<form id="buy-form">
<div class="regular large gray">
<div class="content buy-form">
/* some code here */
<div class="item div-button">
<button id="buy-button" class="button anim" type="submit">Comprar</button>
</div>
</div>
</div>
</form>
----
EDIT
----
Problem solved! The error was in the before ajax. The correct term is beforeSend and not before. Thank you all for help.
You said it was a submit button and you do not cancel the default action so it will submit the form back. You need to stop that from happening.
$('#buy-button').click(function (e){
e.preventDefault();
/* rest of code */
Now to figure out why it is not calling success
$.ajax({
type: 'POST',
data: $('#buy-form').serialize(),
url: './ajax/buy_form.php',
dataType: 'json',
before: function(data){
console.log('ok');
},
success: function(data){
},
error : function() { console.log(arguments); } /* debug why */
});
});
My guess is what you are returning from the server is not valid JSON and it is throwing a parse error.
Try this
<script type="text/javascript">
$(document).ready(function() {
$('#buy-button').click(function (e){
e.preventDefault();
var abc = '<?php echo $var; ?>';
$.ajax({
type: 'POST',
data: $('#buy-form').serialize(),
url: './ajax/buy_form.php',
dataType: 'json',
beforeSend: function(data){
console.log('ok');
},
success:function(data){
}
});
});
});
And make sure that your php file return response

Can't process simple form submitted by jQuery ajax

My form:
<form id="new-protocol-form" method="post" role="form">
<textarea name="text"></textarea>
</form>
My jquery ajax:
$('#submitProtocol').click(
function() {
$.ajax({
type: "POST",
url: "newProtocol.php",
data: $('#new-protocol-form').serialize(),
success: function() { alert{'ok'} },
error: function() { alert('error'); }
});
}
);
My newProtocol.php:
<script>
alert(<?php echo $_POST['text']; ?>);
</script>
Alert window with 'ok' text triggered by ajax 'success' method is shown, but I can't get alert window with $_POST['text'] value from newProtocol.php file. No error in javascript console.
You need to use $_POST['text']. You're using parentheses where you shouldn't be.
In addition, since you're using AJAX you probably don't want to navigate to the other page. Your alerts in your success function will never fire if you don't prevent the default behavior.
newProtocol.php
<?php
echo $_POST['text'];
?>
jQuery
$('#submitProtocol').click(function(event) {
event.preventDefault(); // stop the default click behavior
$.ajax({
type: "POST",
url: "newProtocol.php",
data: $('#new-protocol-form').serialize(),
success: function(data) {
console.log(data); // show the text being returned
},
error: function() { console.log('error'); }
});
}
);
Also, quit using alert() for getting return values and trouble-shooting.
First, $_POST is not a function, it's an array. So it should be $_POST['text']. Also,
<script>
alert(<?php $_POST('text'); ?>);
</script>
will not create an alert like you expect since an async request does not run any javascript in the target page.
Since you're trying to test if the AJAX is working, the best way is to check what was the date returned from that request. Example:
//...
success: function(data) { console.log(data) },
//...

ajax form submission refreshes page

I'm working on this project and am attempting to make a call to a controller function without performing a page refresh. I tried setting up an ajax function in order to do this but haven't had any luck. I've placed the related script both in the html and in a separate jquery.js but to no avail. It appears as if the form submission just isn't hitting the script at all. Any help would be greatly appreciated!! The form is in a cshtml file, controller in .cs, and script in .js
the form in question:
<form id="tableForm" action="#(Url.Action("AddToOrder", "Order"))" method="post">
#{foreach (var item in (IList<Item>)ViewData["items"]){
<input type="hidden" id="#("item_id_" + item.id)" name="#("item_id_" + item.id)" value="#item.id" />
<tr>
<td>#item.description</td>
<td>#String.Format("{0:C}",item.price)</td>
<td><input type="text" id="#("item_quantity_" + #item.id)" name="#("item_quantity_" + #item.id)" style="width: 50px;" value="0" /></td>
</tr>
}}
<tr>
<td><input class="submit" type="submit" value="Add item(s) to order" /></td>
</tr>
</form>
the script in question:
$('#tableForm').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
cache: false,
url: $(this).attr('action'),
data: $(this).serialize(),
succes: function (data) {
alert(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
To reiterate, the controller and method are working great, but the form submission refreshes the page.
refer the below code, call the preventdetfault after the submission
$('#tableForm').submit(function (e) {
$.ajax({
type: "POST",
cache: false,
url: $(this).attr('action'),
data: $(this).serialize(),
succes: function (data) {
alert(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
e.preventDefault();
});
Is your AJAX method getting called on page submission. Try adding an alert to confirm that.
You might want to add ClientIdMOde="static" to your form tag, so that if it is with in master page the control id will be static and JS can bind to it.
May be clientidmode will do the trick.
Let me know if it doesn't
Without your full page shown, I can only make an educated guess: that you have included your .js file at the top of the page or in the head element.
That means that the following code does nothing (returns an empty jQuery object):
$('#tableForm')
That is because the code runs as soon as it is loaded/defined and the form element it references has not been loaded yet.
The simply solution is: to either put your JS code at the end of the body element, or wrap it in a DOM-ready event handler. The handler is preferred as you can be moved about the page without failing:
e.g.
$(function(){
// your jQuery code here can now use the DOM safely
});
which is a shortcut for this:
$(document).ready(function(){
// your jQuery code here can now use the DOM safely
});
That means you code will now look like:
$(function(){
$('#tableForm').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
cache: false,
url: $(this).attr('action'),
data: $(this).serialize(),
succes: function (data) {
alert(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
If it still fails, the usual cause in a Javascript error preceding your code (missing jQuery library include etc). You will need to show your entire page to clarify that though.

Categories

Resources