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

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;
?>

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.

Using ajax with laravel

I'd like to know if it's possible to use Ajax with Laravel without writing the code inside a .js file.
Script.js
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '',
data: ...
});
})
I don't know how to get the URL that I want (which is my currently page,
I just want to change the < select> value then reload the data that's already shown on the page).
Do I have to write the ajax inside my .php files? Is this a 'good practice'?
I'm asking this because I already have another script inside that same .php file.
Update
Following the answer posted by #ohgodwhy
Now nothing happens when the ajax executes.
It hits the success code but nothing happens, the URL does not change. Is it because I'm redirecting to the same page am at?
file.php
<script type="text/javascript">
$('#selectSemestres').change(function(obj){
var anoSemestre = $(this).val();
$.ajax({
type: 'GET',
url: '{{ route('professor') }}',
data: { anoSemestre: anoSemestre },
success: function(){
console.log('HELLO WORLD');
}
});
})
</script>
MyController:
public function getProfessorList()
{
$professor = Professor::all();
if( Request::ajax() )
{
echo 'yolo';
}
$semestres = Horario::distinct()->select('ano_semestre')->get()->toArray();
return View::make('professor', compact('professor', 'semestres'));
}
What I usually do is add a #yield('scripts') section to my layout that I extend.
Then in the child templates that require specific JS, I'll add that in there.
#section('scripts')
<script>
//your javascript here.
</script>
#endsection
There is 1 caveat however. If you use an #include from within a child template, and that included file has it's own javascript, it must invoke the parent first, like this:
#section('scripts')
#parent
<script>
</script>
#endsection.

how to make ajax call on same page ajax request send and get in same page

here is ajax code i'm implement this code
i want to call ajax request same page where i want to get the request mean same page send request and get request
function data(status)
{ $.ajax({
type:"post",
url:"main.php",
data: "status="+ status,
success:function(data)
{
} }); });
i'm try this code but have problem in ajax call same html page show header footer also result
how to call on self page where is ajax code how it is possible?
In your success callback, do the necessary DOM update.
"data" will contain the actual response text from thte page main.php.
Your html should look like something like this:
<html>
<head>
<title></title>
<script src=[jquery JS file]"></script>
</head>
<body>
<div id="mydiv"></div>
</body>
<script>
function data(status)
{ $.ajax({
type:"post",
url:"main.php",
data: "status="+ status,
success:function(data)
{
$("#mydiv").html(data);
}
});
}
</script>
</html>
Here is the code:
$.ajax({
url:'main.php',
mtype:'post',//use mtype as 'get' for get reuest,
contentType:'application/json',
async:true, // for asynchronous calls
sucess:function(data)
{
},
error:function(error)
{
}
});

How to get Ajax responce in Framework7?

I am new to Framework7. In this code i am not getting response from Ajax.
Guide me please.
Thanks in advance.
<!-- Path to Framework7 Library JS -->
<script type="text/javascript" src="js/framework7.min.js"></script>
<!-- Path to your app js -->
<script type="text/javascript" src="js/my-app.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
var myApp = new Framework7();
var $$ = Dom7;
$$('.form-to-json').on('click', function(){
var name = $$('#name').val();
var password = $$('#password').val();
var data = {"name":name,"password":password};
$$.ajax({
url: "validation.php",
type: "post",
data: data,
//dataType: 'json',
success: function (data)
{
alert("data");
}
});
});
</script>
Validation Page
<?php
echo "Hi";
?>
There's a slight error in your code. In the callback, you are displaying alert("data") which will always display "data". To display what's been sent from the php script, you need to change alert("data") to alert(data).

Ajax response inside a div

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);

Resources