Use AJAX Return value to PHP function - php

My ajax successfully return the value but my problem is I can't use the value to my function. How do I convert this div to a value?
<?php
echo $ajax_user_id = '<div id="result"></div>'; //value can display here
getName($ajax_user_id); //value wont work here
?>
<form method="post" id="registerSubmit">
<input type="text" name="user_id" id="user_id">
<button id="submit" type="submit">Submit</button>
</form>
<script>
$(document).ready(function(){
$("#registerSubmit").submit(function( e ) {
e.preventDefault();
$.ajax({
url: "test.php",
method: "post",
data: $(this).serialize(),
dataType: "text",
success: function(Result) {
$('#result').text(Result)
}
})
});
});
</script>

You can't use it that way.because jQuery is a scripting language which runs in browser when DOM is fully loaded and elements are available to make selectors.While php is server side language which runs on server way before page load.anyway to fulfill your need you can try something like this.
<form method="post" id="registerSubmit">
<input type="text" name="user_id" id="user_id">
<button id="submit" type="submit">Submit</button>
</form>
<script>
$(document).ready(function(){
$("#registerSubmit").submit(function( e ) {
e.preventDefault();
$.ajax({
url: "test.php",
method: "post",
data: $(this).serialize(),
dataType: "text",
success: function(Result) {
$('#result').text(Result);
getNameAjax(Result);
}
})
});
});
function getNameAjax(val)
{
$.ajax({
type: "POST",
url: GetNameAjax.php,
data:{'user_id':val},
success: function(res){
$('#name').html(res);
}
});
}
</script>
GetNameAjax.php file you can write like this
$ajax_user_id=$_POST['user_id'];
function getName($ajax_user_id)
{
return "name on the basis of id";
}

Related

How to pass the array value to PHP using AJAX?

I am trying to submit data to the database using AJAX. I have one array and I have to pass the value of the array to PHP using AJAX to display all the related records.
<form id="search-form" method="POST">
<input value="4869" name="compare_id[]" type="hidden">
<input value="4884" name="compare_id[]" type="hidden">
<input value="5010" name="compare_id[]" type="hidden">
<input type="button" id="search-button" name="search-button" value="search">
</form>
<div id="response"></div>
AJAX
<script>
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: 'POST',
url: 'response.php',
data: $('#search-form').serialize(),
dataType: 'json',
success: function(response) {
$('#response').html(response);
//alert(response);
}
});
});
});
</script>
PHP
$sql='SELECT Name, Email FROM request WHERE Id IN (' .( is_array( $_POST['compare_id'] ) ? implode( ',', $_POST['compare_id']) : $_POST['compare_id'] ).')';
$records = array();
$query=$conn->query($sql);
if ($query->num_rows > 0) {
while($row=$query->fetch_assoc()){
$records[]=$row;
}
}
echo json_encode($records);exit();
HTML
<form id="search-form" method="POST">
<input value="4869" name="compare_id[]" type="hidden">
<input value="4884" name="compare_id[]" type="hidden">
<input value="5010" name="compare_id[]" type="hidden">
<input type="button" id="search-button" name="search-button" value="search">
</form>
<div id="response"></div>
JS
<script>
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: 'POST',
url: 'response.php',
data: $('#search-form').serialize(),
dataType: 'json',
success: function(response) {
$('#response').html(response);
}
});
});
});
</script>
PHP
var_dump($_POST['compare_id']);
// it is already an array of ids. You can do whatever you want with it.
change your script as below. Your output is in array so you cant add it in div directly
<script>
$(document).ready(function(){
$('#search-button').click(function(){
$.ajax( {
type: 'POST',
url: 'action.php',
data: $('#search-form').serialize(),
dataType: 'json',
success: function(response) {
$('#response').html();
for(data in response) //loop over your data
{
$('#response').append(response[data].Email); //add email
}
//alert(response);
}
});
});
});
</script>
There are errors in your code. A good way to debug this is to print_r your POST value in your php script.
First $_POST["All"] does not exist. It is all. (php)
Second, you send a GET request not a POST one. (jQuery)
Third, format your date into json. A good way to do this is to create a variable right after compare_id.push, it's more readable, as so :
var json_data = {"my_array" : [1,2, "bonjour", 4]};
Your problem is mostly related to "how to debug". I think you should print what's happening along the way to figure out what's happening.

