AJAX pass data to PHP - javascript

I've been searching this forum, but I had no good result. I have this HTML:
<form method="post" id="postform">
<input type="text" name="message" id="message" placeholder='Say "Hello!"' class="mymessage" maxlength="255"/>
<br />
<input id="submit" type="button" value="Send"/>
</form>
PHP:
<?php
include ('connect.php');
session_start();
if (isset($_POST['message'])){
mysql_query("INSERT INTO messages VALUES ('','".$_POST['message']."','".$_SESSION['user']."')");
}
?>
And jQuery:
$('#submit').click(
function(){
var message = $('#message').val();
$.ajax({
url: post.php,
type:'POST',
data: {"message":message}
});
});
I need to pass #message content to PHP without refreshig the page. This is what I've made, but it's not working.

Check your syntax:
Wrap url with quotes '
Remove single quotes around 'message' variable
$.ajax({
url: 'post.php',
type: 'POST',
data: {message : message}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
See the first example of $.ajax() at the bottom of its documentation page.

I need to pass #message content to PHP without refreshig the page.
Handle form submit instead:
$("#postform").submit(function(){
var message = $('#message').val();
$.ajax({
url: 'post.php',
type:'POST',
data: {message:message}
}).done(function( data) {
// handle response from the server in case of success.
});
return false; //to prevent submitting and refreshing the page.
});

Related

Getting data sent with Ajax from php?

sorry if this has been asked many times but I can't get it to work.
I'm trying to build a restful website, I have a simple form:
<form action="/my/path" method="post" id="myformid">
Name <input type="text" name="name">
<input type="submit" value="Test">
</form>
I convert the data the user inputs using Javascript and I send them to my php file using Ajax:
function postData() {
$('#myformid').on('submit', function(event) {
event.preventDefault();
const json = JSON.stringify($("#myformid").serializeArray());
$.ajax({
type: "POST",
url: "/my/path",
data: json,
success: function(){},
dataType: "json",
contentType : "application/json"
});
});
}
And I tried reading the data on php like:
$data = json_decode(file_get_contents('php://input'), true);
$name = $data["name"];
The code works perfectly if I send a JSON in the request body using a tool like Postman, but from what I tested using Ajax the json data arrives as POST data, and I can read it using $_POST["name"], but non with the 'php://input' as I did.
How can I fix it so the JSON gets accepted even sent via Javascript?
Hi you can try like this:
First I use an id attribute for each input i dont really like to serialize stuff but thats me you can do it your way here are the files.
your index.php:
<form method="post" id="myformid">
Name :<input type="text" id="name" name="name">
<input type="submit" value="Test">
</form>
<br>
<div id="myDiv">
</div>
your javascript:
//ajax function return a deferred object
function _ajax(action,data){
return $.ajax({
url: 'request.php',
type: 'POST',
dataType: 'JSON',
data: {action: action, data: data}
})
}
//your form submit event
$("#myformid").on('submit', function(event) {
//prevent post
event.preventDefault();
//validate that name is not empty
if ($("name").val() != "") {
//parameters INS is insert data is the array of data yous end to the server
var action = 'INS';
var data = {
name: $("#name").val()
};
console.log(data);
//run the function and done handle the function
_ajax(action,data)
.done(function(response){
console.log(response);
//anppend name to the div
$("#myDiv").append("<p>"+response.name+"</p>");
});
}
});
your request.php file:
<?php
//includes and session start here
//validate that request parameters are set
if (isset($_POST["action"]) && isset($_POST["data"])) {
//getters
$action = $_POST["action"];
$data = $_POST["data"];
//switch to handle the action to perfom maybe you want to update with the form too ?
switch ($action) {
case 'INS':
// database insert here..
//return a json object
echo json_encode(array("name"=>$data["name"]));
break;
}
}
?>
Results:
Hope it helps =)
From the documentation of .serializeArray().
The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string.
And in the example given in the same page, it is clear that you will get an array in php,
to access an element, you should try-
`$data[0]['name']`
Also, have you tried print_r($data), is it NULL??
Change your ajax codes
$('#btnSubmit').on('click', function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/new.php",
data: $("#myformid").serialize(),
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
Also you need some changes in form
<form action="new.php" method="post" id="myformid">
Name <input type="text" name="name">
<input id="btnSubmit" type="button" value="Test">
And you can get POST data in php file like $_POST['name']
You can set directly form serialize in ajax request to send params
function postData() {
$('#myformid').on('submit', function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/my/path",
data: $("#myformid").serialize(),
success: function(){},
dataType: "json",
contentType : "application/json"
});
});
}
And you can get POST in your PHP using $_POST
print_r($_POST);

Get and display results of PHP using jQuery/AJAX

