Ajax call's not responding - javascript

var quoteUrl='http://api.forismatic.com/api/1.0/?method=getQuote&lang=en&format=json';
$(document).ready(function() {
var $loader = $("#btn"),
$insertion=$("#insertionPoint");
$loader.click(function() {
$.ajax({
url:quoteUrl ,
dataType: 'json',
success:function(data){
var quote=data.quoteText;
$insertion.replaceWith('<p>'+quote+'</p>');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1>Random quote Machine</h1>
<div id="insertionPoint">
<p>Quotes come here</p>
</div>
<button id="btn">Next Quote</button>
Task:To gain a quote from forimastic.com's Api
Result: Nothing is Happening
Additional:How can I add codes to make it to gain random quotes if this works?

I got it to work by using jsonp and its callback, following the manual from the API's website.
And I even made it prettier :D
var quoteUrl='http://api.forismatic.com/api/1.0/?method=getQuote&format=jsonp&jsonp=parseQuote&lang=en';
$(document).ready(function() {
$("#btn").click(function() {
$.ajax({
url:quoteUrl ,
crossDomain: true,
jsonpCallback: 'parseQuote',
dataType: 'jsonp',
success:function(data){
$("#insertionPoint>#quote").html(data.quoteText);
$("#insertionPoint>#author").html(data.quoteAuthor);
}
});
});
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<h1>Random quote Machine</h1>
<blockquote id="insertionPoint">
<span id="quote">Quotes come here</span>
<footer id="author">Author comes here</footer>
</blockquote>
<button class="btn btn-info" id="btn">Next Quote</button>
You should change #insertionPoint's html instead of replacing it, otherwise the function will no further work since this element will no longer exist.

Replace
$insertion.replaceWith('<p>'+quote+'</p>');
with
$insertion.html('<p>' + quote + '</p>');

Related

send array from js to php

I'm doing some assignment for school, and I'm stuck at passing array from js to php.
I have to say I'm not some expert and I'm still learning. I can't figure out what am I missing. Hope someone will help me.
I try like this.
if(bets.length > 0) {
$.ajax({
url: "mybet.php",
method: "POST",
data: { bets : JSON.stringify( bets ) },
success: function(res) {
console.log(res);
}
});
}
and php file
if (isset($_POST['bets'])) {
$bets = json_decode($_POST['bets'], true);
print_r($bets);
}
bets is an array in js.. and I want if I click on button proceed to collect that array and pass to php so I can work with it. I'm getting undefined index for bets on line $bets = json_decode($_POST['bets']);
print_r($_POST) is empty
You are not sending a 'proceedBet' variable in your ajax request, either you send that variable by changing the data like this:
if(bets.length > 0) {
$.ajax({
url: "mybet.php",
method: "POST",
data: { bets : JSON.stringify( bets ), proceedBet: 'Some Value' },
success: function(res) {
console.log(res);
}
});
}
Or you have to change your condition to check if the bets exist like so:
if (isset($_POST['bets'])) {
$bets = json_decode($_POST['bets'], true);
print_r($_POST['bets']); // use print_r to check the data in the array
// User::redirect("ticket.php");
}
Hi here is an example I made for you:
first the html part is a simple modal to display data from request.php if the data I send from my js array is okay:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<script
src="http://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<div class="container">
<h2>Modal Example</h2>
<!-- Button to Open the Modal -->
<button type="button" class="btn btn-primary" id="btnDisplayModal" >
Open modal
</button>
<!-- The Modal -->
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal" >×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<br>
<div id="add-takeout-messages">
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</body>
the javascript part is an ajax call which display data inside the modal when the request is done:
$(document).ready(function() {
var formData = {id:"1",name:"stan",lastname:"chacon",color:"blue"};
function _ajaxMessage(formData){
return $.ajax({
url: "request.php",
type: 'POST',
data:{data:JSON.stringify(formData)},
dataType: 'json'
})
}
$("#btnDisplayModal").on('click', function(){
_ajaxMessage(formData)
.done(function(response){
console.log(JSON.stringify(response));
$('#add-takeout-messages').empty();
$.each(response.messages,function(index,value){
console.log(index,value);
$('#add-takeout-messages').append('<div class="alert alert-success">' +
'<button type="button" class="close" data-dismiss="alert">×</button>' +
'<strong><i class="glyphicon glyphicon-ok-sign"></i></strong> From: '+ value.from + '<br>' + ' msg: ' + value.msg +
'</div>')
})
$("#myModal").modal();
})
})
})
The request.php file is simple like the request file you are already using, so I guess the problem you have is your array, maybe it has an invalid format and thats why it goes empty.
if (isset($_POST["data"])) {
$data = json_decode($_POST["data"],true);
if ($data["name"] == "stan") {
$array = [
"status"=>"success",
"messages"=> [
array('date' => "2019-04-11", 'msg'=>'Love you', 'from'=>'Annie' ),
array('date' => "2019-04-10", 'msg'=>'Have a nice day', 'from'=>'Annie' )
]
];
echo json_encode($array);
}
}
check your array ant let us know if that was the problem =)
Hiope it helps
Simple working example you can change the logic if needed.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
let bets = [1,2,3]; // This must come dynamically.
if(bets.length > 0) {
$.ajax({url: "server.php", method: "POST", data: { bets : JSON.stringify( bets) }, success: function(result){
$("#div1").html(result);
}});
}
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Send Ajax Request</button>
</body>
</html>
Server side
<?php
if (isset($_POST['bets'])) {
$bets = json_decode($_POST['bets'], true);
print_r($_POST['bets']);
}

jquery ajax next page won't load [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 4 years ago.
I have index.html where there is nav menu, header, footer and div.content where jQuery parses html of page1.html.
page1.html loads fine, but when I add function to .nextPage2 to load page2.html, it wont work.
page1.html does not have head, body and script.
$( document ).ready(()=> {
//Ajax
$.ajax({
url: 'page1.html',
dataType: "html",
success: function(result){
$('.content').html(result);
}});
$(".nextPage2").click(()=>{
$(".content").html("");
$.ajax({
url: 'page2.html',
dataType: "html",
success: function(result){
$('.content').html(result);
}});
})
//Ajax
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<nav class="navMenu">
<div class="container">
<div class="logo">
</div>
<ul>
<li class="page1">page</li>
<li class="page2">page</li>
<li class="page3">page</li>
</ul>
</div>
</nav>
<div class="container">
<div class="content">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
<!--page1.html
<section class="page1">
Bunch of code without head, script, body etc
<button type="button" class="nextPage2" name="button">page2</button>
</section>
-->
Like #Justinas said, you need http://api.jquery.com/on/
$(document).on("click",".nextPage2",()=>{
$(".content").html("");
$.ajax({
url: 'page2.html',
dataType: "html",
success: function(result){
$('.content').html(result);
}});
})

why $.ajax does not work with me?

i don't know why $.ajax never called on my code ?
i use xampp as localhost
jquery called ok , so when i click on the button , the text below it changed .. but $.ajax part never execute ?
my page :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<link rel="stylesheet" href="layout/css/bootstrap.css">
<link rel="stylesheet" href="layout/css/font-awesome.min.css">
<link rel="stylesheet" href="layout/css/mystyle.css">
</head>
<body>
<div class="container">
<div class="alert alert-danger"> alerts alerts </div>
<div class="alert alert-danger"> alerts alerts </div>
<div class="alert alert-danger"> alerts alerts </div>
<button id="btn" class="btn btn-primary">cliquer ici </button>
</div>
<script type="text/javascript" src="layout/js/jquery-1.12.4.min.js">
</script>
<script type="text/javascript" src="layout/js/bootstrap.min.js"></script>
<script type="text/javascript" src="layout/js/myjs.js"></script>
</body>
</html>
my js :
$(document).on('click','#btn',function(){
var ID =$(this).attr('id');
$(this).html("loading ... ");
$.ajax({
type:"POST",
url:"http://localhost/my_projects/testing/moremore.php",
data:"id="+ID,
success: function(html){
$('.container').append(html);
$('#btn').html("done");
}
});
$(this).html("hmmmm ... ");
});
and my moremore.php :
<div class="alert alert-success"> alerts alerts by ajax </div>
1) Look for console.log errors or errors in network header
2) Make sure you .php script where you are requesting the ajax, has major headers to allow access control.
3) Sometimes, the headers doesn't allow to make you request.
4) When making request, keep your console opened (F12) and enable Log XMLhttpRequest
Try adding these headers to you moremore.php
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Headers: X-Requested-With, Content-Type");
header("Access-Control-Allow-Origin: http://localhost");
Also to give it a try, check the ajax request with the ajax header, add this too in your moremore.php:
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
echo '<div class="alert alert-success"> alerts alerts by ajax </div>';
} else {
echo 'no ajax';
}
This will give you an idea if ajax request is working fine or not.
New ajax js:
$(document).ready(function() {
$('#btn').click(function() {
var ID = $(this).attr('id');
$(this).html("Loading ... ");
$.ajax({
type: "POST",
url: "http://localhost/my_projects/testing/moremore.php",
data: {
id: ID
},
cache: false,
xhrFields: {
withCredentials: true
},
dataType: html,
success: function(html) {
$('.container').append(html);
$('#btn').html("done");
},
error: function() {
alert("Something went wrong");
$("#btn").html("hmmmm, it was called... ");
}
});
});
});
Do leave comments for more help!
I tested your code, and it pretty much works as is. The only thing that I changed was the ajax url from absolute http://localhost/my_projects/testing/moremore.php to relative moremore.php and I threw in the official jQuery CDN in case yours was borked.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<script src="http://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="layout/css/bootstrap.css">
<link rel="stylesheet" href="layout/css/font-awesome.min.css">
<link rel="stylesheet" href="layout/css/mystyle.css">
</head>
<body>
<div class="container">
<div class="alert alert-danger"> alerts alerts </div>
<div class="alert alert-danger"> alerts alerts </div>
<div class="alert alert-danger"> alerts alerts </div>
<button id="btn" class="btn btn-primary">cliquer ici </button>
</div>
<script>
$(document).on('click','#btn',function(){
var ID =$(this).attr('id');
$(this).html("loading ... ");
$.ajax({
type:"POST",
url:"moremore.php",
data:"id="+ID,
success: function(html){
$('.container').append(html);
$('#btn').html("done");
}
});
$(this).html("hmmmm ... ");
});
</script>
<script type="text/javascript" src="layout/js/bootstrap.min.js"></script>
<script type="text/javascript" src="layout/js/myjs.js"></script>
</body>
</html>
moremore.php:
<div class="alert alert-success"> alerts alerts by ajax </div>
Results in this expected output after a couple clicks:
Try to wrap anonymous function, and change selector document to '#btn'
(function($) {
$('#btn').on('click',function(){
var ID =$(this).attr('id');
$(this).html("loading ... ");
$.ajax({
type:"POST",
url:"http://localhost/my_projects/testing/moremore.php",
data:"id="+ID,
success: function(html){
$('.container').append(html);
$('#btn').html("done");
}
});
$(this).html("hmmmm ... ");
});
})(jQuery);

How to initialize bootstraps tooltip after including with ajax?

I am loading content (HTML) to my website with ajax. This includes, inter alia, this snippet:
Hover me...
As described here: bootstrap 3 > tooltip, i need to initialize it. How can i initialize it after ajax success?
Edit: Full working example. Here i simulate an "ajax call". The problem is the duration. When you delete the timeout it would work:
<!DOCTYPE html>
<html lang="de">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">
</head>
<body>
<div id="html" style="margin-top: 50px;">
That works: Hover me 1...
</div>
<div style="margin-top: 50px;">Ajax: <span id="ajax"></span></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script>
<script type="text/javascript">
// Document ready
$(document).ready(function ()
{
loadResult();
activateTooltip();
});
// Result
function loadResult()
{
// "Ajax call"
setTimeout(function(){
var result = 'Hover me 2...';
$("#ajax").html(result);
}, 2000); // Simulate Ajax duration
activateTooltip();
}
// Tooltip
function activateTooltip()
{
$('[data-toggle="tooltip"]').tooltip();
}
</script>
</body>
</html>
https://plnkr.co/edit/KBsJK27F9Sb5kV2Ozy56
Hover me...
and reactivate tooltip function in ajax success:
function loadResult()
{
$.ajax({
type: "POST",
url: "index.php?action=loadResult",
data: "id=1",
dataType: 'text',
success: function(data){
var json = $.parseJSON(data);
$("#result").html(json.result);
activateTooltip();
}
});
}
Just add this attribute:
data-placement="right"

document.ready jquery difficulty

In the master page I have the following code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>#ViewBag.Title</title>
<link href="#Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<link href="#Url.Content("http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.css")" rel="stylesheet" type="text/css" />
<script src="#Url.Content("http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.4.min.js")" type="text/javascript"></script>
<script src="#Url.Content("http://code.jquery.com/mobile/1.0rc2/jquery.mobile-1.0rc2.js")" type="text/javascript"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
#RenderBody()
</body>
</html>
Then in the Index.cshtml I have the following code:
#{
ViewBag.Title = "Index";
}
<h2>
Index</h2>
<div data-role="page">
<div data-role="header">
...</div>
<div data-role="content">
<a id="btnShowCustomers" data-role="button" href="#secondDiv"></a>
</div>
<div data-role="footer">
...</div>
</div>
<div id="secondDiv" data-role="page">
<div data-role="content">
</div>
</div>
<script type="text/javascript">
(document).ready(function (event) {
$('#btnShowCustomers').bind('click', function (event) {
GetCustomers();
});
});
function GetCustomers() {
var webMethod = "Home/GetCustomers";
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: webMethod,
data: "{}",
dataType: "json",
success: function (dataObj) {
alert('lala');
}
});
}
</script>
Debugging with Firebug i get the following error:
document.ready is not a function
[Break On This Error] (document).ready(function (event) {
How is that possible? On document ready i want to register the handler for the button's click event.. Any suggestions?
(document).ready(function (event) {
should be
$(document).ready(function (event) {
Should be $(document).ready(function (event) ...
Notice the dollar sign prefixed to the start of the string - although this can differ, jQuery code generally uses this prefix to access its context for selectors and whatnot.
See this page for some information on utilising jQuery.
you ar missing a $
$(document).ready(function (event) {
(document).ready(function (event) {
You don't have $ or jQuery before (document), this it thinks it is calling ready directly on the document object. ready is a jQuery short cut, not a DOM method.
if you include JQuery like this:
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.1.min.js" type="text/javascript"></script>
then this should work:
$(document).ready(function() {
// Handler for .ready() called.
});
As a shortcut you can also write
$(function(){
//your code
});
which is equivalent to writing
$(document).ready(function(){
//your code
});

Categories