AJAX Request Payload not showing up in console log - javascript

I am learning AJAX and I am trying to log all the data parameters in the console in case of success and in case of a failure to throw an alert. My code works and I can successfully dump the data I send, but nothing shows up in the console, even though I explicitly put console.log within the Javascript to register that.
this is my code.
Html page
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h2>Send JSON</h2>
<form action="postrequest.php" class="js-ajax-php-json" method="post" accept-charset="utf-8">
<input type="text" name="param1"/>
<input type="text" name="param2"/>
<input type="text" name="param3"/>
<button type="submit">Submit</button>
</form>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
$("document").ready(function(){
$(".js-ajax-php-json").submit(function(){
var param1 = $("#param1").val();
var param2 = $("#param2").val();
var param3 = $("#param3").val();
$.ajax({
url : 'postrequest.php',
contentType: "application/json",
dataType: "json",
type : 'POST',
data: JSON.stringify({
param1: param1,
param2: param2,
param3: param3
}),
success: function(data) {
console.log(data);
},
error: function (data) {
alert(data.param3);
}
});
});
});
</script>
</html>
postrequest.php
<?php
var_dump( $_POST);
What am I doing wrong?

Error 1: Remove the form tag. It will work because it contains action="postrequest.php". You are doing 2 things at the same time.
Submitting the form via PHP using the form tag.
You are performing ajax and submitting the form.
Error 2: You are writing var param1 = $("#param1").val(); Where is the param1, param2,param3 you defined?
Error 3: You are giving the jquery link, you don't have closed the script tag.
Error 4: You are sending the data in ajax and outputting the ajax response again with the same variable
Error 5: Ajax error block you have created is wrong.
<!DOCTYPE html>
<html>
<body>
<input type="text" name="param1" id="param1"/>
<input type="text" name="param2" id="param2"/>
<input type="text" name="param3" id="param3"/>
<input type="button" value='Submit' class="js-ajax-php-json" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".js-ajax-php-json").click(function() {
var param1 = $("#param1").val();
var param2 = $("#param2").val();
var param3 = $("#param3").val();
$.ajax({
url: 'postrequest.php',
dataType: "html",
type: 'post',
data: {
param1: param1,
param2: param2,
param3: param3
},
success: function(rsp) {
console.log(rsp);
},
error: function(jqXHR, status, err) {
console.log("Error");
},
});
});
});
</script>
</body>
</html>
postrequest.php page
<?php
print_r($_POST);
?>
I have just rewritten your code with a very simpler one. You can
change it as per your requirement.

I think the root cause is that the page is reloading once you hit submit. Hence you cannot see anything in the console. Try the following steps.
Remove the 'action' and 'method' attributes from the form tag. This is already handled in ajax request.
Add onsubmit="return false;" attribute to the form tag. This will prevent reloading of the page.

Related

ajax submit form why it cannot echo $_POST

