I'm creating a PHP application where I have to send a JavaScript variable to the same page and then use it in PHP. However when I run my code the output shows and is correct but it goes away and dissappears.
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { id: 1},
success: function(result) {
$('body').html(result);
console.log(result);
},
error: function() {
alert('Some error happened. Please try again!');
}
});
I accessed the posted variable via PHP post variable and the output is correct but I cant get it to stay on the screen. Is the innerHTML of my ajax.php being overwritten?
The console shows correct output also !
Are you doing something else with your html <body> element? If I were you, I'd make a new element in the body and put your results there.
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { id: 1},
success: function(result) {
$('#results').html(result);
console.log(result);
},
error: function() {
alert('Some error found. Please try again!');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<title>Title</title>
</head>
<body>
<div id="results"></div>
</body>
</html>
You are calling body attributes, try changing this line:
$('body').html(result);
To;
$("#myResult").html(result);
You can now print your response by adding this to your HTML code:
<div id="myResult"></div>
If you want to select via a Class instead:
$(".myResult").html(result);
Here, the ID selector # is replaced by the Class selector . so your div will now become:
<div class="myResult"></div>
Now try this:
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {id: 1},
success: function(result) {
// $('body').html(result);
// $(".myResult").html(result);
$("#myResult").html(result);
console.log(result);
},
error: function() {
alert('Some error found. Please try again!');
}
});
On the HTML side enter this:
<div class="myResult"></div>
Related
I am trying to work on this website that shows a list of records, and when a user clicks on one of them, he will be navigated to another page that shows the details of the record. The logic behind it is, each 'li' tag has an "id" attribute that is unique, and I can use that id to call API and fetch the detailed info for that record. However, it seems that nothing was passed back to Flask...
HTML code:
<ul class="list-group list-group-flush">
{%for i in range(0,length)%}
<li class="list-group-item" id={{res.value[i].id}}>
<h4 class="itemName">Name:{{res.value[i].name}}</h4>
<p class="itemAssetType">{{res.value[i].assetTypes[0]}}</p>
<p class="itemQualifiedName">{{res.value[i].qualifiedName}}</p>
</li>
{%endfor%}
</ul>
JavaScript code:
$(function(){
$('li').click(function(){
var elementID = this.id
var datatosend = JSON.stringify({"guid":elementID})
$.ajax({
url: '/details',
data: datatosend,
type: 'POST',
success: function(response){
window.location.href = '/details'
console.log(response); //for stackoverflow: this shows None in console
},
error: function(ts) { alert(ts.responseText) }
});
});
});
Flask code:
#app.route('/details',methods=['POST','GET'])
def details():
print (request.json) #this gives: None
print (request.data) #this gives: b''
print (request.args.get("guid")) #this gives: None
return str(request.json)
Just wondering how am I supposed to pass that id into flask?? Why is it always empty???
I am kinda new to the front end, any help is greatly appreciated.
i think you remove this part
success: function(response){
window.location.href = '/details'
console.log(response);
}
because you get some data from server and then you go another page? but your data still stands in previous page!
You need to keep stay in current page and use your data like this:
success: function(response){
console.log(response);
}
$(function () {
$('li').click(function () {
var elementID = this.id;
console.log(this.id)//for stackoverflow: this shows the id as I expected
$.ajax({
url: '/details',
data: { guid: this.id },
type: 'POST',
success: function (response) {
console.log(response);
},
error: function (error) {
console.log('failed');
console.log(error);
console.log('element id =======>',elementID)//it is work now!!!
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<li id="xyz">##click me##</li>
<script src="app.js"></script>
I want to receive judgement result from model of Azure Custom Vision by using JavaScript.
I changed JavaScript code that this site has.
https://southcentralus.dev.cognitive.microsoft.com/docs/services/eb68250e4e954d9bae0c2650db79c653/operations/58acd3c1ef062f0344a42814
But I can't.
What is wrong with my code?
I changed IterationId, application, url, content-Type, Prediction-key, and data.
These part are enclosed with {} in the code below.
<!DOCTYPE html>
<html>
<head>
<title>Human</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js">
</script>
</head>
<body>
<script type="text/javascript">
$(function() {
var params = {
// Request parameters
"iterationId": "{Iteration id that showed in Performance Page}",
"application": "{My Project name of Custom Vision}",
};
$.ajax({
url: "{url that showed in "How to use the Prediction API"}" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/octet-stream");
xhrObj.setRequestHeader("Prediction-key","{my prediction key that showed in "How to use the Prediction API"}");
},
type: "POST",
// Request body
data: "D:\some name\some name\image.jpg",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
Of course, I expected showing "success".
But, the actual output is "error"......
When I changed URL that this site has(https://southcentralus.dev.cognitive.microsoft.com/docs/services/eb68250e4e954d9bae0c2650db79c653/operations/58acd3c1ef062f0344a42814) in my code, I can get Success message.
And, I also write
processData: false,
contentType: false,
in ajax in my code
Change your code to see what is the error that you get back:
(Note the new "error" parameter to the request)
$.ajax({
url: "{url that showed in "How to use the Prediction API"}" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/octet-stream");
xhrObj.setRequestHeader("Prediction-key","{my prediction key that showed in "How to use the Prediction API"}");
},
type: "POST",
// Request body
data: "D:\some name\some name\image.jpg",
error: function(xhr,status,error) {
// >>>>>>>>>>>> CHECK HERE THE ERROR <<<<<<<<<<<<
}
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
Once you have the error, it would be easier to help you.
My problem is lack of action after pressing the button. Under the button hook AJAX function.
Please a hint where I have a bug // errors.
My code:
Controller:
[HttpPost]
public ActionResult InsertCodesToDB(string name)
{
cl.InsertCodesToDB(name);
fl.MoveCodeFileToAccept(name);
string response = "Test";
return Content(response, "application/json");
}
View / Button:
<input type="button" class="btn btn-success sendCodesToDB" value="Umieść kody w bazie" data-value="#item.Name"/>
View / Script:
<script>
$('.sendCodesToDB').on('click', function () {
var name = $(this).data("value");
$.ajax({
url: '/ActualCodes/InsertCodesToDB',
type: 'POST',
dataType: 'json',
cache: false,
data: JSON.stringify({ 'name': 'name' }),
success: function (response) {
#(ViewBag.MessageOK) = response;
},
error: function () {
onBegin;
}
});
});
function onBegin() {
$('#files').hide();
$('#insertFiles').hide();
$('#loading').show();
$('#lblSelectedProductName').text('Trwa umieszczanie kodów w bazie danych. Proszę czekać ...');
$('#ttt').show();
}
</script>
Thank you in advance for your help.
You seem to not be adding the on ready function for jQuery. Try adding it before your click action and closing it before your onBegin() function, like so:
<script>
// open here
$( document ).ready(function() {
$('.sendCodesToDB').on('click', function () {
var name = $(this).data("value");
$.ajax({
url: '/ActualCodes/InsertCodesToDB',
type: 'POST',
dataType: 'json',
cache: false,
data: JSON.stringify({ 'name': 'name' }),
success: function (response) {
#(ViewBag.MessageOK) = response;
},
error: function () {
// function call missing "()"
onBegin();
}
});
});
// and close here
});
function onBegin() {
$('#files').hide();
$('#insertFiles').hide();
$('#loading').show();
$('#lblSelectedProductName').text('Trwa umieszczanie kodów w bazie danych. Proszę czekać ...');
$('#ttt').show();
}
</script>
The code in Ajax must be JavaScript. You cannot use C# code there (except to print some values). What is #(ViewBag.MessageOK) doing here:
success: function (response) {
#(ViewBag.MessageOK) = response;
},
If you want to display the response in a message box, try something like:
success: function (response) {
$("#your_message_id").html(response);
},
Notes: aside from that, you have several errors in your code as others pointed out in the comments.
1- Remove the quotes from the data like this:
data: JSON.stringify({ name: name }),
2- Change the error to this:
error: function () {
onBegin(); // You need "()" here
}
Or better this:
error: onBegin // You don't need "()" here
I guess you are sending data inside the AJAX call in the wrong way.
Try it like this
data: JSON.stringify({ name: name })
Hope this will help you.
I try AJAX and JSON.
I have got this very simple scripts. Could you help me to get it work?
html file
<div class="esemeny">
<h2>Event</h2>
<p></p>
<button>click</button>
</div>
json file, I call it eventresult.json
{name: whatever,
}
and the javascript file
$(function(){
$('button').on('click', function(){
$.ajax('/javascript/eventresult.json', {
dataType: 'json',
success: function(result){
var esemeny = $('.esemeny');
esemeny.find('p').html(result.name);
}
});
});
});
Thank you
You didn't tell what did want to do exactly, anyway I think, this what you want to do:
JSON:
{
name: "whatever"
}
JS:
$(function(){
$('button').on('click', function(){
$.ajax('/javascript/eventresult.json', {
dataType: 'json',
type: 'GET' // you want to get content
success: function(result){
var esemeny = $('.esemeny');
esemeny.find('p').html(result.name);
}
});
});
});
Hope that helps a bit
I guess your JSON should look like
{
name: "whatever"
}
Mind the double quotes and the unnecessary comma.
Well,you actually didn't descripte the question clearly.You can have a debug that can be seen from your firebug console,like this:
$.ajax('/javascript/eventresult.json', {
dataType: 'json',
success: function(result){
var esemeny = $('.esemeny');
esemeny.find('p').html(result.name);
}
}).fail(function(jqXHR, textStatus, errorThrown){console.log(textStatus+':'+ errorThrown)})
Here are some suggestions that should make it work:
Make sure you include the necessary script files in your html file:
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
</head>
<div class="esemeny">
<h2>Event</h2>
<p></p>
<button>click</button>
</div>
<script src="javascript.js"></script>
Make sure you use valid json in the json file
{
"name": "whatever"
}
Use .click() function in your javascript:
$(function() {
$('button').click(function() {
$.ajax('/trials/eventresult.json', {
dataType: 'json',
success: function(result) {
var esemeny = $('.esemeny');
esemeny.find('p').html(result.name);
}
});
});
});
I am trying to make a stepy-form for my project. What I want to do is I want to submit all my data step by step in stepy-form so I used an AJAX request for this purpose, but When I am trying to save it it's not working. So I used noConflict Method to avoid jQuery conflicts but I still have the same problem. I am using adminEX template And Not getting any error message. So can anyone help me?
<script src="ajax/jquery.min.js"></script>
<script>
$.noConflict();
Jquery(document).ready(function(){
$('#stepy_form').click(function(){
$.ajax({
type: 'POST',
url: 'ajax/insert_all.php',
data: {
txtVehicleNo: txtVehicleNo,
SltType: SltType,
txtPANNumber: txtPANNumber,
txtManufacture: txtManufacture,
txtModel: txtModel,
txtEngineNumber: txtEngineNumber,
txtChassisNumber: txtChassisNumber,
txtOwnerName: txtOwnerName,
txtUnlaidenWt: txtUnlaidenWt,
txtGVW: txtGVW
// qid: 'form1'
},
//alert('hello');
//async: true,
//cache: false,
success: function(result) {
alert('SUCCESS');
//$('#target').html(result);
}
});
});
});
</script>
And this one is the URL ,insert_all.php
$qid = $_POST['qid'];
echo $qid;
You are not using 'no conflict' with jquery and accessing it using $. Change $ with jQuery like this
$.noConflict();
jQuery(document).ready(function(){
jQuery('#stepy_form').click(function(){
jQuery.ajax({
type: 'POST',
url: 'ajax/insert_all.php',
data: {
txtVehicleNo: txtVehicleNo,
SltType: SltType,
txtPANNumber: txtPANNumber,
txtManufacture: txtManufacture,
txtModel: txtModel,
txtEngineNumber: txtEngineNumber,
txtChassisNumber: txtChassisNumber,
txtOwnerName: txtOwnerName,
txtUnlaidenWt: txtUnlaidenWt,
txtGVW: txtGVW
},
success: function(result) {
alert('SUCCESS');
//$('#target').html(result);
}
});
});
});