On button click perform ajax for sending values in forms are in while loop

How can I send input values through AJAX on button click? My code is below. Thanks in advance.
while
{
<form class="commentform">
<input type="hidden" class="proid" name="proid" value="<?=$rr['id']?>">
<input type="text" class="form-control" name="comval" placeholder="Write a comment.." autocomplete="off">
<button class="btn btn-post" type="button">Post</button>
</div>
</form>
}
$(document).ready(function() {
$(document).on('click', '.btn-post', function(){
var thePostID = $(this).val;
$.ajax({
url: 'fetch_comments.php',
data: { postID: thePostID },
type: 'POST',
success: function() {
alert(data);
}
});
Firstly, the correct method is $(this).val(), not just $(this).val.
Secondly, you can simplify your code by getting the data from the closest form element using serialize(). Try this:
$(document).on('click', '.btn-post', function() {
var $form = $(this).closest('form');
$.ajax({
url: 'fetch_comments.php',
data: $form.serialize(),
type: 'POST',
success: function() {
alert(data);
}
});
});
$("form").serialize();
Serialize a form to a query string, that could be sent to a server in an Ajax request.

Ajax POST and php query

Been looking at some tutorials, since I'm not quite sure how this works (which is the reason to why I'm here: my script is not working as it should). Anyway, what I'm trying to do is to insert data into my database using a PHP file called shoutboxform.php BUT since I plan to use it as some sort of a chat/shoutbox, I don't want it to reload the page when it submits the form.
jQuery:
$(document).ready(function() {
$(document).on('submit', 'form#shoutboxform', function () {
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: form.serialize(),
dataType:'html',
success: function(data) {alert('yes');},
error: function(data) {
alert('no');
}
});
return false;
});
});
PHP:
<?php
require_once("core/global.php");
if(isset($_POST["subsbox"])) {
$sboxmsg = $kunaiDB->real_escape_string($_POST["shtbox_msg"]);
if(!empty($sboxmsg)) {
$addmsg = $kunaiDB->query("INSERT INTO kunai_shoutbox (poster, message, date) VALUES('".$_SESSION['username']."', '".$sboxmsg."'. '".date('Y-m-d H:i:s')."')");
}
}
And HTML:
<form method="post" id="shoutboxform" action="">
<input type="text" class="as-input" style="width: 100%;margin-bottom:-10px;" id="shbox_field" name="shtbox_msg" placeholder="Insert a message here..." maxlength="155">
<input type="submit" name="subsbox" id="shbox_button" value="Post">
</form>
When I submit anything, it just reloads the page and nothing is added to the database.
Prevent the default submit behavior
$(document).on('submit', 'form#shoutboxform', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'shoutboxform.php',
data: $(this).serialize(),
dataType: 'html',
success: function(data) {
alert('yes');
},
error: function(data) {
alert('no');
}
});
return false;
});
Use the following structure:
$('form#shoutboxform').on('submit', function(e) {
e.preventDefault();
// your ajax
}
Or https://api.jquery.com/submit/ :
$("form#shoutboxform").submit(function(e) {
e.preventDefault();
// your ajax
});

Send input value to php using ajax with result printed to div

I'm trying to send an input value to a php script and have the returned value posted to a div, using ajax, but I can't seem to get this right. Any help/suggestions would be appreciated. Thanks!!
This is what I have by now, but console says: "Failed to load resource: the server responded with a status of 404 (Not Found)".
test1.php:
<script>
$.ajax({
type: 'POST',
url: 'test2.php',
data: {url: $('#id1').val()},
success: function (data)
{
$(document).ready(function(){$("#content").load("test2.php");});
}
});
</script>
<form name="input">
<input type="text" id="id1">
<input type="submit">
</form>
<div id="content"></div>
test2.php:
<?php
$string=$_POST['id1'];
require_once('connect.php');
$inf = "SELECT * FROM `comments` WHERE date='$string'";
$info = mysql_query($inf);
while($info2 = mysql_fetch_object($info)) {echo $info2->username.$info2->date;}
?>
<script>
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'test2.php',
data: {id1: $('#id1').val()},
success: function(data)
{
$("#content").html(data);
}
});
});
});
</script>
<form name="input">
<input type="text" id="id1">
<input type="submit" id="submit">
</form>
<div id="content"></div>
When you submit the ajax request, you're already submitting your content to test2.php, so you don't need to load it again. In the success function, you can append the result to the div from the callback.
$(document).on('click','#submit',function(e) {
e.preventDefault();
$.post('test2.php',{url: $('#id1').val()},function(data){
$("#content").html(data);
}
});
});
404 (Not Found) Error is for page not found. Please make sure that file test2.php is exist in same folder. Check url.
Also you can copy the URL from console and paste it in the browser URL to check the url correct or incorrect.
jQuery
<script>
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'test2.php',
data: {id1: $('#id1').val()},
success: function(data)
{
$("#content").html(data);
}
});
});
});
</script>
HTML
<form name="input">
<input type="text" id="id1">
<input type="submit" id="submit">
</form>
You could try this:
<script>
$('#submitBtn').on('click',function(){
$.ajax({
type: 'POST',
url: 'test2.php',
data: {url: $('#id1').val()},
success: function (data)
{
$("#content").html(data);
}
});
return false;
});
</script>
<form name="input">
<input type="text" id="id1">
<input id="submitBtn" type="submit">
</form>
<div id="content"></div>

