PHP and Ajax posting - javascript

I'm using jQuery form plugin to send ajax requests. Which you can find on below url
http://malsup.com/jquery/form/
This is my jQuery code
$(document).ready(function()
{
$('#SubmitForm').on('submit', function(e)
{
e.preventDefault();
$('#submitButton').attr('disabled', '');
$(this).ajaxSubmit({
target: '#output',
success: afterSuccess //call function after success
});
});
});
function afterSuccess()
{
$('#submitButton').removeAttr('disabled'); //enable submit button
}
This code is displaying out put on the div id output and each time i submitted code will remove the old out put and display the new one. What i want to do is, keep the old out and display the new out put on top of the old output. Can someone tell me how to do this.

What you could do, is alter your afterSuccess method a little bit. What I did was:
function afterSuccess(text)
{
$('#output').prepend(text)
$('#submitButton').prop('disabled', false);
}
The whole fiddle is available here
The whole code of javascript:
function afterSuccess(text)
{
$('#output').prepend(text)
$('#submitButton').prop('disabled', false);
}
$(document).ready(function()
{
$('#submitButton').click(function(e)
{
$('#submitButton').prop('disabled', true);
$('#SubmitForm').ajaxSubmit({
data: {
html: "<p>Text echoed back to request</p>",
delay: 1
},
success: afterSuccess,
url: '/echo/html/'
});
});
});
and of course assuming following html structure
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/3.51/jquery.form.min.js"></script>
<body>
<form id="SubmitForm" method="POST">
<input type="button" id="submitButton" value="submit"/>
</form>
<div id="output">
test
</div>
</body>

Related

Button and AJAX not responding

Im working on trying to get a button to run a php script with AJAX. To be clear I am really new to javaScript and PHP so my code might be completely wrong. I think that the problem is in my button click code not so much the ajax code. Any help is great
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
</script>
<div>
<form id="form">
Name of Product: <input type="text" name="productName" value="Enter Here">
<input type="button" name="submit" value="Submit" class="submit">
</form>
</div>
You need a DOM ready wrapper around the jQuery because it executes before the element exists (or is rendered by the browser).
You can use either $(function(){ }) or $(document).ready(function(){ });.
$(function(){
$(".submit").click(function myCall() {
var subdata = $("#form").serializeArray();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata
});
return false;
});
});
In this case, you don't need serializeArray() but simply serialize().
There is no success or complete function defined and so you wouldn't see anything when submitting this, unless of course you watch the developer console/net tab.
Also, using a form's submit event is preferred to the submit button's click event.
$(function(){
$("#form").submit(function myCall() {
var subdata = $(this).serialize();
var request = $.ajax({
url: "construct_new.php",
type: "GET",
data: subdata,
success : function(response){
console.log("success!");
}
});
return false;
});
});
Put your jQuery inside a document ready like this, and prevent the default action (to submit the form):
<script type="text/javascript">
$(document).ready(function(){
$(".submit").click(function(e) {
e.preventDefault();
var subdata = $("#form").serializeArray();
$.get("construct_new.php",{data: subdata}, function(){
console.log(data); // whatever returned by php
});
});
});
</script>
Document ready makes sure page has finished loading everything. e.preventDefault() stops the default action (for a form, submission, for an a tag, following the link).

Call AJAX to send value with button

I read a lot of similar questions, and I tried all solutions but nothing seems to work. I want to send an AJAX request by clicking a button and send what the user typed in a textarea and display it in a div(chatbox). When I click the button, nothing happens. It never calls the function that has the AJAX code. Do you have any ideas what is going on?
P.S. I included the JavaScript files but nothing's changed.
<form action="ajax()">
<textarea id="txtArea" name="txtArea" ></textarea>
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
//AJAX function
function ajax() {
alert("insert");
var txtArea = $("#txtArea").val();
$.ajax({
type: "POST",
url: "InsertMessage.php",
data: {
txtArea: txtArea
}
success: function(data) {
alert(data);
$("#chatbox").load("DisplayMessages.php")
$("#txtArea").val(""); //Insert chat log into the #chatbox div
}
error: function() {
alert('there was an error, write your error handling code here.');
}
});
}
$(document).ready(startAjax);
//setInterval(function(){
// $("#chatbox").load("DisplayMessages.php");
//}//,1400);
</script>
Your question is not so clear, But for sending data in post method when submiting a form and then show result in a div, try something like this:
html:
<form>
<textarea id="txtArea" name="txtArea" ></textarea>
<input type="submit">
</form>
<div id="resultDiv">
</div>
js:
$( "form" ).submit(function( event ) {
var txtArea = $("#txtArea").val();
$.ajax({
type:"POST",
url:"InsertMessage.php",
data:{txtArea:txtArea}
success: function(data){
alert(data);
$("#resultDiv").html(data);
}
error: function(){
alert('there was an error, write your error handling code here.');
}
});
});
The action attribute has to contain a URL, not Javascript. You can use:
<form action="javascript:ajax()">
or:
<form onsubmit="ajax(); return false;">
or you can bind the event in jQUery:
$(document).ready(function() {
$("form").submit(function() {
ajax();
return false;
});
});

Unable to get data from Wikipedia API