I have a Leaflet map, and a text input. I want to take the address from the textbox, run it through a PHP script, and get the result all through jQuery.
Here is my form:
<form id="mapcheck" method="POST" action="geo.php">
<input id="largetxt" type="text" name="checkAddress">
<input id="button" type="submit" name="submit" value="Check">
</form>
Here is part of the PHP:
<?php
if (isset($_POST["checkAddress"])) { //Checks if action value exists
$checkAddress = $_POST["checkAddress"];
$plus = str_replace(" ", "+", $checkAddress);
$json = file_get_contents('https://maps.googleapis.com/maps/api/geocode/json?address=' . $plus . '&key=GMAPSKEY');
$obj = json_decode($json);
$mapLat = $obj->results[0]->geometry->location->lat;
$mapLng = $obj->results[0]->geometry->location->lng;
$coords = ('' . $mapLat . ', ' . $mapLng . '');
return $coords;
}
?>
And the jQuery:
$(document).ready(function() {
$("#button").click(function(){
$.ajax({
url: "geo.php",
method: "POST",
data: {
checkAddress: $("#largetxt").val()
},
success: function(response){
console.log(response);
}
});
});
});
I need to listen on submit of the form via jQuery (NOT PHP), run it through a geocode script, then take that result and put it through regular JavaScript (Leaflet map.) I have played around with the AJAX feature of jQuery to no avail. There is a very simple solution to this, but I have not figured it out.
UPDATE: Problem resolved, thanks Vic.
You would need AJAX. Remove the form element but keep the inputs.
$("#button").click(function(){
$.ajax({
url: "geo.php",
method: "POST",
data: {
checkAddress: $("#largeText").val()
},
success: function(response){
console.log(response);
//your script
}
})
});

Ajax request fail - retrieve user id from server

I have form that has one text input field and a button. On submit form, I take the value from the text field user and make an ajax call to ajax.php to then have the server return the userID. The server is indeed returning a value as shown in the console. But I am not sure why the ajax call is failing on each request after submitting the form. What can I correct or change to have a success?
index.php
$('form').submit(function(e) {
var searchUser = $('input[name="user"]').val();
var getUser = $.ajax({
type: "GET",
url: "ajax.php",
data: {user: searchUser},
dataType:'text'
});
getUser.done(function( data ) {
alert(data);
});
getUser.fail(function( jqXHR, textStatus, data ) {
alert( "Request failed: " + textStatus );
});
});
<form id="search" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="GET">
<label for="user"> Username:</label><input type="text" name="user" id="user" value="<?php echo $user ?>"><br>
<button type="submit" id="search">Search</button>
</form>
ajax.php
if(!empty($_GET['user'])){
$user = $_GET['user'];
echo getInstaID($user); // this prints a numeric value like 2057821
}
Perhaps the data is being returned as json or jsonp? You have specified dataType: 'text'. If the return datatype is different it will error out. If you are using a fairly recent version (I think 2.0 or better) leaving out dataType or specifying dataType:"auto" will allow the call to succeed. Then you can debug to figure out how to handle the response.
You might try adding a success function like the following:
$('form').submit(function(e) {
var searchUser = $('input[name="user"]').val();
$.ajax({
type: "GET",
url: "ajax.php",
data: {user: searchUser},
success:function(data){//begin success function
//do something with the data returned from ajax.php file
alert(data);
}//end success function
});

image button - no page change

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.

Ajax Jquery Comments Page

I've looked at many posts here on SO and I thought that what I have would work in terms of sending form data using AJAX without refreshing the page. Unfortunately it's not working and I'm at a loss to see what it going wrong so here is my code:
profile.php
<script>
$(function () {
$('form#commentform').on('commentsubmit', function(e) {
$.ajax({
type: 'post',
url: 'insertcomment.php',
data: $(this).serialize(),
success: function () {
alert('MUST ALERT TO DETERMINE SUCCESS PAGE');
$("#comment").val('');
}
});
e.preventDefault();
});
});
</script>
<form id='commentform' method='post'>
<textarea class='comment' id='comment'></textarea>
<input type='hidden' name='activityid' value='$activityid'>
//$activityid is the ID of the status so the database knows what status ID to connect the comment with
<input type='submit' name='commentsubmit' value='Comment'>
</form>
insertcomment.php
<?php
include 'header.php';
$activityid=htmlspecialchars($_POST['activityid'], ENT_QUOTES);
$comment=htmlspecialchars($_POST['comment'], ENT_QUOTES);
$commentsql=$conn->prepare('INSERT INTO wp_comments (user_id, activity_id, comment, datetime) VALUES (:userid, :friendid, :comment, CURRENT_TIMESTAMP)');
$commentsql->bindParam(':userid', $_SESSION['uid']);
$commentsql->bindParam(':activityid', $activityid);
$commentsql->bindParam(':comment', $comment);
$commentsql->execute();
include 'bottom.php';
?>
The end result hopefully is that the comment gets inserted into the database without refreshing the page and then the text area is reset.
As of right now when I click the comment submit button it refreshes the page.
try this:
$(document).ready(function(){
$('form#commentform').submit(function( e ) {
var postData = $(this).serializeArray();
$.ajax({
type: 'post',
url: 'insertcomment.php',
data: postData,
success: function () {
alert('MUST ALERT TO DETERMINE SUCCESS PAGE');
$("#comment").val('');
}
});
e.preventDefault();
});
});

Categories