How to solve Error 400 on html page post method - javascript

I have make a simple html file to get my data and add button to post data but however i am returning error 400
My get method are running fine with displaying the backend data out in the html but however post method i am returning some errors 400 due to my query which i not sure why is there any way i can prevent this error 400 ?
<!DOCTYPE html>
<html>
<head>
<title>Add recycables</title>
<!-- Stylesheet -->
<link rel="stylesheet" href="/">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id = "add"></div>
<P>Add recycables</P>
<p>name: <input type="text" id="name"></p>
<p>type:<input type="text" id="type"> </p>
<button id="add">Add</button>
</body>
<script>
$(document).ready(function(){
var $items = $('#add');
var $name = $('#name');
var $type = $('#type');
$.ajax({
url:"https://ecoexchange.dscloud.me:8080/api/get",
method:"GET",
// In this case, we are going to use headers as
headers:{
// The query you're planning to call
// i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
query:"RecyclableGet(0)",
// Gets the apikey from the sessionStorage
apikey:sessionStorage.getItem("apikey")
},
success:function(data, item, xhr,textStatus) {
//console.log(data)
$.each(data, function(i, item){
$items.append('<li>name: '+item.Name +', type: '+ item.RecyclableType + '</li>');
});
},
error:function(xhr,textStatus,err) {
console.log(err);
}
});
$('#add').on('click', function(){
var addRecyclables = {
Name: $name.val,
RecyclableType: $type.val
}
})
$.ajax({
url:"https://ecoexchange.dscloud.me:8080/api/post",
method:"POST",
headers:{
// The query you're planning to call
// i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
query:`RecyclableAdd('${name}','${type}')`,
// Gets the apikey from the sessionStorage
apikey:sessionStorage.getItem("apikey")
},
success:function(data, Newitem, xhr,textStatus){
$items.append('<li>name: '+Newitem.Name +', type: '+ Newitem.RecyclableType + '</li>');
},
error:function(xhr,textStatus,err) {
console.log(err);
}
})
})
</script>
</html>
Json file look like
my html on web

Related

Populating select in html document using ajax (JQuery)

