im trying to send some data through ajax jQuery to a php file with POST but i keep getting POST 405 Method Not Allowed error, any ideas to solve this issue will be appreciated, heres the function that makes the call
function manageData(key) {
var name = $("#countryName");
var abbrev = $("#countryAbbrev");
var desc = $("#countryDesc");
if (isNotEmpty(name) && isNotEmpty(abbrev) && isNotEmpty(desc)) {
$.ajax({
url: 'http://127.0.0.1:5500/ajax.php',
method: 'POST',
dataType: 'text',
data: {
key: key,
name: name.val(),
abbrev: abbrev.val(),
desc: desc.val()
},
success: function (response) {
alert(response);
}
});
}
}
and here is the ajax.php file code
<?php
if (isset($_POST['key'])) {
$conn = new mysqli(host:'localhost', username:'root', passwd:'root',
dbname:'mysqldatamanager');
$name = $conn->real_escape_string($_POST['name']);
$abbrev = $conn->real_escape_string($_POST['abbrev']);
$desc = $conn->real_escape_string($_POST['desc']);
if($_POST['key'] == 'addNew') {
$sql = $conn->query(query:"SELECT id FROM country WHERE
countryName = '$name'");
if ($sql->num_rows > 0) {
exit("Country already exists!");
} else {
$conn->query("INSERT INTO country (countryName,
countryAbbrev, countryDesc) VALUES ('$name', '$abbrev',
'$desc')");
exit("Country has been added succesfully!");
}
}
}
?>
Please try below code.
function manageData(key) {
var name = $("#countryName");
var abbrev = $("#countryAbbrev");
var desc = $("#countryDesc");
if (isNotEmpty(name) && isNotEmpty(abbrev) && isNotEmpty(desc)) {
$.ajax({
url: 'http://localhost/ajax.php',
type: "POST",
data: {
key: key,
name: name.val(),
abbrev: abbrev.val(),
desc: desc.val()
},
success: function (response) {
alert(response);
}
});
}
}
Related
I'm working on a CRUD project. All of my other functions are working except update. I have included a catch to see if there are any errors in the SQL statement and it doesn't catch anything. When I press save changes, the code is executed but doesn't reflect any changes in my table. I have checked all of the error logs also and nothing is apparent. Any ideas? (I had to remove the details from the fields as they contain identifiable information).
function edit(rowID) {
$.ajax({
url: 'ajax.php',
method: 'POST',
dataType: 'json',
data: {
key: 'getRowData',
rowID: rowID
}, success: function (response) {
$("#editRowID").val(response.rowID);
$("#fullName").val(response.fullName);
$("#dob").val(response.dob);
$("#ethnicity").val(response.ethnicity);
$("#gender").val(response.gender);
$("#nhsNo").val(response.nhsNo);
$("#hospNo").val(response.hospNo);
$("#idMarks").val(response.idMarks);
$("#address").val(response.address);
$("#tableManager").modal('show');
$("#manageBtn").attr('value', 'Save Changes').attr('onclick', "manageData('updateRow')");
}
});
}
function manageData(key) {
var fullName = $("#fullName");
var dob = $("#dob");
var ethnicity = $("#ethnicity");
var gender = $("#gender");
var nhsNo = $("#nhsNo");
var hospNo = $("#hospNo");
var idMarks = $("#idMarks");
var address = $("#address");
var editRowID = $("#editRowID");
if (isNotEmpty(fullName) && isNotEmpty(dob) && isNotEmpty(ethnicity) && isNotEmpty(gender) && isNotEmpty(nhsNo) && isNotEmpty(hospNo) && isNotEmpty(idMarks) && isNotEmpty(address)){
$.ajax({
url: 'ajax.php',
method: 'POST',
dataType: 'text',
data: {
key: key,
fullName: fullName.val(),
dob: dob.val(),
ethnicity: ethnicity.val(),
gender: gender.val(),
nhsNo: nhsNo.val(),
hospNo: hospNo.val(),
idMarks: idMarks.val(),
address: address.val(),
rowID: editRowID.val()
}, success: function (response) {
alert(response);
}
});
}
}
$fullName = $conn->real_escape_string($_POST['fullName']);
$dob = $conn->real_escape_string($_POST['dob']);
$ethnicity = $conn->real_escape_string($_POST['ethnicity']);
$gender = $conn->real_escape_string($_POST['gender']);
$nhsNo = $conn->real_escape_string($_POST['nhsNo']);
$hospNo = $conn->real_escape_string($_POST['hospNo']);
$idMarks = $conn->real_escape_string($_POST['idMarks']);
$address = $conn->real_escape_string($_POST['address']);
$rowID = $conn->real_escape_string($_POST['rowID']);
if ($_POST['key'] == 'updateRow') {
$conn->query("UPDATE suspects SET fullName='$fullName', dob='$dob', ethnicity='$ethnicity', gender='$gender', nhsNo='$nhsNo', hospNo='$hospNo', idMarks='$idMarks', address='$address' WHERE id= '$rowID'");
exit('Record for '.$fullName.' updated.');
}
I have this function to get values from a form
$("button[name='createimport']").click(function() {
var fd = new FormData();
var files = $('#xsfile')[0].files[0];
fd.append('file',files);
var batchid = $("input[name='batchid']").val();
var yrstart = $("input[name='yrstart']").val();
var yrend = $("input[name='yrend']").val();
$.ajax({
url:"fetch_import.php",
method:"POST",
data: { batchid : batchid, yrstart: yrstart, yrend: yrend, fd},
success: function (data) {
//show success result div
if(data)
{
showSuccess();
}
else
{
showFailure();
}
},
error: function () {
//show failure result div
showFailure();
}
});
});
and a php code like this:
enter code here$bcid = $_POST['batchid'];
$yrs = $_POST['yrstart'];
$yrg = $_POST['yrend'];
/* Getting file name */
$filename = $_FILES['file']['name'];
/* Location */
$location = "upload/".$filename;
$FileType = pathinfo($location,PATHINFO_EXTENSION);
move_uploaded_file($_FILES['file']['tmp_name'],$location);
passing the file doesn't work. I've searched for this but still not working for me, i think i'll understand how it will work. Any idea? Tyia
You should append your fields to fd and simply use that as data-parameter in $.ajax:
$("button[name='createimport']").click(function() {
var fd = new FormData();
var files = $('#xsfile')[0].files[0];
fd.append('file',files);
fd.append('batchid', $("input[name='batchid']").val());
fd.append('yrstart', $("input[name='yrstart']").val());
fd.append('yrend', $("input[name='yrend']").val());
$.ajax({
url:"fetch_import.php",
method:"POST",
data: fd,
success: function (data) {
//show success result div
if(data)
{
showSuccess();
}
else
{
showFailure();
}
},
error: function () {
//show failure result div
showFailure();
}
});
});
I am using jQuery & ajax to save a entire form in session which is being generated.
when I press the search button the
onclick="updateContentdata();
is called. which is doing following.
function updateContentdata() {
var updateSearchContent = $('#savelistdata').html();
var rowNumb = rowCount;
var inFileds = JSON.stringify(field_options);
// var inputValue = $('inptval_' + rowCount).val();
$.ajax({
type: "POST",
url: "<?= $HOMEPAGE_ROOT; ?>/ajax_listuser.php",
data: {
rowNum: rowNumb,
field_options: inFileds,
html: updateSearchContent
},
success: function (data) {
$('#searchusers').submit();
},
error: function (req, status, error) {
console.log(error)
}
});
}
ajax_listuser.php
<?php
session_start();
if(isset($_POST['html']) && isset($_POST['rowNum'])){
$_SESSION['searchContent'] = $_POST['html'] ;
$_SESSION['rowNumber'] = $_POST['rowNum'] ;
$_SESSION['field_options'] = $_POST['field_options'];
}
?>
Form is being saved in the session but I want to keep form values in the session. but it only keeping the form.
So basically I need
<input class="form-control" type="text" id="inptval_2" name="search_input_value[]" value="71347">
instead of
<input class="form-control" type="text" id="inptval_2" name="search_input_value[]">
Create this function first:-
function getHtml(div){
div.find("input, select, textarea").each(function () {
var $this = $(this);
if ($this.is("[type='radio']") || $this.is("[type='checkbox']")) {
if ($this.prop("checked")) {
$this.attr("checked", "checked");
}
} else {
if ($this.is("select")) {
$this.find(":selected").attr("selected", "selected");
} else {
$this.attr("value", $this.val());
}
}
});
return div.html();
}
and then modify your funciton:-
function updateContentdata() {
var updateSearchContent = getHtml($('#savelistdata'));
var rowNumb = rowCount;
var inFileds = JSON.stringify(field_options);
// var inputValue = $('inptval_' + rowCount).val();
$.ajax({
type: "POST",
url: "<?= $HOMEPAGE_ROOT; ?>/ajax_listuser.php",
data: {
rowNum: rowNumb,
field_options: inFileds,
html: updateSearchContent
},
success: function (data) {
$('#searchusers').submit();
},
error: function (req, status, error) {
console.log(error)
}
});
}
You will probably have to put those values back in the form, since the value="123" is not part of the html when someone fills the form. Iterate over the values you have and find the corresponding form-element, and set its value
I am trying to get a form to work, but when I call ti with ajax, it will not work.
// ----------------------------EDIT----------------------------
I actually found exactly what I was looking for while browsing around.
jQuery Ajax POST example with PHP
I just have one question, would this be the best way to get the data, or could I call it from an array somehow?
post.php
$errors = array(); //Store errors
$form_data = array();
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$_POST['name'])); //Get data
if (!empty($errors)) {
$form_data['success'] = false;
$form_data['errors'] = $errors;
} else {
$form_data['success'] = true;
$form_data['country'] = $query['country'];//Have a bunch of these to get the data.
$form_data['city'] = $query['city'];//Or is there an easier way with an array?
$form_data['zip'] = $query['zip'];
// Etc, etc
}
echo json_encode($form_data);
Then in index.php just call it via:
$('.success').fadeIn(100).append(data.whatever-i-have-in-post);
// ----------------------------v-ORIGINAL-v----------------------------
This is I have so far. At the bottom you can see I have an if statement to check if I could get the results from post, but it always results in "unable to get country" (I'm checking with google.com). I don't know if I am doing it correct or not. Any ideas?
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var dataString = 'name=' + name;
if (name == '') {
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "post.php",
data: dataString
});
}
return false;
});
});
</script>
<form id="form" method="post" name="form" style="text-align: center;">
<input id="name" name="name" type="text">
<input class="submit" type="submit" value="Submit">
<span class="error" style="display:none">Input Empty</span>
<?php
include_once('post.php');
if($query && $query['status'] == 'success') {
$query['country'];
} else {
echo 'Unable to get country';
}
?>
</form>
Post.php
$ip = $_POST['name'];
//$ip = isset($_POST['name']); // I dont know if this makes a difference
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
Try with this after changing the dataString = {name: name}
$(".submit").click(function() {
var name = $("#name").val();
var dataString = {name: name};
if (name == '') {
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
success: function(response) {
// Grab response from post.php
}
});
}
return false;
});
The best way i like to grab the JSON data from ajax request. You can do it by slightly changes in your script.
PHP File
$query = #unserialize(file_get_contents('http://ip-api.com/php/'.$ip));
echo json_encode(array('status'=>true, 'result'=>$query)); // convert in JSON Data
$(".submit").click(function() {
var name = $("#name").val();
var dataString = {name: name};
if (name == '') {
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "post.php",
data: dataString,
dataType: 'json', // Define DataType
success: function(response) {
if( response.status === true ) {
// Grab Country
// response.data.country
// And disply anywhere with JQuery
}
}
});
}
return false;
});
I am new to cakephp and trying to implement AJAX . I have a view add.ctp in which I have written the following lines :
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = "http://localhost/testpage/officenames/get_office_names_by_catagory/";
$.ajax({
type: "GET",
url: url_to_call,
data = data,
//dataType: "json",
success: function(msg){
alert(msg);
}
});
}
});
And the function get_office_names_by_catagory() within OfficenamesController.php is:
public function get_office_name_by_catagory($type = '') {
Configure::write("debug",0);
if(isset($_GET['type']) && trim($_GET['type']) != ''){
$type = $_GET['type'];
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
return 'Hello !';
}
But unfortunately, its not alerting anything ! Whats wrong ?
Could be caused by two issues:
1) In your js snippet, you are querying
http://localhost/testpage/officenames/get_office_names_by_catagory/.
Note the plural 'names' in get_office_names_by_category. In the PHP snippet, you've defined an action get_office_name_by_catagory. Note the singular 'name'.
2) You may need to set your headers appropriately so the full page doesn't render on an AJAX request: Refer to this link.
I think, you have specified data in wrong format:
$.ajax({
type: "GET",
url: url_to_call,
data = data, // i guess, here is the problem
//dataType: "json",
success: function(msg){
alert(msg);
}
});
To
$.ajax({
type: "GET",
url: url_to_call,
data: { name: "John", location: "Boston" }, //example
success: function(msg){
alert(msg);
}
});
You should specify the data in key:value format.
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = "http://localhost/testpage/officenames/get_office_name_by_catagory/"+office_id;
$.ajax({
type: "GET",
url: url_to_call,
success: function(msg){
alert(msg);
}
});
}
});
In your action
public function get_office_name_by_catagory($type = '') {
$this->autoRender = false;
Configure::write("debug",0);
if(!empty($type)){
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
echo 'Hello !';
exit;
}
See what I have done is I have changed your request to function get_office_name_by_catagory, as there is one paramenter $type is already defined in the function, so if I have the request by /get_office_name_by_catagory/2 then you will find value in $type in action.
So no need to use $_GET and rest everything is fine!
Try this,
remove type from ajax and try.
$('#office_type').change(function(){
var office_id = $('#office_type').val();
if(office_id > 0) {
var data = office_id;
var url_to_call = yourlink +office_id;
**$.ajax({
url: url_to_call,
success: function(msg){
alert(msg);
}
});**
}
});
In your action
public function get_office_name_by_catagory($type = '') {
$this->autoRender = false;
Configure::write("debug",0);
if(!empty($type)){
$conditions = array("Officename.office_type"=> $type);
$recursive = -1;
$office_names = $this->Officename->find("all",array("conditions"=>$conditions,"recursive"=>$recursive));
}
$this->layout = 'ajax';
//return json_encode($office_names);
echo 'Hello !';
}