AJax not calling php file correctly, html forms - javascript

UPDATE:
This is the error:
412 (Precondition Failed)
I am trying to call a php script from ajax, I currently have the below ajax, which when the button in the form (also below) is clicked will call a php script passing it the form data, which will then be submitted to the database.
However, it is not working; and what's more I am just getting a blank error back, so I do not even know what is going wrong.
Could someon please point me in the right direction?
Thanks.
HTML form:
<form name="report-form" id="report-form" action="" method="POST">
<textarea id="reason-box" type="text" name="reason-box" cols="40" rows="5" maxlength="160" onkeypress=""></textarea>
<input id="reportedID" name="reportedID" type="text" />
<!--<input id="report-submit" value="" name="submit" type="submit" onclick="submitReport()"/> -->
<button id="report-submit" name="submit" onclick="submitReport()"></button>
</form>
AJax call:
function submitReport()
{
var ID=$('#reportedID').val();
var reason=$('#reason-box').val();
var formData = "ID="+ID+"&reason="+reason;
alert(formData);
//This code will run when the user submits a report.
$.ajax(
{
url: 'submit_report.php',
type: "POST",
data: formData,
success: function(data)
{
alert("Report Submitted!");
},
error: function(xhr,err)
{
alert(err.message);
alert("responseText: "+ xhr.responseText);
}
});
}
Now I have already tested the php script, and that works fine, the problem started when I added the ajax call so I know it is something to do with the ajax not the php.

This should correct the problem with submitting:
Your jQuery Ajax call won't succeed because the POST data isn't supplied in the correct format.
If the ajax should succeed the form is also posted resulting in a 405 error.
<button id="report-submit" name="submit" onclick="submitReport(event)"></button>
function submitReport(event)
{
event.preventDefault();
....... // your code
}
Now the default action of your form will be prevented (resulting in a 405 error). And only the ajax request is submitted.
In the button element we pass the event object on to the function. We use event.preventDefault() to make sure the button doesn't run it's default action, which is submitting the form.
You could also prevent this by deleting the form element as a wrapper, but maybe you want to use other features (like validation) on the form.
Form data in a jQuery ajax request needs to be an object called data:
var formData = {"ID" : ID, "reason" : reason};
jQuery will reform this to a correct query string for the submit.

I would do it like this:
<form name="report-form" id="report-form" action="" method="POST">
<textarea id="reason-box" type="text" name="reason-box" cols="40" rows="5" maxlength="160"></textarea>
<input id="reportedID" name="reportedID" type="text" />
<button id="report-submit" type="submit" name="submit" value="submit"></button>
</form>
<script type="text/javascript">
jQuery("document").ready(function(){
var $ = jQuery
$("form").submit(function(){
var data = "";
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
url: "submit_report.php",
data: data,
success: function(data)
{
alert("Report Submitted!");
},
error: function(xhr,err)
{
alert(err.message);
alert("responseText: "+ xhr.responseText);
}
});
return false;
});
});
</script>
and then use $reason=$_POST['reason-box']; and $ID=$_POST['reportedID']; inside your PHP script

this is optional to choose the form for submitting data or you can do it without the HTML form this is what i do
<textarea id="reasonbox" type="text" name="reason-box" cols="40" rows="5" maxlength="160" onkeypress=""></textarea>
<input id="reportedID" name="reportedID" type="text" />
<button id="report-submit" ></button>
and the using folloing javascript and jquery style
<script type="text/javascript">
$(function() {
$("#report-submit").click(function(){
try
{
$.post("your php page address goes here like /mypage.php",
{
//in this area you put the data that is going to server like line below
'reasonbox':$("#reason-box").val().trim(),
'reportedID':$("#reportedID").val().trim()
}, function(data){
data=data.trim();
//this is data is sent back from server you can send back data that you want
//like message or json array
});
}
catch(ex)
{
alert(ex);
}
});
});
</script>
I hope it helps

Related

Ajax Call using Jquery in HTML and take a response to other Html Page