Problem : I am trying to populate the 1st SELECT on load. And 2nd SELECT depends on the 1st one.
1st select : populated with states
2nd select : should be populated with districts based on selected states.
jSON file is HERE
Solutions given on other stackoverflow documents didn't meet my requirements\
$(document).ready(function(){
$.ajax({
type:'GET',
header:{' Access-Control-Allow-Origin ':'*'},
datatype:'json',
url:'https://github.com/sab99r/Indian-States-And-Districts/blob/master/states-and-districts.json'
})
.done(function(response){
console.log(response);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>
<div class="">
<select class="states" >
</select>
<select class="districts" >
</select>
</div>
<link rel="text/script" href="jquery-3.5.1.js">
<link rel="text/>script" href="index.js">
</body>
</html>
Below example show an example how to load data, first and then store it in
a var to prevent ajax loading every change, then in every change fetch data array to load districts :
( uring raw url load text , so you have to pare json from string at first )
See wokring snippet :
data = [];
$(document).ready(function() {
$(".states").on("change", stateChange);
$.ajax({
type: 'GET',
header: {
' Access-Control-Allow-Origin ': '*'
},
datatype: 'json',
url: 'https://raw.githubusercontent.com/sab99r/Indian-States-And-Districts/master/states-and-districts.json'
})
.done(function(response) {
var resp = JSON.parse(response);
loadStates(resp);
})
});
var loadStates = function(response) {
if (response.states) {
data = response.states;
response.states.forEach(state => {
var option = $('<option/>');
option.attr({
'value': state.state,
}).text(state.state);
$('.states').append(option);
})
}
}
var stateChange = function(event) {
let stateValue = event.target.value;
let state = data.find(state => state.state === stateValue);
$('.districts').html("");
if (state) {
state.districts.forEach(ditrict => {
var option = $('<option/>');
option.attr({
'value': ditrict,
}).text(ditrict);
$('.districts').append(option);
})
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
state :
<select class="states">
</select>
<br> distric
<select class="districts">
</select>
Just set code according to your requirement but you need to set all logic. You need to set when you send state data then you will get all districts
function changeselect(){
$.ajax({
type:'GET',
header:{' Access-Control-Allow-Origin ':'*'},
datatype:'json',
url:'https://github.com/sab99r/Indian-States-And-Districts/blob/master/states-and-districts.json'
})
.done(function(response){
console.log(response);
response.foreach(function(data){
$("#distr").append("<option>+data+</option>")
})
})
}
$(document).ready(function(){
$.ajax({
type:'GET',
header:{' Access-Control-Allow-Origin ':'*'},
datatype:'json',
url:'https://github.com/sab99r/Indian-States-And-Districts/blob/master/states-and-districts.json'
})
.done(function(response){
console.log(response);
response.foreach(function(data){
$("#distr").append("<option>+data+</option>")
})
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Demo</title>
</head>
<body>
<div class="">
<select class="states" onchange="changeselect()">
<option>A</option>
<option>B</option>
<option>C</option>
</select>
<select class="districts" id="distr">
</select>
</div>
<link rel="text/script" href="jquery-3.5.1.js">
<link rel="text/>script" href="index.js">
</body>
</html>
I have got a even short code to do it.
We can use ajax GET to get data from the raw of any repository.
Solution to the above question :
$.get('https://raw.githubusercontent.com/aps08/web-development/main/web-dev-series/JSON/indian-states-and-cities.json', // url
function (data1, textStatus, jqXHR) { // success callback
var data1 = JSON.parse(data1);
load(data1);
});
Remember that if u loading data from your local machine then you need to remove
var data1 =JSON.parse(data1) line

Learning ajax. How to print the variable on json response

I am trying to learn ajax, because it will be useful for the project I am developing. I am only getting started at it. I've watched some tutorials and now I testing out some code. I am using laravel. Here is my view:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<button type="button" class="btn btn-warning" id="getRequest">get Request</button>
<div id="teste"></div>
<script type="text/javascript">
var id = 12; // A random variable for this example
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$('#getRequest').click(function(){
$.ajax({
method: 'POST', // Type of response and matches what we said in the route
url: '/customer/ajaxupdate', // This is the url we gave in the route
data: {'id' : id}, // a JSON object to send back
success: function(response){ // What to do if we succeed
var theDiv = document.getElementById("teste");theDiv.innerHTML += response->'teste';
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
})
})
</script>
</body>
</html>
Here is my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AjaxController extends Controller
{
public function updateCustomerRecord(Request $request)
{
$datda = $request->all(); // This will get all the equest data.
$teste = "teste";
return response()->json(['success' => true, 'teste' => $teste]);
echo "ole";
}
}
And lastly we have my routes:
Route::post('/customer/ajaxupdate', 'AjaxController#updateCustomerRecord');
Route::get('/teste', function(){
return view('teste');
});
As you can see this is simple code... When I get more used to Ajax I will do a select from database and show data on the view. But now I am trying to pass data from one variable on the controller to the view using json response. I also wish you could give me a tip how I should do a simple db:select and the best way to pass it through to the view.
I am expecting this code to pass data from controller to view.
There's a mistake in your JavaScript code. You are using arrow -> instead of period or dot .
Please replace this
theDiv.innerHTML += response->'teste';
with this
theDiv.innerHTML = response.teste;

How to get data from select tag using AJAX before submitting into PHP?

I want to get the data of the select tag id="departmentselect" so that the values of it will be stored in the mysql database before submitting the form. I heard that you will use AJAX to get the data before you submit the form. Because when I select the College select tag and its corresponding values of the department select tag it will only store a number in the department of the database.
Example MYSQL database:
In the query of mysql, the department did not get the values of the JSON file. It only display the number.
Here is my PHPCode
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="SignupProcess.php" method="POST" onsubmit="return check_password();" id="signupform">
<select id="collegeselect" name="collegeselect">
<option value="">College</option>
<option value="College of CAS">College of CAS</option>
</select>
<select id="departmentselect" name="departmentselect">
<option value="">Department</option>
</select>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="GetCollegeJsonData.js"></script>
<script>
$('#signupform').submit(function(e))
{
if($('#departmentselect').val() != '')
{
$ajax
({
type: 'POST',
url: 'Signup.php?select' += select,
success: function(data)
{
alert(data);
}
});
}
else
{
alert('error');
}
e.preventDefault();
});
</script>
</html>
Script Type
Here is the script for using ajax but it did not seem to have any effect.
<script>
$('#signupform').submit(function(e))
{
if($('#departmentselect').val() != '')
{
$ajax
({
type: 'POST',
url: 'Signup.php?select' += select,
success: function(data)
{
alert(data);
}
});
}
else
{
alert('error');
}
e.preventDefault();
});
</script>
JQUERY Code file name GetCollegeJsonData.js
I get the JSON data from the file and read it into my Jquery file and then link the file using script to my php code
//Get json
$('body').on('change', '#collegeselect', function() {
var selected_college = $(this).val();
$('#departmentselect').html('');
$.getJSON("CollegeAndDepartment.json", function(data) {
$.each(data[selected_college], function(key, val) {
$('#departmentselect').append("<option value='" + key + "'>" + val + "</option>");
});
});
})
Its JSON File
{
"College of CAS": ["Biology", "English", "LIACOM", "Library & Information Science", "Mass Communication", "Philosophy", "Political Science", "Psychology"]
}
Is my Ajax function is incorrect?
Your ajax method code has syntax error and, when you use post method you have to post data using data option not with URL. data should be in json object or query string.
Your ajax function should be
<script>
$('#signupform').submit(function(e))
{
if($('#departmentselect').val() != '')
{
$.ajax({
type: 'POST',
url: 'Signup.php',
data: {select: $('#departmentselect').val()},
success: function(data)
{
alert(data);
}
});
}
else
{
alert('error');
}
e.preventDefault();
});
</script>
I have edited your code as below.
Kindly give it a try.
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<form action="SignupProcess.php" method="POST" onsubmit="return check_password();" id="signupform">
<select id="collegeselect" name="collegeselect">
<option value="">College</option>
<option value="College of CAS">College of CAS</option>
</select>
<select id="departmentselect" name="departmentselect">
<option value="">Department</option>
</select>
</form>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
<script src="GetCollegeJsonData.js"></script>
<script>
$('#signupform').submit(function(e)
{
if($('#departmentselect').val() != '')
{
$.ajax
({
type: 'POST',
data:{select:$('#departmentselect').val()},
url: 'Signup.php',
success: function(data)
{
alert(data);
}
});
}
else
{
alert('error');
}
e.preventDefault();
});
</script>
</html>
For GetCollegeJsonData.js, ihave modified as follows:
//Get json
$('#collegeselect').on('change', function() {
var selected_college = $(this).val();
$('#departmentselect').html('');
$.getJSON("CollegeAndDepartment.json", function(data) {
$.each(data[selected_college], function(key, val) {
$('#departmentselect').append("<option value='" + val + "'>" + val + "</option>");
});
});
})

how to handle json data in javascript

I am using worldweatheronline api to access weather data,when a request is send it response by sending data in json.I want to display the weather information in html page
<!DOCTYPE html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
</head>
<body>
<input type="text" id="in"></input>
<input type="hidden" id="keys" value="apikey"></input>
<button id="go">Search</button>
<script>
$(document).ready(function(){
$("#go").click(function(){
var apikey = $("#keys").val();
var q = $("#in").val();
jQuery.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?key=' + apikey + '&q=' + q,
success: function(response){
var obj = JSON.parse(response);
console.log(obj);
},
});
});
});
</script>
</body>
</html>
<html>
<head>
<title>weather app</title>
</head>
<body>
<form method="GET" action="http://api.openweathermap.org/data/2.5/weather">
<input type="hidden" name="key" value="apikeyneeded"></input>
<input type="text" name="q"></input>
</form>
</body>
</html>
Check this.
var apikey = jQuery('[name="key"]').val();
var q= jQuery('[name="q"]').val();
jQuery.ajax({
url: 'http://api.openweathermap.org/data/2.5/weather?key=' + apikey + '&q=' + q,
success: function(response){
var obj = JSON.parse(response);
console.log(obj);
},
});
add this line into the head tag to include jQuery
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
You can't use the JSON.parse that way. At first you must make a request to that API, then get a response and finally use the parse JSON.parse(response)
if you are interested I can help you to manage this using jQuery to request the json.
Use ajax method to get the data from openweathermap api.
$.ajax({
url: "http://api.openweathermap.org/data/2.5/weather?key=apikey&q=delhi",
dataType: "jsonp", //Handle ajax cross domain
success: function (response) {
//the response already parsed.
}
});

jquery post php send form data

I'm trying to send variables from 2 form elements to another PHP script, through jquery.
Not sure what I'm doing wrong, just can't get the variables sent to the other PHP script.
Tried with jquery serialize as well, didn't get that to work either.
Tried with serialize() command as well.
Any suggestions more than welcome.
Thanks!
When putting the data in url manually, the return is correct. Then in data I have +page, as:
$.ajax
({
type: "GET",
url: "agent_talktime_pag.load.php?txtDate=2007-03-04&zone=Hongkong",
data: "page="+page,
success: function(msg)
If I use " var datastring = $('#idForm').serialize(); " the return doesn't work.
The variables get passed in the url, but the issue seems that the page="+page isn't passed. Which makes the load script not work. I tried to add a hidden field in the form like:
<input type="hidden" name="page" value="+page">
But, seems it's not passed as expected by the load script. The +page becomes just a string, think in the $.ajax it functions as a counter?
Any ideas?
$(document).ready(function(){
$("#driver").click(function(){
var datastring = $('#testform').serialize();
function loading_show(){
$('#loading').html("<img src='../images/loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function loadData(page){
loading_show();
$.ajax
({
type: "GET",
url: "agent_talktime_pag.load.php?txtDate=2007-03-04&zone=Hongkong",
data: "page="+page,
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
$(document).ready(function(){
$("#driver").click(function(){
var txtDate=$("#txtDate").val();
var zone=$("#zone").val();
var dataString = 'txtDate='+ txtDate + '&zone='zone;
});
function loading_show(){
$('#loading').html("<img src='../images/loading.gif'/>").fadeIn('fast');
}
function loading_hide(){
$('#loading').fadeOut('fast');
}
function loadData(page){
loading_show();
$.ajax ({
type: "GET",
url: "agent_talktime_pag.load.php",
data: dataString,
success: function(msg)
{
$("#container").ajaxComplete(function(event, request, settings)
{
loading_hide();
$("#container").html(msg);
});
}
});
}
loadData(1); // For first time page load default results
$('#container .pagination li.active').live('click',function(){
var page = $(this).attr('p');
loadData(page);
});
$('#go_btn').live('click',function(){
var page = parseInt($('.goto').val());
var no_of_pages = parseInt($('.total').attr('a'));
if(page != 0 && page <= no_of_pages){
loadData(page);
}else{
alert('Enter a PAGE between 1 and '+no_of_pages);
$('.goto').val("").focus();
return false;
}
});
});
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<!-- This is a pagination script using Jquery, Ajax and PHP
The enhancements done in this script pagination with first,last, previous, next buttons -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Pagination with Jquery, Ajax, PHP</title>
<script type="text/javascript" src="jquery/external/jquery/jquery.js"></script>
<script type="text/javascript" src="jquery/jquery-ui.min.js"></script>
<link rel="stylesheet" href="includes/jquery/jquery-ui.css">
<link type="text/css" rel="stylesheet" href="style.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
<div align="center" style="font-size:24px;color:#cc0000;font-weight:bold">Pagination with jquery, Ajax and PHP</div>
<form id="testform">
<input type="text" name="txtDate" id="txtDate">
<select id="zone" name="zone">
<option value="Hongkong">Hongkong</option>
<option value="EST">EST</option>
</select>
<input type="button" id="driver" name="submit" value="Search"/>
</form>
<div id="loading"></div>
<div id="container">
<div class="data"></div>
<div class="pagination"></div>
</div>
</body>
</html>
To send data you have to do as follows:
Error code:
var datastring = 'txtDate =' + txtDate + '& zone =' zone;
Code:
//Manual code
var datastring = {"name field" txtDate, "fieldname": zone} // zone = field values
otherwise:
var datastring = $('#idForm').serialize();
Code ajax:
$.ajax({
data: datastring, //date form
url: 'url',
type: 'get', //type
dataType: "html",
beforeSend: function () {
//code load
},
success: function (response)
{
//code
}
});
You shouldn't be posting data in the url as params. You should use data to map out your data fields that you're going to be sending:
type: "method",
data: {field1: field1, field2: field2}

Categories