$.ajax( type: "POST" POST method to php

I'm trying to use the POST method in jQuery to make a data request. So this is the code in the html page:
<form>
Title : <input type="text" size="40" name="title"/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
var title=f.title.value;
$.ajax({
type: "POST",
url: "edit.php",
data: {title:title} ,
success: function(data) {
$('.center').html(data);
}
});
}
</script>
And this is the php code on the server :
<?php
$title = $_POST['title'];
if($title != "")
{
echo $title;
}
?>
The POST request is not made at all and I have no idea why. The files are in the same folder in the wamp www folder so at least the url isn't wrong.
You need to use data: {title: title} to POST it correctly.
In the PHP code you need to echo the value instead of returning it.
Check whether title has any value or not. If not, then retrive the value using Id.
<form>
Title : <input type="text" id="title" size="40" name="title" value = ''/>
<input type="button" onclick="headingSearch(this.form)" value="Submit"/><br /><br />
</form>
<script type="text/javascript">
function headingSearch(f)
{
var title=jQuery('#title').val();
$.ajax({
type: "POST",
url: "edit.php",
data: {title:title} ,
success: function(data) {
$('.center').html(data);
}
});
}
</script>
Try this code.
In php code, use echo instead of return. Only then, javascript data will have its value.
try this
$(document).on("submit", "#form-data", function(e){
e.preventDefault()
$.ajax({
url: "edit.php",
method: "POST",
data: new FormData(this),
contentType: false,
processData: false,
success: function(data){
$('.center').html(data);
}
})
})
in the form the button needs to be type="submit"
Id advice you to use a bit simplier method -
$.post('edit.php', {title: $('input[name="title"]').val() }, function(resp){
alert(resp);
});
try this one, I just feels its syntax is simplier than the $.ajax's one...
function signIn()
{
var Username = document.getElementById("Username").value;
var Password = document.getElementById("Password").value;
$.ajax({
type: 'POST',
url: "auth_loginCode.jsp",
data: {Username: Username, Password: Password},
success: function (data) {
alert(data.trim());
window.location.reload();
}
});
}
contentType: 'application/x-www-form-urlencoded'

Categories