image button - no page change - javascript

I'm trying to call a php file without refreshing the page. The code executes the php file, but the value toid is not being passed along. If i manually query the page then it works fine. The other issue im having is the button needs to be an image with the path src="{ROOT_PATH}mchat/quote.gif"
<form id="myform" method="POST" class="form_statusinput">
<input type="hidden" name="toid" id="toid" value="<?php echo {mchatrow.MCHAT_USERNAME}; ?>">
<div id="button_block">
<input type="submit" id="button" value="Enter">
</div>
</form>
<script>
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var toid = $("#toid").val();
$.ajax({
type: "POST",
url: "randomquote.php",
data: "toid=" + toid,
});
});
});
</script>
Any ideas?

When you say "if i manually query the page then it works fine", does that mean hitting the endpoint directly like
http://yoursite.com/randomquote.php?toid=239439
Have you tried sending the data as an object (like this):
$.ajax({
type: "POST",
url: "randomquote.php",
data: { toid: toid }
});
That may do the trick.

Related

Dynamically adding picture using php

I am having trouble getting a picture stored on a server and its path in my database, then i want to retrieve and showe it on the same page. So far I have the add photo button which onchange triggers the photo to a series of checks then stores it. However, because of this set up the page changes, but there's other info on the page that needs to be inputted. I am assuming I have to create some ajax function, which I have below, but it doesn't work. Here's what I have so far.
<div class="step1-container">
<h3 class="steps-detail">Step 1:</h3>
<p>Upload a picture for you new friends</p>
<form action="../Controllers/fileupload_controller.php" method="post" enctype="multipart/form-data">
Select image to upload:
<label class="upload-cov">
<input type="file" name="fileToUpload" id="fileToUpload">
<span>Add Photo</span>
</label>
<input type="submit" id="photoSubmit" style="display:none">
</form>
</div>
<div class="profile-pix">
</div>
php:
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
$_POST['UserId'] = $_SESSION['logname'];
$_POST['ProfilePix'] = $target_file;
if (storeData($_POST, $table, $cxn)) {
$result = $target_file;
//echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
}
js:
$("#fileToUpload").change(function() {
$('#photoSubmit').click();
});
ajax:
$('#fileToUpload').on('change', 'input', function(e) {
e.preventDefault();
var str = $('#fileToUpload').serialize();
$.ajax({
type: 'POST',
url: '../Controllers/fileupload_controller.php',
async: true,
traditional: true,
data: str,
success: function (msg) {
console.log(msg);
}
});
Since you want to send a file as multi-part/form-data to the server using ajax, the easiest way will be to send the form data of the form.
Example code:
//from within the on change event listener
$.ajax({
//pass the form element to the form data object
data: new FormData($(this).parents('form'))
})

PHP Ajax Submit Form Return Data

I have the following form in my HTML page:
<form id="submission" action="testresponse.php" method="post">
<input id="URL" name="URL" type="text">
<button name="Submit" type="submit">Submit</button>
</form>
testresponse.php just contains <?php print_r($_POST); ?> to print all the post variables.
I am trying to submit the form and have it return the values on the same page that the page was submitted (i.e. return the POST variables somewhere above the form)
I used the following jQuery code:
$( document ).ready(function() {
var frm = $('#submission');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log(data.responseText);
}
});
ev.preventDefault();
});
});
But for some reason data.responseText always returns blank
Is there a way to have my form send a POST request to a PHP page and return the result?
Change from
console.log(data.responseText)
to
console.log(data)

Enter ID in html form and load related data from MySQL database in same page

