Send variable From PHP to AJAX [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I have a php page called posts.php, this page just select all from a database table named posts and display them. Down the page I have a textarea named post. When I press the submit button the AJAX script will send the text from textarea to a page called insert.php. This insert.php gets the submited text and insert it into posts table. How can I do this and how can I upload the posts.php when I have inserted a post into posts table.
Example:
User 123 writes a message in the textarea. He presses submit button. AJAX sends the post to insert.php. Insert.php inserts the post into posts tabel. Posts.php shows the message.

You can do it very easily! Here's a very simple example.
func.js
$(document).on("click", ".submitBtn", function() {
var textareaVal = $(".textarea").val();
$.ajax({
type: "POST",
url: "insert.php",
dataType: "text",
data: { postVar: textareaVal },
success: function(data) {
$(".resultDiv").load("posts.php");
}
});
});
insert.php
// You have to pay attention to AJAX can only invite your file!
if (!empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest") {
if (isset($_POST["postVar"])) {
$var = sanitize($_POST["postVar"]); // You need sanitize the data!
// Insert into your table...
}
}
In your posts.php, SELECT datas from your table, but only select the data, without „HTML container”! Your JS file load this datas on your resultDiv box.

I'm not certain why you would need to do this via ajax, but:
$( "#myForm" ).submit(function( event ) {
$.ajax({
type: 'post',
url: '../insert.php' ,
data: { value1: document.getElementById('textarea').value },
success: function () {
alert("yay!");
}
});
});

Related

Why ajax loaded link not clickable on jQuery click event? [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I called Ajax on button click, and I got response with link. Now I want to do some action on that link but I cant, why?
here is the ajax call:
$( document ).ready(function() {
jQuery(".rateReset").click(function(){
var data_item = jQuery(this).attr("data-item");
var data_target = jQuery(this).attr("data-target");
var me = this;
jQuery.ajax({
type: "POST",
url: "likevoting.php?data_item="+data_item+"&data_target="+data_target+"&interchange=yes",
success: function(data){
jQuery(me).closest("div.rateWrapper").html(data);
}
});
});
I got response like:
some text link lorem ipsume...
Now I want to add click event on 'link' text, how to do this.
Thanks
replace
jQuery(".rateReset").click(function(){
to
jQuery(document).on("click", ".rateReset", function(){

Show MySQL Results in a table without reloading page [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm trying to write a web application for database managing purposes. I've written front-end of the app on HTML+CSS3 and the server-side language is PHP, but I'm still confused about how to make MySQL calls and show it to the user without refreshing/reloading the page.
Trying to be specific, here are my doubts:
Can I execute a MySQL query without reloading a page?
How do I show a table with query's results?
Use Ajax for this :
Add this code to main page where you want to display table data
<html>
<head>
<script>
function dashboard() {
var query_parameter = document.getElementById("name").value;
var dataString = 'parameter=' + query_parameter;
// AJAX code to execute query and get back to same page with table content without reloading the page.
$.ajax({
type: "POST",
url: "execute_query.php",
data: dataString,
cache: false,
success: function(html) {
// alert(dataString);
document.getElementById("table_content").innerHTML=html;
}
});
return false;
}
</script>
</head>
<body>
<div id="table_content"></div>
</body>
</html>
In table_content div the data come from execute_query.php page will load without refreshing the page.
execute_query.php
$user_name = $_POST['parameter'];
$query="SELECT * from info where name=$user_name";
$result=mysql_query($query);
$rs = mysql_fetch_array($result);
do
{
?>
<table>
<tr>
<td><?php echo $rs['city']; ?></td>
<td><?php echo $rs['phone_number']; ?></td>
</tr>
</table>
<?php
}while($rs = mysql_fetch_array($result));

jquery select adding extra rows [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have a small ajax call:
$.ajax({
type:'POST',
dataType: 'json',
url: 'inc/getfunctions.php?q='+l_id+'&func=load_po',
success:function(data){
//alert ('hi');
if (data.po_num) {
$('#po_num_s').append($('<option>').text('Select a PO').attr('value', 0));
var po_num = data.po_num;
var $subType = $("#po_num_s");
$.each(data, function () {
$subType.append($('<option></option>').attr("value", data.l_id).text(data.po_num));
});
}
}
});
it is apending 2 rows :
<'option value="11">112212<'/option>
<'option value="11">112212<'/option>
is the output
Thanks in advance
The $.each function will take an array or an object and iterate over its items, while providing the item key and value as parameters to the callback. Like so:
$.each(["aaaa", "bb", "ccc"], function(key, value){
console.log(value.length);
});
// Will output:
// 4
// 2
// 3
But you aren't using the each-loop for something useful, as you don't receive any item in the callback function. The only reason you're getting as few as 2 lines is that your data object only has 2 keys in it. Try adding another property to data at the same place as your commented alert, like so:
......
success:function(data){
//alert ('hi');
data.foo = "bar"
if (data.po_num) {
......
and watch the each-loop go three rounds.

How to submit a form to the same page and refresh content without reloading entire page

Basically what I'm trying to do is post comments to a page without having to refresh the entire page. Just the Comments DIV so it looks like it posted and refreshed smoothly.
The form submits to the same page it's on. Everything I've found shows me how to refresh content constantly using intervals. I just want the comments DIV to refresh when someone posts a comment.
I can't find the correct ajax code to do this the way I want.
Here is my code:
var submit_button = $('#submit_button');
submit_button.click(function() {
var commentSubmitted= $('commentSubmitted').val();
var update_div = $('#update_div');
$.ajax({
type: 'POST',
url: '/blog/',
data: data,
success:function(html){
update_div.html(html);
}
});
});
in the same PHP file, I have the post to DB:
if($_POST[commentSubmitted])
{
$query="INSERT INTO comments (commentSubmitted) VALUES ('$commentSubmitted')";
mysql_query($query);
}
The HTML is for the form:
<form id="flow" method='post' action='/blog/'>
<textarea name='commentSubmitted' ></textarea>
<input type='submit' value='Post'/>
The DIV containing all comments looks like so:
<DIV id='AllComments'>
// comments displayed here
</DIV>
So after submitting the form, I would like the 'AllComments' DIV to reload.
The best would be to use jQuery to make the ajax call to the server and retrieve the data you want.
You have two ways of retrieving the data. Either retrieve the additional comments to show in a json array and handle it with javascript, or create the html on the server side and append/replace the html in the comments section.
Using Json
$.ajax({
url: "the_ajax_url_here",
type: "post",
data: {paramTitle: "paramValue", paramTitle1: "paramValue1"},
dataType: "json"
success: function(response) {
// handle the response
}
});
Retrieving Html
$.ajax({
url: "the_ajax_url_here",
type: "post",
data: {paramTitle: "paramValue", paramTitle1: "paramValue1"},
dataType: "html"
success: function(response) {
// set the html of comments section to the newly retrieved html
$("comments_section_selector").html(response);
}
});
What I would do is retrieve the newly added comment in a json array and then using javascript append it to the comments section.
edit:
After seeing your code I have some comments that might help you.
I would personally prefer the code that handles the ajax request in a separate file.
In that file you can store the new comment and create the html to display that comment.
Then in the success function just append the new html to the comment section like so:
success: function(response) {
$('#AllComments').append(response);
}
You can also make new comment appear on top using prepend
$('#AllComments').prepend(response);
Simple as that hope you are upto it
submit_button.click(function() {
var commentSubmitted= $('commentSubmitted').val();
var update_div = $('#update_div');
$.ajax({
type: 'POST',
url: '/blog/',
data: data,
success:function(html){
update_div.html(html);
}
});
});
Then you go to insert data
if($_POST[commentSubmitted])
{
$query="INSERT INTO comments (commentSubmitted) VALUES ('$commentSubmitted')";
mysql_query($query);
//After Inserting data retrieve back all the comments from db
$sql = "select * from comments";//any query and execute it
$query = mysql_query($sql);
while($data = mysql_fetch_array($query)){
echo $data["comments"];//Echo your commenets here
}
exit;
}
Thats it

Sending form using jQuery [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to send a form using jQuery and it's not working. This code with a <a> tag works fine, but inside a form using the submit button doesn't.
$('#send-comment').click(function(){
var id_parent = $('#id_parent').val();
var comment_text = $('#comment-box').val();
var user_id = <?php echo $_SESSION['log_id']; ?>;
var new_id = <?php echo $id_new; ?>;
$.post( "dn-functions.php", { func: "registerComment", id_parent: id_parent, comment_text: comment_text, user_id: user_id, new_id: new_id })
.done(function( data ) {
alert( data );
});
});
Do you know what am I doing wrong?
$('#send-comment').click(function(e){
e.preventDefault();
var id_parent = $('#id_parent').val();
var comment_text = $('#comment-box').val();
var user_id = <?php echo $_SESSION['log_id']; ?>;
var new_id = <?php echo $id_new; ?>;
$.post( "dn-functions.php", { func: "registerComment", id_parent: id_parent, comment_text: comment_text, user_id: user_id, new_id: new_id })
.done(function( data ) {
alert( data );
});
});
I'm pretty sure you are submitting the form and your request is not being sent since you're leaving the page on form submit.
So pass the event and prevent the default action of form submit.

Categories