I have a html page through which I am sending data to PHP through ajax but the code is not working.
HTML
<form name='tip' method='post' action=''>
Tip somebody: <input name="tip_email" id=tip_email type="text" size="30" />
<input type="submit" value="Skicka Tips" />
<input type="hidden" id="ad_id" name="ad_id" />
</form>
<script>
$('#submit').click(function() {
event.preventDefault();
$.ajax({
url: insertdata.php,
type: 'POST',
data: {
tip_email: $('#tip_email'),
ad_id: $('#ad_id')
},
success: function(res) {
if (res == 'successful') {
alert("successful");
} else {
alert("failed");
}
},
error: function() {
$('#status').html('Failed').slideDown();
}
});
});
</script>
PHP
<?php
echo "successful"
?>
I have tried various available options on stackoverflow but none of them is working.
enter image description here
Uncaught ReferenceError: $ is not defined
$('#submit').click(function()
Still not working
But when I am including the above script to code it is going in infinite loop and throwing error as "Uncaught RangeError: Maximum call stack size exceeded"
I have done three changes in my existing code.
1) Added script src
I have also tried adding other similar scripts but all showing same error
that means there is some issue with code itself.
2)Added event to statement
$('#submit').click(function(event)
3)placed php in single quotes
url: 'insertdata.php'.
please do correction in code as
1.) add script to below your form close - <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
2.) add id in submit button - <input type="submit" id="submit" value="Skicka Tips" />
Add jquery first to before starting your script. It is not loaded that's why $ is not defined error came.
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
And You are not passing the event object here
$('#submit').click(function() {})
Add it in your code
$('#submit').click(function(event) {});
Or remove the submit type from your input button as
<input type="button" value="Skicka Tips" />
First off, there is no event passed in your
$('#submit').click(function(){})
You'd have to change that to
$('#submit').click(function(event) {})
to work.
Secondly, your
<input type="submit" value="Skicka Tips" />
has no id so jQuery cannot find it using the # identifier.
You either have to change that to
<input type="submit" id="submit" value="Skicka Tips" />
or use the onsubmit event with the form.
Related
For some reason, my form won't post, any ideas as to why(I already know that everything else on my server is operational)? Code below:
PHP
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "<br>";
$ret = file_put_contents('user.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
}
?>
https://pastebin.com/hHeMD4Mq
HTML/AJAX JS
<form id ="form">
<p>Name:</p>
<input name="field1" type="text" id ="name" />
<h3> </h3>
<p>Message:</p>
<textarea name="field2" type="text" id ="message"></textarea><br/>
<button onclick="pos();">reply</button>
</form>
</td>
</table>
</div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
function pos(){
var values=$("form").serialize();
$.post('form.php', values, function(response) {
console.log("Response: "+response);
});}
</script>
https://pastebin.com/eAVE8EGS
demo on my site:
jakesandbox.com/dnd/
(any info not provided above will be provided upon request in the comments)
The problem is your button is actually submitting the form (Which is essentially reloading the page, as it's submitting to itself). You need to do one of 2 things:
Change your button to a type="button" to prevent it from submitting (A button inside of a form element automatically becomes a submit button):
<button type="button" onclick="pos();">reply</button>
Prevent the click action from taking place (Thus preventing the submit):
<button type="button" onclick="pos(event);">reply</button>
<script type="text/javascript">
function pos(e){
e.preventDefault();
var values=$("form").serialize();
$.post('form.php', values, function(response) {
console.log("Response: "+response);
});}
</script>
-OR-
<button type="button" onclick="pos(); return false;">reply</button>
It turns out your form is actually sent normally with GET request (you can probably see the page reload). It occurs when a button inside a form has no specified type (default being submit).
A button of type "submit" inside a form submits the form while a button of type "button" doesn't.
Just add the attribute type="button" to your button and your problem should be solved.
<button type="button" onclick="pos();">reply</button>
On your php end to debug if the data actually came
<?php
header('Content-Type: application/json');
echo json_encode($_POST);
Then on your js
$.post('form.php', values, function(response) {
console.log(response); // return json
});}
This question already has answers here:
JavaScript: Inline Script with SRC Attribute?
(3 answers)
Closed 6 years ago.
I tested my update.php file and it works perfect and there is not any error when i checked my script via console . Only problem in here . Ajax can't send values "id" "comment_area" to update.php file . What is the mistake in here ?
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js">
$(document).ready(function() {
$("#b_news").submit(function(evt) {
evt.preventDefault();
var text = $('#breaking_news_text').val();
var id = 21;
$.ajax({
type: "POST",
url: "update.php",
data: {
comment_area: text,
id: id
},
success: function() {
alert("sucess");
}
});
});
});
</script>
<form id="b_news" method="post" action="">
<div>
<div>
<textarea id="breaking_news_text" class="breaking_news_text" rows="6" cols="50" placeholder="Add text here..." required></textarea>
</div>
</div>
<div>
<input type="button" id="save" value="Save Changes" />
</div>
</form>
<?php
include("./inc/connect.inc.php");
$id=$_POST['id'];
$update = $_POST['comment_area'];
$sql = "update comments set comment_area='$update' Where id='$id'";
$result = mysqli_query($mysqli, $sql)or die("error");
?>
Seems to me that your button simply can't submit the form because of its type.
Try to change the type attribute of the button to submit this way :
<input type="submit" id="save" value="Save Changes"/>
You have two problems.
First you can only have one script per script element. The script can either be referenced by the src attribute or it can be between the start and end tags.
If you try to do both, as you are here, then only the src will be respected.
Use separate <script> elements for your two scripts.
Second, you have no way to trigger the submit event. The submit event will trigger when the form is submitted, but you can't do that from a textarea or a button. Replace the button with a submit button.
Hi all I am developing a site in Codeigniter and I have a form that I am posting using PHP and this is absolutely fine. However I have a small dropdown on the side of my page which I am using to jump between pages - in order to do this I am simply using a href and passing variables within the URL.
I need to POST some data however when they click on the link. I don't wish to use a button and was wondering whether this could be acheived using an ajax onclick() event?? - the data I need to post however is within the form. The code structure is roughly:
<form action="main/postback" method="post">
<input type="hidden" name="pagereference" value="2" />
<input type="hidden" name="supervariable" value="7" />
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
<div>
<ul>
<li><a href = 'http:localhost/landing'>click me</a></li>
</ul>
</div>
When someone clicks on the link I want to send an Ajax Post request, but In the php file that I am posting the data I want to be able to retrieve data from within the form. Is this possible? if so could someone please provide an example AJAX request and how to retrieve the data in PHP as I am majorly confused. I tried the following:
<li><a onclick='myFunction()'>click me</a></li>
<script type="text/javascript">
function myFunction()
{
var "test";
$.ajax({
type: "POST",
url: "http://localhost/ciproject/assessment/test",
dataType: String,
success: function(msg){
alert( "Data Saved: " + msg ); //Anything you want
}
});
window.alert("TEST");
}
</script>
Any ideas would be much appreciated, many thanks
You will probably run into problems using complete urls (with the domain name) due to CORS so I would recommend removing that, but you can easily do what you want using something like:
<li><a class="postFormLink">click me</a></li>
<script type="text/javascript">
$('.postFormLink').on('click', function() {
$.ajax({
type: "POST",
url: "/ciproject/assessment/test",
data: $('form').serialize(),
success: function(msg){
alert( "Data Saved: " + msg ); //Anything you want
}
});
window.alert("TEST");
}
</script>
If you have more than one form on your page, you should add an ID or a class to target it instead of using $('form').
Note that I have also removed the inline event handler.
Try the following:
<form action="main/postback" method="post" id="form1">
<input type="hidden" name="pagereference" value="2" />
<input type="hidden" name="supervariable" value="7" />
First name: <input type="text" name="firstname"><br>
Last name: <input type="text" name="lastname">
</form>
<li><a id="clickme">click me</a></li>
<script type="text/javascript">
$(function () {
$("#clickme").click(function () {
var form_data = $('#form1').serialize();
$.ajax({
type: "POST",
dataType: "text",
url: "ciproject/assessment/test",
data: form_data,
success: function(response){
alert('Job well done');
}
})
})
})
</script>
The following should work, if you put it into your ajax options. You will need to identify your form, the easiest way is to use an id.
data: $("#theFormId").serialize()
-- EDIT: This turns out not to be a js issue but a "Mixed Active Content" issue in Firefox 24.0. --
Locally, an event handler correctly intercepts a form submission; however, on Heroku, the application instead issues an HTTP request and the appropriate Javascript function is never called.
My webpage has the following Javascript:
<script id="infrastructure-cxn" type="application/javascript">
$(function () {
// [additional code ... ]
$("#message-form").submit(function (event) {
event.preventDefault();
var msg = $("#msg-input").val();
var msgObject = { text: msg };
server.publish(channel, msgObject);
});
});
</script>
My webpage has the following form:
<form id="message-form" accept-charset="UTF-8">
<!-- [additional code ...] -->
<div class="field">
<input
id="msg-input"
type="text"
placeholder="Enter message..." />
</div>
<input
class="btn btn-xs btn-primary"
type="submit"
value="Send" />
</form>
Could anyone offer any suggestions as to how I can fix my application so that in production it doesn't issue either GET or POST requests but instead calls the anonymous function in my event handler?
I have this code here that ajaxifies my web-application.
$.get(State.url, function(data) {
console.log($(data).find('#main-content').text());
$('#main-content').html($(data).find('#main-content').html());
},"html");
In some certain point the user should upload a file, but since it is ajaxified it will only load the parent container of the incoming response which is this.
<form enctype="multipart/form-data" class="contact_form" action="doUploadAudio">
<input type="file" name="file" value="" id="file"/>
<script>
console.log("HEHE");
$('#fileupload').fileupload({
replaceFileInput:false,
done: function (e, data) {
alert("DONE");
$('#main-content').html('');
$('#main-content').html($(data.result).find('#main-content').html());
}
});
</script>
<button class="btn" id="uploadAudio" type="submit" class="submit" data-loading-text="Uploading...">Upload</button>
</form>
As you can see my form is not executing its script tags, is there anyway I can execute it?
Note that I am currently using jQuery 1.8.3
First of all, I don't see any element with an id fileupload in your HTML?
Anyway, you should avoid loading HTML containing <script> tags, as the behavior of the JavaScript loaded is unpredictable.
Firstly, you should your HTML separate and load it in separately:
<form enctype="multipart/form-data" class="contact_form" action="doUploadAudio">
<input type="file" name="file" value="" id="file"/>
<button class="btn" id="uploadAudio" type="submit" class="submit" data-loading-text="Uploading...">Upload</button>
</form>
And then you can either execute the JavaScript in the success callback of the $.get:
$.get(State.url, function(data) {
console.log($(data).find('#main-content').text());
$('#main-content').html($(data).find('#main-content').html());
$('#fileupload').fileupload({
replaceFileInput:false,
done: function (e, data) {
alert("DONE");
$('#main-content').html('');
$('#main-content').html($(data.result).find('#main-content').html());
}
});
},"html");
Or put the snippet of JavaScript (without the <script> tags) in a JS file on the server (e.g. fileupload.js) and then call it like so:
$.get(State.url, function(data) {
console.log($(data).find('#main-content').text());
$('#main-content').html($(data).find('#main-content').html());
$.getScript("<url to fileupload.js>", function() {
console.log("Fileupload should now be working");
});
},"html");