I am doing this for the first time. i want a data of another HTML page using AJAX call and jQuery in HTML page.
Below is mycode
this is my .js code
<script type="text/javascript">
$(document).ready(function()
{
$('#submit').click(function(){
var name =$('#name').val();
var pass =$('#passsword').val();
if(name=='' || pass==''){
alert('first fill the details');
}
else {
$.ajax({
method:'POST',
url:"login.html",
data:{name:name,
password:pass},
daatType:"HTML",
success:function(status) {
alert('success');
$('#div').html(status);
}
})
}
})
})
this is my Html code
<form>
<label>Name:</label><input type="text" id="name"><br>
<label>Password:</label><input type="text" id="password"><br>
<button type="submit" id="submit" >Submit</button>
</form>
<h2 id="div"></h2>
please help
Change dataType:"HTML" to dataType:"json"
dataType:'json' // its mean server return type data
whereas
contentType:'json' // send data type to server should be json

Not posting jQuery form

I'm trying to post a form via Ajax, and I came across jQuery's POST, which sounds like the propper tool to use. I tried using the following html form:
<form id="my_form" action="http://localhost:4567/pedidos/guardar" method="POST">
Name:<br>
<input type="text" name="person_name"><br>
Amount:<br>
<input type="text" name="amount">
<br>
<input type="submit" value="Submit" id="submit_form">
</form>
<script type="text/javascript">
$('#submit_form').click( function() {
$.post( 'http://localhost:4567/pedidos/guardar', $('#my_form').serialize(), function(data) {
// ... do something with response from server
alert( "Data saved: " + data );
},
'json' // I expect a JSON response
);
});
</script>
This form was built based on this SO answer
I'm expecting to POST the form to /pedidos/guardar. On the server side, to test that the form is properly posted, I created a really small Sinatra script:
require 'sinatra'
require 'json'
not_found do
status 404
"This page could not be found"
end
get '/' do
"Hello World!"
end
get '/pedidos' do
{ :person_name => "#{params[:person_name]}" }.to_json
end
post '/pedidos/guardar' do
#{}"I got #{params[:person_name]}."
{ :person_name => "#{params[:person_name]}" }.to_json
end
When using my form, I'm getting {"person_name":"Juan"}, which is the expected response from Sinatra. But I'm not getting any alert window, it's like no Ajax is being used at all.
What am I missing in my form to make it work with Ajax? Do I need the action and method="POST" there?
Thanks in advance
You are sending your data throw ajax: $.post is a shorthand to $.ajax, but as the documentation explains it, you have to get a reference to the submit event and stop the default action.
$('#submit_form').click( function( event ) {
// Stop form from submitting normally
event.preventDefault();
Try replacing the script with this
$('#submit_form').click( function(){
$.ajax({
url: 'http://localhost:4567/pedidos/guardar',
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify($('#my_form').serialize()),
success: function(data){
alert( "Data saved: " + data );
}
});
});
setting the contentType is for the response data type.

Ajax form with separate action values

I have a contact form with multiple submit buttons which have different action values.
<form action="confirm.php" data-query="send.php" method="POST" class="form">
I am using data-query attribute to fetch action link for one of the submit buttons.
<input type="submit" name="submit1" id="submit1">
<input type="submit" name="submit2" id="submit2" value="Submit B">
Ajax code is below:
<script>
$(function() {
$('#submit2').click(function(e) {
var thisForm = $('.form');
e.preventDefault();
$('.form').fadeOut(function() {
$("#loading").fadeIn(function() {
$.ajax({
type: 'POST',
url: thisForm.attr("data-query"),
data: thisForm.serialize(),
success: function(data) {
$("#loading").fadeOut(function() {
$("#success").fadeIn();
});
}
});
});
});
})
});
</script>
I am getting the success message but the php code isn't getting executed.
The PHP code is working fine without the AJAX method.
.serialize() doesn't give you button values, you'll have to add it manually, something like
data: thisForm.serialize()+'?button2=Submit%20B',

Popuating form fields from MySQL using AJAX and Jquery

I followed a tutorial to adapt the code. Here I am trying trying to auto-populate my form fields with AJAX when an 'ID' value is provided. I am new to Jquery and can't get to work this code.
Edit 1 : While testing the code, Jquery isn't preventing the form to submit and sending the AJAX request.
HTML form
<form id="form-ajax" action="form-ajax.php">
<label>ID:</label><input type="text" name="ID" /><br />
<label>Name:</label><input type="text" name="Name" /><br />
<label>Address:</label><input type="text" name="Address" /><br />
<label>Phone:</label><input type="text" name="Phone" /><br />
<label>Email:</label><input type="email" name="Email" /><br />
<input type="submit" value="fill from db" />
</form>
I tried changing Jquery code but still I couldn't get it to work. I think Jquery is creating a problem here. But I am unable to find the error or buggy code. Please it would be be very helpful if you put me in right direction.
Edit 2 : I tried using
return false;
instead of
event.preventDefault();
to prevent the form from submitting but still it isn't working. Any idea what I am doing wrong here ?
Jquery
jQuery(function($) {
// hook the submit action on the form
$("#form-ajax").submit(function(event) {
// stop the form submitting
event.preventDefault();
// grab the ID and send AJAX request if not (empty / only whitespace)
var IDval = this.elements.ID.value;
if (/\S/.test(IDval)) {
// using the ajax() method directly
$.ajax({
type : "GET",
url : ajax.php,
cache : false,
dataType : "json",
data : { ID : IDval },
success : process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
}
else {
alert("No ID supplied");
}
};
function process_response(response) {
var frm = $("#form-ajax");
var i;
console.dir(response); // for debug
for (i in response) {
frm.find('[name="' + i + '"]').val(response[i]);
}
}
});
Ajax.php
if (isset($_GET['action'])) {
if ($_GET['action'] == 'fetch') {
// tell the browser what's coming
header('Content-type: application/json');
// open database connection
$db = new PDO('mysql:dbname=test;host:localhost;', 'xyz', 'xyz');
// use prepared statements!
$query = $db->prepare('select * from form_ajax where ID = ?');
$query->execute(array($_GET['ID']));
$row = $query->fetch(PDO::FETCH_OBJ);
// send the data encoded as JSON
echo json_encode($row);
exit;
}
}
I don't see where you're parsing your json response into a javascript object (hash). This jQuery method should help. It also looks like you're not posting your form using jquery, but rather trying to make a get request. To properly submit the form using jquery, use something like this:
$.post( "form-ajax.php", $( "#form-ajax" ).serialize() );
Also, have you tried adding id attributes to your form elements?
<input type="text" id="name" name="name"/>
It would be easier to later reach them with
var element = $('#'+element_id);
If this is not a solution, can you post the json that is coming back from your request?
Replace the submit input with button:
<button type="button" id="submit">
Note the type="button".
It's mandatory to prevent form submition
Javascript:
$(document).ready(function() {
$("#submit").on("click", function(e) {
$.ajax({type:"get",
url: "ajax.php",
data: $("#form-ajax").serialize(),
dataType: "json",
success: process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
});
});

Form Post data using Ajax and jquery

I have a Form
<script type="text/javascript" src="result.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<form name="form" method="POST" id="form">
<input type="text" value="" id="htno" name="htno" Maxlength="12" style="width:165px;" class="bodytext"></input>
<input type="button" value="Submit">
</form>
<div id="result" class="result"></div>
And result.js file is
$("#form").submit(function (event) {
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$.ajax({
url: "url",
type: "post",
data: "htno=" + htno + "&code=2132",
success: function () {
alert("success");
$("#result").html('submitted successfully');
},
error: function () {
alert("failure");
$("#result").html('there is error while submit');
}
});
});
htno is the value the user enters through form
Data to be posted is htno & code
i am unable to get output using this, please can u tell me the fault . . . .
You should know that a form is submitted when the input type is submit.In your code change the type of button to submit.
just change the part
<input type="button" value="Submit" >
to
<input type="submit" value="Submit" >
and in your result.js remove this line
event.preventDefault();
because this line prevent your form from submitting without any reason.
try changing your
$("#form").submit(function(event) {
event.preventDefault();
by
$(document).on('submit','#form',function(e) {
e.preventDefault();
alto, try to alert data
The page you are trying to connect use temporary tokens. You cannot do what you are looking for. You are not allowed to do it. Ask owner of site for kind of API access, he could make you a good price... { this topic should be closed! }

Categories