I'm trying to get some information from my php code when clicking on a button, but it doesn't connect to php.
front page is displayed in index.php
index.php:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="mystyle.css">
<script type="text/javascript" src="jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="functions.js"></script>
<title>Account Panel</title>
</head>
<div "getInfos">
<h2>In this section you can get your inforrmation</h2>
<button id="getNameBtn">Get Your Name!</button>
<span id="getNameSpan"> something must come here</span>
</div>
</body>
</html>
javascript codes and ajax are in
functions.js:
$(document).ready(function(){
$("#getNameBtn").live('click', function() {
$.ajax({
type: 'POST',
url: 'handler.php',
data:JSON.stringify({taskid = 1}),
headers: {
'content-type': 'application/json'
},
success: function(response) {
document.getElementById('getNameSpan').innerHTML = response;
},
error: function() {
alert("Error Ajaxing");
}
});
});
and php in serverside is some simple thing like this:
handler.php:
<?php
echo('Ajax successful!');
?>
You have not close the document ready function:
$(document).ready(function(){
$("#getNameBtn").live('click', function() {
$.ajax({
type: 'POST',
url: 'handler.php',
data:JSON.stringify({taskid = 1}),
headers: {
'content-type': 'application/json'
},
success: function(response) {
document.getElementById('getNameSpan').innerHTML = response;
},
error: function() {
alert("Error Ajaxing");
}
});
});
});
data:JSON.stringify({taskid = 1}),
shoulde be
data:JSON.stringify({taskid: 1}),
First of all, you should better use a newer jquery version.
There is at least one error in your Code:
data:JSON.stringify({taskid = 1})
The json should read
{taskid : 1}
Use a colon, not an equal sign. Not sure that it is true for your jQuery version, but usually data can be attached as json object already, so the whole line should work so:
data: {taskid : 1},
And the data is then visible as POST data in the PHP page. Note that the live() function is deprecated since 1.7. You can use
$("#getNameBtn").click(function(){...});
instead. Moreover, I don't think you need the headers in your request.
First important change you need to do, use $.on instead of $.live, since the latter is deprecated. Another thing you should check, if the handler.php file is at the same level as your JS/HTML file. It could be that the file is not reachable from your code. Here is what you can try:
$(document).ready(function(){
$("#getNameBtn").on('click', function() {
$.ajax({
type: 'POST',
url: 'handler.php',
data: { call: 'myAjax', taskid : 1 },
headers: {
'content-type': 'application/json'
},
success: function(response) {
$('#getNameSpan').html(response);
},
error: function() {
alert("Error Ajaxing");
}
});
});
});
And in the PHP file, you can check for the call key:
<?php
if(isset($_POST) && $_POST['call'] == 'myAjax') {
echo $_POST['taskid'];
exit;
}
?>
That exit is really important.
In your PHP file that returns JSON you should also set the header to JSON.
header("Content-Type: application/json"); //Above all HTML and returns
And the true answer to your problem has already been answered.
Related
I am new to Microsoft Cognitive services and this problem seems to have an easy fix but it has spoiled my two days. I have just copied the Computer vision for javascript code and replaced my the subscription key with mine and opened the .html file in my browser it says error.
DO I have to add something in the code
Also, I have nowt provided any image in this code what's he doing without an image?
The script code is here
<!DOCTYPE html>
<html>
<head>
<title>JSSample</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
"visualFeatures": "Categories",
"details": "{string}",
"language": "en",
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","{6e07223403d94848be20af6f126fsssd}");
},
type: "POST",
// Request body
data: "{body}",
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
code and preview of error
While it's not very obvious, in any code snippet from the Cognitive Service API reference page such as this one that I suspect you were using, you must provide a value (or remove) wherever it shows {something}. Here's code with suitable values:
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
var myKey = "6e07223403d94848be20af6f126fsssd";
var myBody = {url:"http://www.gannett-cdn.com/-mm-/2d2a8e29485ced74b7537554043aeae2e0bba202/c=0-104-5177-3029&r=x1683&c=3200x1680/local/-/media/2015/07/18/USATODAY/USATODAY/635728260394906410-AP-GOP-Trump-2016.jpg"}
$(function() {
var params = {
// Request parameters
"visualFeatures": "Categories",
"language": "en",
};
$.ajax({
url: "https://westus.api.cognitive.microsoft.com/vision/v1.0/analyze?" + $.param(params),
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", myKey);
},
type: "POST",
// Request body
data: JSON.stringify(myBody),
})
.done(function(data) {
alert("success");
debugger;
})
.fail(function() {
alert("error");
});
});
</script>
</body>
</html>
Before marking it as duplicated, i tried the other solutions found on the web, including SO, and none of them solved my issue.
I'm using x-editable plugin to store a new record using a store route.
When the form is submitted, i get a 500 with TokenMismatchException error.
I know about setting the csrf token thing, but i tried it in several ways, and nothing is working.
That's my javascript code:
$.fn.editable.defaults.params = function (params) {
params._token = window.Laravel.csrfToken;
return params;
};
$('.editable').each(function () {
$(this).editable();
});
The html
<head>
[...]
<meta name="csrf-token" content="{{ csrf_token() }}">
[...]
<script>
window.Laravel = <?php
echo json_encode([
'csrfToken' => csrf_token(),
]);
?>
</script>
[...]
</head>
<button id="note-asl-text"
data-type="textarea"
data-placeholder="Aggiungi Nota"
data-url="{{route('ricettanota.store')}}"
data-title="Inserisci una nuova nota"
data-highlight="false"
data-mode="inline"
data-send="always"
data-showbuttons="bottom"
class="editable"
>Aggiungi nota</button>
The Route
Route::resource('ricettanota', 'RicettaNotaController');
I already tried all possible combinations of the following:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': window.Laravel.csrfToken
}
});
$('.editable').each(function () {
$(this).editable({
ajaxOptions: {contentType: 'application/json', dataType: 'json'},
params: function (params) {
params._token = window.Laravel.csrfToken;
return JSON.stringify(params);
}
});
});
note
$('meta[name="csrf-token"]').attr('content') and window.Laravel.csrfToken are the same
update
I found out that placing Route::resource('ricettanota', 'RicettaNotaController'); into the api routes file(api.php) causes the issue, while placing the routes into the web routes file (web.php) and using the code above works.
Why using the API i get token mismatch, is still a mystery.
Not sure if this is what you are looking for, but maybe you should not struggling in sending custom header with x-editable plugin, but sending custom parameters.
The following code works for me.
$(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.node').editable(
{
params: function(params) {
var data = {};
data['_csrf_token'] = $(this).data("csrf");
return data;
},
}
);
});
Set csrf in your a-tag or somewhere else you like.
<a href="#" ... data-csrf="xxxxxxx" /a>
Hope this helps.
try this in your ajaxSetup
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
I also faced same issue in Laravel 5.8. Following code worked for me.
$.fn.editable.defaults.ajaxOptions = {
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
};
this is use code
$.ajax({
type: 'POST',
url: url,
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
dataType:'html',
data:data,
success:function(data){
}});
this Follow link
https://laravel.com/docs/5.3/csrf#csrf-x-csrf-token
I'm trying to simply create a HTML webpage that gives me emotions from images input by the user.
Using Microsoft's documentation I created a HTML file below:
<!DOCTYPE html>
<html>
<head>
<title>JSSample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","my-key");
},
type: "POST",
// Request body
data: {"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"},
})
.done(function(data) {
alert("success");
})
.fail(function() {
alert("fail");
});
});
</script>
</body>
</html>
My understanding is that this should work without the need of a server, however, I am always getting 'fail' message on loading the website.
Any help would work, thank you!
Use the API testing tool we (Microsoft) have on over here:
https://dev.projectoxford.ai/docs/services/5639d931ca73072154c1ce89/operations/563b31ea778daf121cc3a5fa/console
Ensure you can make a correct request and you are actually setting your api key and not sending my-key on over.
If your key is invalid you'll get an error in the javascript console: 'Access-Control-Allow-Origin' header is present on the requested resource.
If your key is valid but your data is not escaped, you'll get a 400 bad request error. Update your data field to wrap with ''. See my example here (fill in your key) http://jsfiddle.net/w3npr1ue
$(function() {
$.ajax({
url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
beforeSend: function(xhrObj){
// Request headers
xhrObj.setRequestHeader("Content-Type","application/json");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","SetYourKey");
},
type: "POST",
// Request body
data: '{"url": "http://1.bp.blogspot.com/-dWka6rPeHZI/UL7newH9TnI/AAAAAAAAAQI/OfU3TW0dDBE/s220/Asa%2Band%2BDada%2Bin%2Bst.%2Bpetersburg%2BSmall.jpg"}',
})
.done(function(data) {
alert("success");
})
.fail(function(error) {
console.log(error.getAllResponseHeaders());
alert("fail");
});
});
As the title says, I'm trying to pass a couple js variables to a php file. Here is my code so far.
JS:
$.ajax({
method: "POST",
url: "sendDataToDB.php",
data: {
mainVideoData: mainVideoTitle
},
success: function(data) {
alert("data sent");
},
error: function(data) {
alert("Data sending failed");
}
});
sendDataToDB.PHP:
<?php
$temp = $_POST["mainVideoData"];
echo $temp;
?>
I saw this code on different websites, but for some reason it's not working for me. It says that 'mainVideoData' is undefined which basically means that it doesn't exist.
Does anyone know what I did wrong?
Thanks!
EDIT:
I've read some suggestions, and decided to make a whole new file with just the code someone gave me that worked for him. Here is my whole php file and whole js file.
php.php:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="jquery-2.1.3.js" type="text/javascript"></script>
<script src="getApiData.js" type="text/javascript"></script>
<meta charset="utf-8"/>
<link rel="stylesheet" href=""/>
</head>
<body>
</body>
</html>
<?php
if(isset($_POST['mainVideoData'])){
$temp = $_POST["mainVideoData"];
echo $temp;
}
?>
And here is my whole js file:
$(document).ready ( function(){
var mainVideoTitle = "Hello";
$.ajax({
method: "POST",
url: "php.php",
data: {
mainVideoData: mainVideoTitle
},
success: function(data) {
alert("data sent");
},
error: function(data) {
alert("Data sending failed");
}
});
});
It only gives me an alert saying 'data sent', but it doesn't echo 'hello'.
Does anyone know what's wrong?
EDIT 2:
So I've added some code in my php file that should put my $temp in a database. Sadly that doesn't work. When I replace $temp by a normal value like 'hello' it places it in my database. When I use $temp it gives me this error:
Error: INSERT INTO youtubevideos (category)
VALUES (Wiz Khalifa - See You Again ft. Charlie Puth [Official Video] Furious 7 Soundtrack)You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Khalifa - See You Again ft. Charlie Puth [Official Video] Furious 7 Soundtrack)' at line 2
As you can see, it does give me the right value, and it also places that right value in VALUES. But for some reason it still gives me this error. Any reason why?
jQuery library is definitely included
check the path of your php file is valid
check mainVideoTitle defined or not
After just try this.
script:
$(document).ready ( function(){
var mainVideoTitle = "Hello";
$.ajax({
method: "POST",
url: "sendDataToDB.PHP",
data: {
mainVideoData: mainVideoTitle
},
success: function(data) {
alert("data sent");
},
error: function(data) {
alert("Data sending failed");
}
});
});
sendDataToDB.PHP:
<?php
if(isset($_POST['mainVideoData'])){
$temp = $_POST["mainVideoData"];
echo $temp;
}
?>
I hope this is help to achieve your result!!!
Try this it will work.Data will be captured in success.
$.ajax({
method: "POST",
url: "sendDataToDB.php",
data: {
mainVideoData: mainVideoTitle
},
success: function(data) {
console.log(data);
alert("data sent");
},
error: function(data) {
alert("Data sending failed");
}
});
I am using a JQuery date and time picker in my php website. I want to save the javascript variable as a php session, I have looked at previous answers on this site and tried suggestions but it doesnt seem to be working for me. Can anyone tell me what Im missing?
This is my jquery date and time picker, getting the selected date and time, and the posting ajax:
<input type="text" name="date2" value="">
<script type="text/javascript">
$(function(){
$('*[name=date2]').appendDtpicker({"inline": true,
"allowWdays": [1, 2, 3, 4, 5], // 0: Sun, 1: Mon, 2: Tue, 3: Wed, 4: Thr, 5: Fri, 6: Sat
"futureOnly": true,
"autodateOnStart": false
});
$('#btn_input').on('click', function(){
var input = $('*[name=date2]').handleDtpicker('getDate');
console.log(input);
jQuery.ajax({
url: 'backend.php',
type: 'POST',
data: {
'input': input,
},
dataType : 'json',
success: function(data, textStatus, xhr) {
console.log(data); // do with data e.g success message
},
error: function(xhr, textStatus, errorThrown) {
console.log(textStatus.reponseText);
}
});
});
});
</script>
<input type="submit" class="btn" id="btn_input" value="Confirm">
And this is the backend.php i am sending it to:
<?php
session_start();
$_SESSION['input'] = $_POST['input'];
echo ($_SESSION['input']);
?>
Any help is much appreciated!
New answer:
HTML
<!DOCTYPE html>
<html>
<head>
<!-- include jquery here -->
<script type="text/javascript" src="jquery.simple-dtpicker.js"></script>
<link type="text/css" href="jquery.simple-dtpicker.css" rel="stylesheet"/>
</head>
<body>
<input type="text" class="myDatepicker"/>
</body>
</html>
JS
$(function(){
$('.myDatepicker').appendDtpicker({ //please note that it requires an element that fits this selector
'inline' : true,
'allowWdays' : [1, 2, 3, 4, 5],
'futureOnly' : true,
'autodateOnStart' : false
'onHide': function(handler){
$.ajax({
type: 'POST',
url: 'backend.php',
data: 'input='+ handler.getDate(), //the selected value is being sent to your php, where the session variable is set accordingly
success: function(response){
console.log(response); //in case you have any output (e.g. error messages) in backend.php we will output them to the console for debugging purposes.
}
});
}
});
});
PHP (backend.php)
<?php
session_start();
$_SESSION['input'] = $_POST['input'];
echo $_SESSION['input'];
?>
Complete script would typically look like:
index.php / index.html
<!DOCTYPE html>
<html>
<head>
<!-- include jquery here -->
</head>
<body>
<input type="text" class="myDatepicker"/>
</body>
</html>
<script type="text/javascript">
$(function(){
$('.myDatepicker').appendDtpicker({ //please note that it requires an element that fits this selector
'inline' : true,
'allowWdays' : [1, 2, 3, 4, 5],
'futureOnly' : true,
'autodateOnStart' : false
'onHide': function(handler){
$.ajax({
type: 'POST',
url: 'backend.php',
data: 'input='+ handler.getDate(), //the selected value is being sent to your php, where the session variable is set accordingly
success: function(response){
console.log(response); //in case you have any output (e.g. error messages) in backend.php we will output them to the console for debugging purposes.
}
});
}
});
});
</script>
Please note that the path to backend.php suggests that index.php/index.html and backend.php are located in the same folder.
ORIGINAL ANSWER: Originally I thought we were talking about jQuery-ui datepicker. I'll leave this response in case anyone needs it.
This is one way of doing it...
$('.myElement').datepicker({
minDate: 0, //dates from today and onwards
onSelect: function(date){ //"date" will have the selected value of the datepicker
$.ajax({
type: 'POST',
url: 'backend.php',
data: 'input='+ date, //the selected value is being sent to your php, where the session variable is set accordingly
success: function(response){
console.log(response); //in case you have any output (e.g. error messages) in backend.php we will output them to the console for debugging purposes.
}
});
});
Should you using jquery cookies too(Jquery Cookies).. So, after you call ajax and success, you will get return session from passing your backend.php, and then that result you store to jquery cookies. After that, you can using cookies for next progress..
Try:
<script>
jQuery(function($) {
$(document).on('click', '#btn_input', function(){ // edit here
var input = $('*[name=date2]').handleDtpicker('getDate');
console.log(input);
jQuery.ajax({
url: 'backend.php',
type: 'POST',
data: {
'input': input,
},
dataType : 'json',
success: function(data, textStatus, xhr) {
console.log(data); // do with data e.g success message
},
error: function(xhr, textStatus, errorThrown) {
console.log(textStatus.reponseText);
}
});
});
});
</script>
Does this work? If not, what's value of input in your console?