Calling JSon file with ajax(Uncaught ReferenceError: request is not defined) - javascript

Brand new to using JSon/ajax. Trying to replicate this jQuery UI Autocomplete using a static json file as source just as an example. I'm not positive I'm referencing this correctly if someone could let know whats wrong. Getting a (Uncaught ReferenceError: request is not defined)
<form id="searchform" method="get" role="search">
<input id="searchfield" />
<input type="submit" name="go" value="go!" />
</form>
<script src='js/jquery-1.11.0.min.js'></script>
<script src="js/autocomplete/jquery-ui-1.10.3.custom.js" type="text/javascript" charset="utf-8"></script>
<script>
$(function() {
$.ajax({
url: "json/Providers.json",
dataType: "json",
data: {term: request.term},
success: function(data) {
var cat_data = $.map(data, function(item) {
return {
ProviderID: item.ProviderID,
Name: item.Name,
};
});
$("#searchfield").catcomplete({
delay: 0,
source: cat_data,
minlength:0
});
}
});
});
</script>
json format
{"Providers":[{"ProviderID":"3","NAME":"name1"},
{"ProviderID":"4","NAME":"name2"},
{"ProviderID":"5","NAME":"name3"}]}

This particular data: {term: request.term}, is the problem
You need to define any javascript variable before accessing them.
var request;
In your case data is not required. Just remove data: {term: request.term} since you are loading the static .json file

Since you're a reading json file, it is clear there is no need to pass any parameter. So remove data: {term: request.term}

Related

Laravel Ajax JSON Object is empty