I'm test using ajax submit form (submit to myself page "new1.php")
The thing that I want is, after click submit button, it will echo firstname and lastname. But I don't know why I do not see the firstname and lastname after submit.
here is new1.php page
<?php
echo $_POST['firstname']."<br>";
echo $_POST['lastname']."<br>";
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<form id="myform" action="new1.php" method="post">
Firstname : <input type="text" name="firstname"> <br>
Lastname : <input type="text" name="lastname"> <br>
<input type="submit" value="Submit">
</form>
<script>
// this is the id of the form
$("#myform").submit(function(e) {
$.ajax({
type: "POST",
url: 'new1.php',
data: $("#myform").serialize(), // serializes the form's elements.
success: function(data)
{
alert('yeah'); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
</script>
</body>
</html>
In your case the best option to retrieve values as JSON format using json_encode in your PHP code and then accessing these values through data object.
Example:
PHP code:
if($_POST)
{
$result['firstname'] = $_POST['firstname'];
$result['lastname'] = $_POST['lastname'];
echo json_encode($result);
die(); // Use die here to stop processing the code further
}
JS code:
$("#myform").submit(function (e) {
$.ajax({
type : "POST",
url : 'new1.php',
dataType : 'json', // Notice json here
data : $("#myform").serialize(), // serializes the form's elements.
success : function (data) {
alert('yeah'); // show response from the php script.
// make changed here
$('input[name="firstname"]').text(data.firstname);
$('input[name="lastname"]').text(data.lastname);
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
When you use form as a serialize you have to retrieve like this.
Edit your ajax like this :
data: { formData: $("#myform").serialize()},
Then you can retrieve like this in your controller:
parse_str($_POST['formData'], $var);
echo "<pre>";
print_r($var);
exit;
Make some changes in javascript here:
success: function(data)
{
$('#response').html(data); // show response from the php script.
}
And in html code make a div with id response
<div id="response"></div>
Change from
alert('yeah'); // show response from the php script.
to
alert(data); // show response from the php script.
the value firstname, lastname will not display because you called the new1.php via ajax and the data (firstname, lastname and the page code) is returned to java script variable (data) you need to inject the data to your document
Try this
$.ajax({
type: "POST",
url: 'new1.php',
data: $("#myform").serialize(), // serializes the form's elements.
success: function(data) {
document.documentElement.innerHTML = data;
}
});

JavaScript/Ajax - How to run one PHP script before posting form to another one

I am almost at my wit's end trying to figure out why my code is not working.
Here is what I am trying to do:
1) Accept several variables in a form (myform).
2) Using an onsubmit, I want to use pass one or more of those variables to a script (process_info).
3) After process_info has executed, the form should be posted to the form's action URL ('save_info.php').
As you can see in the code below, I have tried several things:
Test 1: This simple alert is shown and the form is submitted to save_info.php.
Test 2: I copied and modified this jQuery script from another page on this site. No matter what I do, the script does not run. I know this because no alert message is shown.
Test 3: After removing the jQuery(document).ready statement from Test 2, the senddata function runs. Although it runs the process_info script, the form does not get posted to save_info.
<html>
<head>
<title>Form Test</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javaScript">
/* Test 1: this works - form is submitted to the action URL
function senddata() { alert('here'); }
*/
/* Test 2: this does not run (no alert shown) - form is submitted to the action URL */
jQuery(document).ready(function() {
function senddata() {
var formdata = jQuery("#myform").serialize();
var decoded = decodeURIComponent(formdata);
strip = decoded.replace(/[\[\]]/g, "_");
// alert(strip);
jQuery.ajax({
type: "POST",
url: 'process_info.php',
data: strip,
success: function(){ alert('success'); },
error: function(){ alert('failure'); },
complete: function(){
jQuery("#myform").submit(); //submit the form after ajax completes
}
});
return false; //stop the form from initially submitting
}
});
/* Test 3: this runs and the AJAX URL is executed, "success" is displayed - form is NOT submitted to the action URL
function senddata() {
var formdata = jQuery("#myform").serialize();
var decoded = decodeURIComponent(formdata);
strip = decoded.replace(/[\[\]]/g, "_");
// alert(strip);
jQuery.ajax({
type: "POST",
url: 'process_info.php',
data: strip,
success: function(){ alert('success'); },
error: function(){ alert('failure'); },
complete: function(){
jQuery("#myform").submit(); //submit the form after ajax completes
}
});
return false; //stop the form from initially submitting
}
*/
</script>
</head>
<body>
<form name="myform" id="myform" onsubmit="return senddata()" action="save_info.php" method="post" enctype="multipart/form-data">
<input type="text" name="id" />
<input type="text" name="last" />
<input type="submit" value="send" />
</form>
</body>
</html>
I assume that what I am trying to do is actually possible. What am I doing wrong?
ok, I have edited your code in a way that it works and I'll explain a few changes after the code.
<html>
<head>
<title>Form Test</title>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javaScript">
/* Test 2: this does not run (no alert shown) - form is submitted to the action URL */
jQuery(document).ready(function(){
$("#myform").submit(function(event){
event.preventDefault();
var formdata = jQuery("#myform").serialize();
var decoded = decodeURIComponent(formdata);
strip = decoded.replace(/[\[\]]/g, "_");
// alert(strip);
jQuery.ajax({
type: "POST",
url: 'process_info.php',
data: strip,
success: function(){ alert('success'); },
error: function(){ alert('failure'); },
complete: function(){
jQuery("#myform")[0].submit(); //submit the form after ajax completes
}
});
return false; //stop the form from initially submitting
});
});
</script>
</head>
<body>
<form name="myform" id="myform" action="save_info.php" method="post" enctype="multipart/form-data">
<input type="text" name="id" />
<input type="text" name="last" />
<input type="submit" value="send" />
</form>
</body>
</html>
So, first I have removed onsubmit from the <form> element in the html
Then changed the function the same as you did in your comment.
The last trick is that if I wanted to use jQuery("#myform").submit(); in the complete section of the ajax it would add another listener for the form submit event and would call the function again and again and again.
So I had to access the HTML form element directly and call the submit for it, that's the trick as you can see jQuery("#myform")[0].submit();

How to send a GET Request using Jquery?

Trying to send a simple Jquery GET request, which doesn't work.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#clk").click(function() {
$.get('http://www.abelski.com/courses/ajax/emailajaxservice.php', { email: 'mymail#example.com'}, function() {
alert("Sent");
});
});
});
</script>
</head>
<body>
<input type="text" id="email" />
<input type="button" id="clk" />
<span id="res"></span>
</body>
</html>
http://www.abelski.com/courses/ajax/emailajaxservice.php is on.
I don't get any alert. what is the problem in my code?
Why don't you try this one:
$.ajax({
type: "GET",
url: RequestURL,
dataType: "html",
success: function(htm) {
alert(htm);
}
}
});
In your code snippet, the function
function() { alert("Sent"); }
will be called when the request succeeds. If it fails for any reason (cross-domain requests are forbidden, answer returns with a non OK code, ...) nothing will be executed.
You can add a .fail() listener to see if an error was triggered :
$.get( ... ).fail(function(){ alert("Error"); });
Check your web console to have more detail on the failure.

Jquery ajax with google app engine post method

Just trying to learn using ajax with appengine,started with the post method,but it does not work.
This is my HTML Code for the page
<html>
<head>
<title> Hello </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
var data={"name":"Hola"};
$(document).ready(function(){
$('#subbut').click(function(){
$.ajax({
url: '/test',
type: 'POST',
data: data,
success: function(data,status){
alert("Data" + data +"status"+status);
}
});
});
});
</script>
</head>
<body>
<form method="post" action="/test">
<input type="submit" id="subbut">
</form>
<div id="success"> </div>
</body>
</html>
Here goes my python code to render the above html code , its handler is /test1
from main import *
class TestH1(Handler):
def get(self):
self.render('tester.html')
And this is the python script to which AJAX request must be sent to,handler is /test.
from main import *
import json
class TestH(Handler):
def post(self):
t=self.request.get('name')
output={'name':t+" duck"}
output=json.dumps(output)
self.response.out.write(output)
Expected behavior is that when i click on submit button,i get an alert message saying "Hola duck" , get nothing instead.
Any help would be appreciated as i am just starting with AJAX and Jquery withGAE
At first, I suppose you should suppress default behavior of form submitting when you press submit button by adding "return false" to the .click function. But I suppose it would be better to use just
<input type="button" id="subbut">
instead (even without form).
Then you should add "dataType: 'json'" to your ajax call to tell jQuery what type of data you expect from server. Doing this you will be able to get response data by property names like "data.name". So:
var data={"name":"Hola"};
$(document).ready(function(){
$('#subbut').click(function(){
$.ajax({
url: '/test',
type: 'POST',
data: data,
dataType: 'json',
success: function(data,status){
alert(data.name);
alert("Data" + data +"status"+status);
}
});
return false;
});
});
and it would be better if you set appropriate content type header to your response:
response.headers = {'Content-Type': 'application/json; charset=utf-8'}
self.response.out.write(output)

Formulate JSON in JavaScript from HTML form textarea values and Post?

I want to have an HTML form that posts the following in an Http-request body.
{ “info” : {
“id” : “123”
“text1” : <comes from html text-box>
}
So, what I want is to formulate the above as a JavaScript Object, and then post this JavaScript object on submit. The value of “text1” will be coming from user input, that will be an html-form textarea input box. The first value “id” will be hard-coded, or could also come from a hidden text-box.
So my question is: how can I write a piece of JavaScript to achieve this, together with the corresponding html form, etc.
It is easiest to do this using jQuery.
First, initialize a JavaScript object with your data. Then, use jQuery to extract the text from the text box and assign it to the desired property in your object.
var data = {
"info": {
"id":"123",
"text1":""
}
};
data.info.text1 = $("#yourTextBox").val();
Then you can use jQuery.ajax to make the request:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
See the jQuery documentation for posts:
http://api.jquery.com/jQuery.post/
EDIT:
Using inline javascript, your HTML would look something like this (not using jQuery to grab the form data):
<html>
<head>
<script>
var data = {
"info": {
"id":"123",
"text1":""
}
};
function makeRequest()
{
data.info.text1 = document.forms["frm1"]["fname"].value;
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
}
</script>
</head>
<body>
<form name="frm1" id="yourTextBox" onsubmit="makeRequest()">
<input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
<html>
<head>
<script>
function sendJson()
{
var x=document.forms["alfa"]["text1"].value;
str1="{ 'info' : { 'id' : '123' 'text1' : ";
str2=str1.concat(x);
body=str2.concat(" }");
document.forms["alfa"]["text1"].value=body;
}
</script>
</head>
<body>
<form id="alfa" onsubmit="return sendJson()">
Text1: <input id="text1" type=text size=50>
<input type="submit" value="Submit">
</form>
</body>
</html>
The best way is to use JSON.parse()

Categories

Resources