I am posting data to a PHP page using the $.ajax in Jquery. So far all this is working fine.
Here is how all this looks in my index.html.
function send() {
$( "#send" ).show( "slow" );
var page = Page;
var title = $("#title").text();
var title_2 = $("#title_2").val();
$.ajax({
url: "save.php",
method: "POST",
data: { MyPage : page, My_Title1 : title, My_Title2 : title_2 },
dataType: 'json',
success: function(data) {
alert(data);
var result = jQuery.parseJSON(data);
alert(result.last_id);
},
error: function(output) {
alert("not working whole process");
}
});
This to sum up what I am doing, is sending some data, Html and contents in div's, to a sql database.
What I would like to do now is that once this data is posted to the save.php file, I get a response from the php sending me the ID of the page I have saved all this in. So I am using mysqli_insert_id($con); to acheive this.
Set it it looks like this.
$last_id = mysqli_insert_id($con);
When I execute all this, the Post works fine and I end up with what I want.
{"last id":265} at the end of my post.
$data['last id'] = $last_id;
echo json_encode($data);
How do I get this value back to my index.html so that I can place it inside a input. The success is not working out.
//Reply to Steves answer
# Steve. Thank you for answering. Your answer is exactly what is happening. I am sending a whole bunch of html to my save.php file so it can save it to a sql table.
Something looking like this.
Write to MySQL OK!<br>INSERT INTO Project(ID_User,Name_Project,Page_Project,Date_Project) VALUES ( 110, '\"Project name here\"', '<div class=\"file_save_container\"> <------------- HERE THERE IS A WHOLE BUNCH OF HTML ------------> </div>\n\n\n', '2015-03-19 13:10:23');<br>
This is all saving properly to my sql table. What I would like to achieve here is that when the ajax is sent to my save.php I get a response sending me the id of the newly created Project so that I can then place the response "the id" inside a . Right now mysqli_insert_id is placing this at the end of my post.
<br>{"this_id":"311"}
This is what I would like to get back as a response to my index.html file and not have it at the end of my post.
Try to set header('Content-Type: application/json'); in save.php
Write $data['last_id'] instead of $data['last id'] to match your JS.
Related
Trying to send a post request from ajax to php.
I did many trial and errors based from the answers including making sure that the "type" is set to post, specifying "dataType", correct "url". I think I miss something important but I can't figure out what it is.
main.php
<script>
$(document).ready(function(){
$(".editContact").on("click", function(){
let dataID = $(this).attr("data-id");
console.log(dataID);
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
dataType: "text",
data:{data:dataID}
});
});
});
</script>
functions/phonebook.php
if(isset($_POST["data"])){
$res = array($data=>var_dump($_POST["data"]));
}
else{
$res ='null';
}
Then print the $res variable containing the dataID from ajax to my html element in main.php
<label class="m-label-floating">Contact name <?php echo $res; ?> </label>
The console.log in my main.php prints the data what I want to send in ajax but when I try to send the dataID to my phonebook.php, I get a null value.
Your problem is here:
$res = array($data=>var_dump($_POST["data"]));
You are using var_dump the wrong way.
From the docs:
This function displays structured information about one or more expressions that includes its type and value. Arrays and objects are explored recursively with values indented to show structure.
This function does not return any value, so, in your case, $data=>var_dump($_POST["data"]) will always be null.
What you need to is:
$res = array($data => $_POST["data"]);
If you are sending data to a different page altogether and need to use jquery / JS to do it, it might be simpler to send via window replace:
window.location.replace(...)
If you need to stay on the same page, you might want to include a success function in your ajax query, as this will return to the page you are calling from:
$.ajax({
type: 'POST',
url: 'functions/phonebook.php',
data:{data:dataID},
success: function (html) {
// do your HTML replace / add stuff here
},
});
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
So I am submitting data to the database. Each data sent contains an id that is auto incremented. With ajax or PHP (I am very much new to this, and trying to learn I'm sure it's ajax along with some php) I need to fetch the id of the data that was submitted.
The idea is, after the form is submitted, the user gets the link back to the submitted page. Example:
Quote was submitted! [link] Click to go to the link or go back.
The link will look like this: http://example.com/quote-192
I pretty much have everything else set, I just don't know how I'll get the id and add it to the link.
Here is the PHP that processes the form:
require('inc/connect.php');
$quote = $_POST['quote'];
$quotes = mysql_real_escape_string($quote);
//echo $quotes . "Added to database";
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
Oh, and the data is being sent with ajax:
$(document).delegate("'#submit-quote'", "submit", function(){
var quoteVal = $(this).find('[name="quote"]').val();
$.post("add.php", $(this).serialize(), function() {
var like = $('.quote-wrap span iframe');
$('.inner').prepend('<div class="quote-wrap group">' + like + '<div class="quote"><p>' + quoteVal+ '</p></div></div>');
// console.log("success");
});
return false;
});
So how would I get the id for each quote and add it to the page after the form has been submitted?
In you php:
echo mysql_insert_id($result)
Then in your jquery ajax:
$.ajax({
type:'post',
url:'url.php',
data:querystring,
success:function(data){
var id = parseInt(data);
}
]);
this will return the inserted ID as an integer value that you can work with in javascript
Have the PHP print the ID as a response to the request:
mysql_query("INSERT INTO entries (quote) VALUES('$quotes')")
or die(mysql_error());
// Print the id of last insert as a response
echo mysql_insert_id();
jQuery, test code to alert what was echoed by the PHP as a test
// add data as a param to the function to have access to the PHP response
$.post("add.php", $(this).serialize(), function(data) {
alert(data);
});
With this php-function. You can call after inserting.
int mysql_insert_id ([ resource $Verbindungs-Kennung ] )
mysql_insert_id
I have a simple load more style script that works fine on the index page, where only one parameter is sent via ajax
$(function() {//When the Dom is ready
$('.load_more').live("click",function() {//If user clicks on hyperlink with class name = load_more
var last_msg_id = $(this).attr("id");//Get the id of this hyperlink this id indicate the row id in the database
if(last_msg_id!='end'){//if the hyperlink id is not equal to "end"
$.ajax({//Make the Ajax Request
type: "POST",
url: "index_more.php",
data: "lastmsg="+ last_msg_id,
beforeSend: function() {
$('a.load_more').html('<img src="loading.gif" />');//Loading image during the Ajax Request
},
success: function(html){//html = the server response html code
$("#more").remove();//Remove the div with id=more
$("ul#updates").append(html);//Append the html returned by the server .
}
});
}
return false;
});
});
With this HTML/PHP
<div id="more">
<a id="<?php echo $msg_id; ?>" class="load_more" href="#">more</a>
</div>
However, I want to add another php variable so that it can also work with particular categories, I have no problems writing the HTML and PHP but I am new to Jquery and struggling to edit the script to include the additional parameter if it is set. This is the HTML that I am thinking of using, just struggling with editing the JQuery
<div id="more"class="<?php echo $cat_id;?>">
<a id="<?php echo $msg_id;?>" class="load_more2" href="#">more</a>
</div>
As always any help is much appreciated!
You can set
data = {onevar:'oneval', twovar:'twoval'}
And both key/value pairs will be sent.
See Jquery ajax docs
If you look under the data section, you can see that you can pass a query string like you are, an array, or an object. If you were to use the same method you already are using then your data value would be like "lastmsg="+ last_msg_id + "&otherthing=" + otherthing,
You can pass multiple URL params in the data portion of your ajax call.
data: "lastmsg="+ last_msg_id +"&otherparam="+ other_param
On the PHP side, you'd just process these as you already are.
You can use this code:
$.ajax({//Make the Ajax Request
type: "POST",
url: "index_more.php",
data: {var1: "value1", var2: "value2"},
beforeSend: function() {
$('a.load_more').html('<img src="loading.gif" />');//Loading image during the Ajax Request
},
success: function(html){//html = the server response html code
$("#more").remove();//Remove the div with id=more
$("ul#updates").append(html);//Append the html returned by the server .
}
});
Try It:
data: JSON.stringify({ lastmsg: last_msg_id, secondparam: second_param_value});
You can add more parameters separating them by comma (,).
I have a simple AJAX function to send an id of an object to a php page
My function looks like this:
$(function(){
$("a.vote").click(function(){
//get the id
the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: "?id="+the_id,
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
My vote.php looks like this:
session_start();
if(isset($_SESSION['user'])) {
// db setup removed
// insert vote into db
$q = "UPDATE votes SET vote = vote + 1 WHERE id = " . $_POST['id'];
mysql_query($q);
echo "You sent " . $_POST['id'];
}
When I execute my AJAX function, it appears that the vote.php is never run
I know that my AJAX function is being called correctly, because alert(the_id); is popping up with the correct ID.
I know my vote.php is functioning correctly because I can run an HTML method="post" with a textbox named "id", and it will update the database correctly.
Can anyone see what's wrong?
Thank you
You're trying to send your variables in the URL, not as POST variables. Should be something like:
$(function(){
$("a.vote").click(function(){
//get the id
var the_id = $(this).attr('id');
alert(the_id);
//ajax post
$.ajax({
type: "POST",
data: {id:the_id},
url: "vote.php",
success: function(msg)
{
$("span#message"+the_id).html(msg);
}
});
});
});
Your data should be as included as an object, not as a string URL. Check out the examples on the jquery API page for more info on this!
The principal thing I see in your code that doesn't look right is data: "?id="+the_id,. The ? is unnecessary, and illogical for a post request. Do the following instead:
data: {
id: the_id
}
This lets jQuery do the URL-encoding for you.
As an additional point, you do $(this).attr(id). This is very inefficient. Do this.id instead, for exactly the same effect hundreds of times quicker at least 20 times quicker.
Your data value shouldn't need a question mark at the beginning.