I am working on a 'Wikipedia Viewer' project, where you enter a search term and see a list of Wikipedia search results, but it is far from complete.
Until now I have just written the code to display the first search term. But it doesn't work.
My HTML:
<div class="container-fluid">
<div class="searchAndButtons">
<input type="text" id="search">
<button class="btn" id="searchBut">Search</button>
<form action="https://en.wikipedia.org/wiki/Special:Random"><button class="btn">Random Wiki Article</button>
</form>
</div>
<div class="searchResults">
</div>
</div>
My CSS:
.container-fluid{
padding:5%;
}
.searchAndButtons{
text-align:center;
}
My Javascript:
$(document).ready(function(){
$("#searchBut").on("click",function(){//this is click handler
var searchTerm=document.getElementById("#search").value;
searchTerm=searchTerm.replace(/\s/g,"+");
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles="+searchTerm+"&rvprop=content&format=json&rvsection=0&rvparse=1",function(json){
$(".searchResults").html(JSON.stringify(json));
});
});
});
Where am I going wrong? When I run the code in Codepen and check the console, it shows an error "TypeError: document.getElementById(...) is null".
My project on codepen - link
$(document).ready(function(){
$("#searchBut").on("click",function(){//this is click handler
var searchTerm=document.getElementById("search").value;
searchTerm=searchTerm.replace(/\s/g,"+");
$.getJSON("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles="+searchTerm+"&rvprop=content&format=json&rvsection=0&rvparse=1",function(json){
$(".searchResults").html(JSON.stringify(json));
});
});
});
Update your JS code with this. id gets value by 'search' not '#search'
UPDATE: To add headers you can do the following
$(document).ready(function(){
$("#searchBut").on("click",function(){//this is click handler
var searchTerm=document.getElementById("search").value;
searchTerm=searchTerm.replace(/\s/g,"+");
$.ajax({
url: 'http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles="+searchTerm+"&rvprop=content&format=json&rvsection=0&rvparse=1', //your request URL
type: 'GET',
dataType: 'json',
success: function() { alert('hello!'); },
error: function() { alert('boo!'); },
beforeSend: setHeader
});
});
function setHeader(xhr) {
xhr.setRequestHeader('securityCode', 'Foo'); //your header key and value
}
});
});

Ajax: link in ajax response is not working

I have tried all possible solutions suggested, but it is still not working for me.
I am using ajax call to a php page, say livesearch.php, from index page to get live search result.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$("#livesearch").on("click", "a.alert", function() {
alert("here");
});
</script>
<script>
function showResult(str) {
if (str.length == 0) {
$("#livesearch").empty();
$("#livesearch").css('display', 'none');
return;
}
$.ajax({
type: "GET",
url: "livesearch.php?q=" + str,
success: function(responseText) {
$("#livesearch").html(responseText);
$("#livesearch").css('display', 'block');
$("#livesearch").css('background', '#fff');
}
});
}
</script>
</head>
<body>
<form>
<input type="text" size="30" onkeyup="showResult(this.value)" onblur="showResult('')" placeholder="search here">
<div id="livesearch" style="height:500px;width:900px;overflow-y:scroll;display:none;z-index:99999;"></div>
</form>
<div id="gentext" style="position:fixed;top:40px;z-index:-1;">This is just a dummy text to check if result div overshadow this line or not.</div>
</body>
</html>
It works fine and list possible search.
Now from search results, a user can click on a page to browse it - simple. As soon as one click's on the link, I want to catch that and do some processing. See below section in above code:
$("#livesearch").on("click", "a.alert", function() {
alert("here");
});
To begin with, I am testing, if I am able to capture click on this link returned from ajax search or not - so alert("here"), but it is not working.
Please hep
Define the click method after appending the links:
success: function(responseText)
{
$("#livesearch").html(responseText);
$("#livesearch").css('display', 'block');
$("#livesearch").css('background', '#fff');
$("#livesearch").on("click", "a.alert", function()
{
alert("here");
});
}
Try this, and let us know what the console returns:
$.ajax({
type: "GET",
url: "livesearch.php?q=" + str,
success: function(responseText) {
console.log(responseText); //CHECK YOUR CONSOLE
$("#livesearch").append(responseText);
$("#livesearch").css('display', 'block');
$("#livesearch").css('background', '#fff');
$("#livesearch").find(".alert").click(function(e) {
e.preventDefault();
alert("here");
});
}
});
Another way to accomplish this is to build your anchor tag like this , then create the JS function:
myFunction(){
alert("here")
return false;
}

Posting a form with jQuery and want to change the submit button after click

Posting a form with jQuery and want to change the submit button after click.
Here's the code I'm using :P but did not work!
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#button").click(function(){
$("#button").submit(sendForm)
});
function sendForm() {
$.post('post.cfm',$("#button").serialize(),function(data,status){
$("#result").html(data)
});
return false
}
$("#button").html("Friend request sent");
});
});
</script>
</head>
<body>
<form id="button">
<input type="submit" value="Add as a friend">
</form>
You could try this:
var sendForm = function() {
$.post('post.cfm',$("#button").serialize(),function(data,status){
$("#result").html(data)
});
var request = $.ajax({
type:'POST',
dataType:'json',
url:'post.cfm',
data:{
data: $('#button').val()
},
success:function(data){
console.log(data);
// Do something
},
error:function(data){
console.log(data);
// Do something
}
});
request.done(function(data){
alert("Friend request sent");
});
return false;
}
$(document).ready(function(){
$("#button").click(function(){
$("#button").submit(sendForm)
});
Try something like this:
$(document).ready(function(){
// #button is your form's id, it's confusing
$('#button').on('submit', function(e){
e.preventDefault();
var form = $(this);
$.post('post.cfm', form.serialize(), function(data){
$("#result").html(data);
form.find(':submit').val("Friend request sent");
});
});
});
Also, add some inputs (text boxes as form data to post) in the form and give your submit button a name/id (better) and yes, you asked what the hell that message was, it was because you didn't provide enough information but only some code so, StackOverflow asked to provide more information so anyone could have understood the problem and as a result you would be benefited. Anyways, read the documentation properly, you need to learn the basic first and this is not a tutorial site.

Categories