I'm working on a laravel web app, I'm relatively new to laravel so I'm not very familiar with the ajax tokens and such, but I believe I have set it up correctly.
Below is my Ajax code for a test page that I want to try and send data from.
<meta name="csrf-token" content="{{ csrf_token() }}">
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#btn').on('click', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'testSend',
data: {
test: 'hello'
},
dataType: 'json',
success: function (response) {
alert(response);
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
Here is my form:
<div class="flex-center position-ref full-height">
<div class="content">
<form action="testSend" method="post" enctype="multipart/form-data">
<button type="submit" id="btn"> submit</button>
</form>
</div>
And here is a simple route that I have setup just to test this:
Route::post('testSend', function (Request $request) {
return response()->json($request);
});
However when I go to check the network in chrome, the JSON Object is empty.
The empty JSON Object:
I'm pretty new to this, I have learned it but never really tried to create a web app until now. I have searched everywhere, but no one seemed to have the same problem, maybe they did but I just don't know.
The problem might just be a dumb mistake, but I really can't figure it out ):
Thanks.
Rather than passing Request instance try this:
return response()->json($request->all());

Form ajax post data to php file [duplicate]

This question already has answers here:
jQuery Ajax POST example with PHP
(17 answers)
Closed 5 years ago.
Hi i trying make form using ajax. But i get some problems to sending form vars to php file. I get error: Undefined index: name.
I check chrome dev tools and i see variable is sending. But when made echo json_encode i see in php file i get empty array. So i dont have any idea where i made misstake.
file Main.js
var name = $('#user_name').val();
var lname = $('#user_lastname').val();
function formLogin(name, lname)
{
$.ajax({ url: 'database/register.php',
data: {
'name' : name,
'lname' : lname
},
type: 'post',
dataType:'json',
success: function(data) {
alert(data);
}
});
}
Html form:
<form class="circleForm" id="registerForm">
Imię: <input type="text" id="user_name"><br>
Nazwisko: <input type="text" id="user_lastname">
<br>
<input class="btnCircle" type="button" id="submit" value="Przejdź dalej" onclick="formLogin(name, lname)">
</form>
Php Code:
$dane = $_POST;
echo json_encode($dane);
Chrome dev:
I just want figure how can i echo this variables(name,lname) in php file register.php
Version with serialize:
function formLogin() {
var dane = $('form').serialize();
$.ajax({
url: 'database/register.php',
data: {'dane': dane},
method: 'post',
success: function(data) {
console.log(data);
}
});
}
Then result console:
<pre class='xdebug-var-dump' dir='ltr'>
<small>D:\xampp\htdocs\szkola\database\register.php:8:</small>
<b>array</b> <i>(size=1)</i>
'dane' <font color='#888a85'>=></font> <small>string</small> <font color='#cc0000'>''</font> <i>(length=0)</i>
</pre>
jquery-3.2.1.min.js:4 XHR finished loading: POST "http://localhost/szkola/database/register.php".
But when i go to http://localhost/szkola/database/register.php
i get this:
D:\xampp\htdocs\szkola\database\register.php:8:
array (size=0)
empty
You need to change the way you define your variables in your Javascript and declare them inside your function, not outside :
function formLogin(){
var name = $('#user_name').val();
var lname = $('#user_lastname').val();
$.ajax({ url: 'database/register.php',
data: {
'name' : name,
'lname' : lname
},
type: 'post',
dataType:'json',
success: function(data) {
alert(data);
}
});
}
And you need to update your HTML the same way (formLogin() instead of formLogin(...,...)) :
<form class="circleForm" id="registerForm">
Imię: <input type="text" id="user_name"><br>
Nazwisko: <input type="text" id="user_lastname">
<br>
<input class="btnCircle" type="button" id="submit" value="Przejdź dalej" onclick="formLogin()">
</form>
Try using method instead of type.
The HTML:
<form class="circleForm" id="registerForm">
Imię: <input type="text" id="user_name" name="name"><br />
Nazwisko: <input type="text" id="user_lastname" name="lname"><br />
<input class="btnCircle" type="button" id="submit" value="Przejdź dalej" onclick="formLogin();">
</form>
The JavaScript:
function formLogin() {
// Serialize the form
var data = $('form').serialize();
// Ajax call
$.ajax({
url: 'database/register.php',
data: data,
method: 'post',
dataType: 'json',
success: function(data) {
console.log(data);
}
});
}
Also remember that you're requesting a JSON so you have to echo a json_encode($array) in your PHP file for a simple string will not be returned.

How to upload an image through jQuery?

For past few days i have been struggling to submit a form with jQuery and AJAX. The problem i'm facing is to upload the image in the form field.
My form is something like this:
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
and my jQuery script for getting the form value is something like this:
$("form").submit(function (event) {
$.dataArray = $(this).serializeArray(); // array of form data
console.log($.dataArray);
event.preventDefault();
});
But this returns all the field values except image one, in case of image is return null.
How do I store in the dataarray?
I want to store so I can send the value to the server through the AJAX.
For uploading single image its like this
<html>
<head>
<meta charset="UTF-8">
<title>AJAX image upload with, jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$('#upload').on('click', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'http://localhost/ci/index.php/welcome/upload', // point to server-side controller method
dataType: 'text', // what to expect back from the server
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from the server
},
error: function (response) {
$('#msg').html(response); // display error response from the server
}
});
});
});
</script>
</head>
<body>
<p id="msg"></p>
<input type="file" id="file" name="file" multiple />
<button id="upload">Upload</button>
</body>
</html>
For multiple images u will have to loop its kinda different
I have found a similar question, hope it will help you.
Upload image using jquery
Another option to consider is to use some sort of jQuery plugin to upload images like Cloudinary and include it in your HTML pages :
<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>
and then include all required jQuery files:
<script src='jquery.min.js' type='text/javascript'></script>
<script src='jquery.ui.widget.js' type='text/javascript'></script>
<script src='jquery.iframe-transport.js' type='text/javascript'></script>
<script src='jquery.fileupload.js' type='text/javascript'></script>
<script src='jquery.cloudinary.js' type='text/javascript'></script>
try this code, it's work for me.
$("form").submit(function (event) {
var form_data = new FormData($(this));
$.ajax({
url : url,
type : 'POST',
data : form_data,
processData: false, // tell jQuery not to process the data
contentType: false,
success : function(resp){
}
});
});
Try this code. using formData()
$("form").submit(function (event) {
var formData = new FormData($(this));
$.ajax({
url: url,
type: 'POST',
data: formData,
async: false,
success: function (data) {
//success callback
},
cache: false,
contentType: false,
processData: false
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
serialize() method not able to post file data.
For sending file using ajax use FormData instead of serializing
HTML5 introduces FormData to allow developers to build forms objects dynamically, and then to send this form object via AJAX.
your Html
<form action="upload_image.php" id="form_img" method="GET" role="form" enctype="multipart/form-data">
<input type="text" placeholder="Name" name="name">
<input type="file" name="img" multiple>
<button type="submit">Submit </button>
</form>
AJAX call
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#form_img").submit(function(e){
e.preventDefault();
var formData = new FormData($("#form_img")[0]);
$.ajax({
url : $("#form_img").attr('action'),
type : 'POST',
data : formData,
contentType : false,
processData : false,
success: function(resp) {
console.log(resp);
}
});
});
});
</script>
upload_image.php
print_r($_FILES) //check you get file data or not
Try this way.Hope it will help you
Please check the follow the code, which i am using to upload image.
$.ajax({
url: UPLOADURL, // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this),// Data sent to server, a set of key/value pairs representing form fields and values
contentType: false,// The content type used when sending data to the server. Default is: "application/x-www-form-urlencoded"
cache: false,// To unable request pages to be cached
processData:false,// To send DOMDocument or non processed data file it is set to false (i.e. data should not be in the form of string)
success: function(data)// A function to be called if request succeeds
{
data = JSON.parse(data);
console.log(data);
if(data.status == "Success"){
attachmentListing();
//$("#mailerMessage").html(data.data.mailStatus);
//$("#mailerMessage").fadeIn();
setTimeout(function () {
$("#mailerMessage").fadeOut();
},5000);
}else{
toastr.warning(data.status);
}
$("#ajaxloader").addClass("hideajaxLoader");
},
error: function (jqXHR, errdata, errorThrown) {
log("error");
$("#ajaxloader").addClass("hideajaxLoader");
}
});

getting php session from javascript variable

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?

jQuery autocomplete UI - doesn't work

I am trying to make an autocomplete widget that will display item's codes returned from a database.
I have successfully made it so my database will return the appropriate JSON response.
The problem now is I don't know why the drop-down list doesn't show up.
Here's the code down below:
<input type="text" id="search" class="form-control" placeholder="">
<form action="post" action="" id="spareParts" class="spareparts">
</form>
$('#search').keyup(function(event) {
var search = $(this).val();
if($.trim(search).length){
var arr = [];
$.ajax({
url: 'get_spareparts',
type: 'POST',
dataType: 'JSON',
data: {item: search},
success: function (data) {
arr = $.parseJSON( data );
console.log(arr);// CONSOLE.LOG WORKS WELL
//[Object { id="1", value="25.00", desc="Fuel pump", more...}]
// AUTOCOMPLETE DOESN'T WORK
$('#spareParts').autocomplete({
minLength:0,
source: arr
});
}
});
}
});
The autocomplete with AJAX loaded data should be configured differently. source property can be a function which accepts a callback parameter. You should feed this callback with data loaded from server.
Also you don't need to bind keyup event manually. Your code will become:
$('#search').autocomplete({
minLength: 0,
source: function(request, response) {
$.ajax({
url: 'get_spareparts',
type: 'POST',
dataType: 'JSON',
data: {item: request.term}
}).done(function(data) {
response(data.map(function(el) {
return {
value: el.value,
label: el.desc
};
}))
});
}
});

Categories