I have a form with an input field for a userID. Based on the entered UID I want to load data on the same page related to that userID when the user clicks btnLoad. The data is stored in a MySQL database. I tried several approaches, but I can't manage to make it work. The problem is not fetching the data from the database, but getting the value from the input field into my php script to use in my statement/query.
What I did so far:
I have a form with input field txtTest and a button btnLoad to trigger an ajax call that launches the php script and pass the value of txtTest.
I have a div on the same page in which the result of the php script will be echoed.
When I click the button, nothing happens...
Test.html
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
<script>
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
</script>
</head>
<body>
<form name="testForm" id="testForm" action="" method="post" enctype="application/x-www-form-urlencoded">
<input type="text" name="txtTest" id="txtTest"/>
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
<input type="submit" name="SubmitButton" id="SubmitButton" value="TEST"/>
</form>
<div id="testDiv" name="testDiv">
</div>
</body>
The submit button is to insert updated data into the DB. I know I have to add the "action". But I leave it out at this point to focus on my current problem.
testpassvariable.php
<?php
$player = $_POST['userID'];
echo $player;
?>
For the purpose of this script (testing if I can pass a value to php and return it in the current page), I left all script related to fetching data from the DB out.
As the documentation says 'A page can't be manipulated safely until the document is ready.' Try this:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
You need to correct two things:
1) Need to add $(document).ready().
When you include jQuery in your page, it automatically traverses through all HTML elements (forms, form elements, images, etc...) and binds them.
So that we can fire any event of them further.
If you do not include $(document).ready(), this traversing will not be done, thus no events will be fired.
Corrected Code:
<script>
$(document).ready(function(){
//AJAX CALL
function fireAjax(){
$.ajax({
url:"testpassvariable.php",
type:"POST",
data:{userID:$("#txtTest").val(),},
success: function (response){
$('#testDiv').html(response);
}
});
}
});
</script>
$(document).ready() can also be written as:
$(function(){
// Your code
});
2) The button's HTML is improper:
Change:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"
To:
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
$.ajax({
url: "testpassvariable.php",
type: "POST",
data: {
userID: $("#txtTest").val(),
},
dataType: text, //<-add
success: function (response) {
$('#testDiv').html(response);
}
});
add dataType:text, you should be ok.
You need to specify the response from the php page since you are returning a string you should expect a string. Adding dataType: text tells ajax that you are expecting text response from php
This is very basic but should see you through.
Change
<input type="button" id="btnLoad" name="btnLoad" onclick="fireAjax();"/>
Change AJAX to pass JSON Array.
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "action.php",
data: data,
....
// action.php
header('Content-type: application/json; charset=utf-8');
echo json_encode(array(
'a' => $b[5]
));
//Connect to DB
$db = mysql_connect("localhst","user","pass") or die("Database Error");
mysql_select_db("db_name",$db);
//Get ID from request
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
//Check id is valid
if($id > 0)
{
//Query the DB
$resource = mysql_query("SELECT * FROM table WHERE id = " . $id);
if($resource === false)
{
die("Database Error");
}
if(mysql_num_rows($resource) == 0)
{
die("No User Exists");
}
$user = mysql_fetch_assoc($resource);
echo "Hello User, your number is" . $user['number'];
}
try this:- for more info go here
$(document).ready(function(){
$("#btnLoad").click(function(){
$.post({"testpassvariable.php",{{'userID':$("#txtTest").val()},function(response){
$('#testDiv').html(response);
}
});
});
});
and i think that the error is here:-(you wrote it like this)
data:{userID:$("#txtTest").val(),}
but it should be like this:-
data:{userID:$("#txtTest").val()}
happy coding :-)

Having problems figuring out AJAX POST functions

I am trying to post using AJAX because I don't want to use a submit button and reload the page everytime I click it.
I am using this code for ajax:
<script language="JavaScript"><!--
function postit()
{
var frm = $('#pmconfirm');
$.ajax({
type: "POST",
url: "bitcin",
data: frm.serialize(),
success: function(msg){
$("#main").hide();
$("#main").html(msg).show();
},
error: function(msg){
$("#main").html("<font color='#ff0000'>Ajax loading error, please try again.</font>").show();
}
});
}
setTimeout("postit()",2000);
//--></script>
Next, I am using this form:
<form action="" name="fcaptcha" method="post">
<input type="hidden" id="bitcoin" name="bitcoin">
<input type="hidden" id="pmconfirm" name="pmconfirm" src="http://www.mvixusa.com/newsletter/2010/11/newsletter-membership-confirmation/images/confirm-button.png" alt="Submit Form" onclick=\"document.getElementById("fcaptcha").submit()\"/>
</form>
<div id="main">
</div>
This works it posts but I doesn't give me results ?
if (isset($_POST['bitcoin']))
{
// My code here works, because it works when i dont use ajax
// And I have some things to check like if it wasnt what i wanted
// it returns some message which is shown with php.
}
<div id="messaget">
<?php
if($failed == 1) echo $messages;
?>
</div>
This is the part where the messages should be displayed, I tried using a tag #messaget to display the HTML after post but it didn't work, I tried displaying the entire page in this page it still didn't work.
And the url: "bitcin", is entirely ok, i used htaccess.
Can somebody spot where the problem is ?
Add an id to the form :
<form id="pmform" action="" name="fcaptcha" method="post">
And change Js to:
var frm = $('#pmform');
When performing:
............
data: frm.serialize(), //this will take the form and make an array based on the names of the form elements thus having them accessible in the PHP script
..........

How can i use this javascript code without interfering with other forms

I created two forms on my website, but when i submit it redirects automatically, i want to prevent this.
I have a javascript code here that does exactly what i need, but it works in all forms on my website, i just need this code working in a specific form, because i have two forms, one called login, and other one called cart, and when i click on login button, it doesnt redirect, because of the script, it works for both forms, and i just want this script working in a specific form, in this case, cart.
I hope you understand, i dont speak english very well.
My Javascript code:
<script type="text/javascript">
$(document).ready( function () {
$('form').submit( function () {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
url: "carrinho.php",
data: formdata,
});
return false;
});
}); </script>
My html code:
<form name="comprar" method="post" action="carrinho.php">
<input name="id_txt" type="hidden" value="<?php echo $id; ?>" />
<input name="nome" type="hidden" value="<?php echo $nome; ?>" />
<input name="preco" type="hidden" value="<?php echo $preco; ?>" />
<input name="quantidade" type="hidden" value="1" />
<input name="Comprar" type="submit" class="Adicionar" value="" />
</form>
Carrinho means cart, im building a ecommerce store.
Try:
$(document).ready( function () {
$("form[name='comprar']").submit( function () {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
url: "carrinho.php",
data: formdata
});
return false;
});
});
Use $("form[name='comprar']") to access particular form. Change form name according to your requirement.
Use an attribute selector to select only the desired form. Also note that extra , is going to cause problems in IE < 9.
$("form[name='comprar']").submit( function () {
var formdata = $(this).serialize();
$.ajax({
type: "POST",
url: "carrinho.php",
data: formdata, //remove this comma
});
return false;
});

Categories