Load respond of php document into a textfield - jQuery/Ajax - php

i do have a litte problem with my actual project.
My .HTML document gives via post some data to a php document wich is only echoing some numbers and letters but no spaces. So now id like to load that respond directly into a textbox, without showing the "ugly" respond php doc or reloading the site.
thanks for help

$.ajax({
url: "/mydoc.php",
type: 'POST',
data: {tb1: "arbitrary"}, // this could be anything
success: function(data) {
$("#myTextBox").val(data);
}});
Hope this helps!

You can accomplish this with jquery.
You will need to capture your response and set the textfield value attribute.
If you are getting data perhaps you should use GET method instead of post.
$.get('your_php_url?some_data=here&some_more_data=here', function(response, status) {
if (status === 'success') {
$('#your_textbox').val(response);
}
});
Or even better encode your data in JSON instead of passing plain text.
$.getJSON and set your textbox to the json response
you can use submit to attach a submit handler to your form. Make sure to return false so the form doesn't go to the action page.

Related

Jquery / Ajax form submission won't forward POST data

I have a PHP script that generates identical forms with different values (ie. lines of a database)
When one form is submitted, I want it to trigger an AJAX request that will update just that line of the database without reloading the page.
I have this AJAX script in my header:
function ajaxCall() {
$.ajax({
url:"database_quickupdate.php",
type: "POST",
success:function(result){
alert(result);
}
});
And obviously all forms have onsubmit="ajaxCall()" attributes set
But when I try to return the $_POST array from database_quickupdate.php, it comes back empty (meaning no data is passed to the script)
I tried various versions of serializing the data, including this here:
$.ajax({
type: "POST",
url: 'database_quickupdate.php',
data: $(this).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
but this didn't work either.
Of course I can assign unique ID-s to each of the forms, but then how can I tell ajaxCall in the header that I want the values from the form that_has_just_been_submitted?
It must be something very basic, still, I'm lost. I think I'm missing something on the jQuery side, but I'm not even sure about that.
Thanks for your help
onsubmit="ajaxCall()"
You're calling ajaxCall() by itself, so inside it this is the default object (window in a browser).
So then:
$(this).serialize()
You are trying to serialize the window and not the form.
You need to pass the form.
Don't use on... attributes. They come with a host of issues.
Bind your event handlers with JavaScript instead.
jQuery("form").on("submit", ajaxCall);
That will pass the form as the value of this.

Using ajax for form submission with multiple forms generated by php on page

I have a page with multiple forms that do the same thing, acting as a like button for each post in the page, and right next to it the number of likes inside a div named "likes".$id, so I can identify where to write the likes count after the ajax call. I was trying to use jQuery ajax function, but I couldn't set what div to write the results of the function.
$.ajax({
type:'POST',
url: 'likepost.php',
data:$('#like').serialize(),
success: function(response) {
$('#like').find('#likediv').html(response);
}
});
And how would I access the data on likepost.php? I am terrible with javascript, so I hope someone could help me and explain how the jQuery function really works, because I've been copying and pasting it without really knowing what I was doing.
Would this work?
$(function () {
$("#likebutton").click(function () {
var id = $('input[name=id]'); // this is me trying to get a form value
$.ajax({
type: "POST",
url: "likepost.php",
data: $("#like"+id).serialize(), // the form is called like+id e.g. like12
success: function(data){
$("#likes"+id).html(data); // write results to e.g. <div id='likes12'>
}
});
});
});
I put this in the code but when the button is clicked, the usual post refreshing page is done. Why is that?
Making a mini-form, serializing it, and POSTing it seems like a lot of heavy lifting when all you really want to do is send the ID to the likepost.php script.
Why not just retrieve the ID and post it to the script?
First let's break down your function:Type is the type of the request we're making, you specified POST here. This means in your PHP file you'll access the data we're sending using $_POST. Next up is URL which is just the url of where you're sending the data, your php file in this case.
After that is data, that is the data we're sending to the url (likepost.php). You're serializing whatever has a ID of "like" and sending it to the php file. Finally success is a function to run once the request is successful, we get a response back from the PHP and use it in the function to output the response.
As for the multiple forms I'd recommend doing something like:
http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
Here's documentation on the stuff we talked about, if you're every confused about jquery just break it down and search each part.
http://api.jquery.com/serialize/
http://api.jquery.com/jQuery.ajax/
you can try :
function submitform(id) {
var jqxhr = $.post('./likepost.php',$("#"+id).serialize(), function(data) {
$("#"+id).find('#likediv').html(data);
}, "json")
return false;
}
in form:
<form method="post" id="likeForm" onsubmit="return submitform(this.id);">
<input..... />
<input type="submit" value="Submit" />
</form>
in likepost.php add first line:
if ($_SERVER['HTTP_X_REQUESTED_WITH'] != "XMLHttpRequest") {
header("location: " . $_SERVER['HTTP_REFERER']);
exit();
}
you can see more : http://api.jquery.com/serialize/
working for me.

Ajax Post PHP Div Refreshing

It is me again. I am getting so frustrated with this code it is not even funny. It's not that I am wanting to post it again. It is just that now I understand the where the problem was in the code and wanted to see if you guys can help me figure the last part out.
Basically I am trying to refresh a div without reloading the entire page. It's killing me. Here is some more information on it:
here is my js file first
$(function() {
$(".button").click(function() {
// validate and process form
// first hide any error messages
var email = $("input#email").val();
//var dataString = '&email=' + email; commented out
var dataString = email;
//try insted this //alert (dataString);return false;
$.ajax({ type: "POST", dataType:'HTML',
//or the appropiate type of data you are getting back
url: "http://www.edshaer.com/EdinburgCISD/Gorena/Gorena.php", data: {email:dataString},
//in the php file do $email = $_POST['email'];
//not a good practice but you can try with it and without it
success: function() {
$("#div").fadeOut($("#div").html());
$("#div").fadeIn($("#div").html());
$("#email").val('');
// Change the content of the message element
// Fade the element back in
} });
//ajax ends
return false; });
//click ends
});//document ready ends
Now the problem that I am running into with this code is on the Ajax part. After placing the alert(), I have relized that if I use the function() like this:
success: function(data)
Then the alert came out blank. The reason behind it is that my URL is going to my php file, but my div that I am trying to refresh is on my html file. Meaning if I do this:
success: function(data) {
$("#div").html(data)}
I am sending blank data because it's trying to get the div from my php file instead of my html file.
Now if I do this:
$("#div").html()
Then that gives me the div that is in my html file.
By knowing what is going on now, Can you guys please help me???
My dear you should generate some sort of html in your php file that you want to generate in your div. Then you will see that you are having some content in data in the success function. This is an easy approach.
But there is also some other approach that is more efficient but it needs some sort of search. This is the implementation of Client Side Scripting. You can do this with the help of a jquery plugin jquote2. I hope it will work for you.
You're using
$("#div").fadeOut($("#div").html());
$("#div").fadeIn($("#div").html());
Both are wrong, jQuery .fadeIn() and .fadeOut() arguments are either [duration,] [callback] or [duration,] [easing,] [callback]. None take HTML as input.
Try changing
$("#div").fadeOut($("#div").html());
to
$("#div").fadeOut();
and moving it outside the $.ajax call to hide the previously showed (if any) results before the post and also change
$("#div").fadeIn($("#div").html());
to
$("#div").html(result).fadeIn();
Also change
success: function()
to
success: function(result)
Hope it helps.
This might be a problem relating to the response from the php script. Jquery doesn't always correctly render the Ajax response as html.
Setting dataType: html in the $.ajax({ ... }) call can help. Also setting header("Content-Type: text/html"); at the top of your php ajax script.

How to populate one form data into another form on same page before submit is clicked using ajax or js?

I am new to ajax and javascript.
I want to populate a entry form data into another form on the same page before it is submitted.
That means i want to display the name,gender etc of registration form in another form on the same page before it is submitted with click button event.
Please anybody post some examples.
(In response to your comment on the question above...)
Ah, that example is significantly more complex than previously implied. The target in that example isn't a form, it's an image. Do you have functionality in your server-side code already for generating the image?
Posting the AJAX to the server is very much the easy part in this case. Using jQuery for example, you can do something like this:
$.ajax({
type: 'POST',
url: 'somepage.php',
data: data,
success: function() {
alert('success!');
},
dataType: 'json'
});
The variable 'data' would be built from your form elements. Possibly something like this:
var data = '';
data = data + 'somevalue=' + $('#formElement').val();
data = data + 'anothervalue=' + $('#aDifferentElement').val();
// etc.
What the code essentially does is submit an HTTP POST to the supplied URL with the supplied data, and then run the supplied "success" function upon a successful result. You can also add an "error" function for an error result.
In your case, the result looks like it's an image. So you'd end up setting the src attribute on an img tag to the resulting image. Something like this:
$('#imageElement').attr('src', someString);
I'm not sure exactly how they're doing it in that example, but you can certainly look through the code and step through it in Firebug to see what you can find. The response appears to be the actual image, not a link to the image. But you can design yours either way.

PHP json_encode unread by jQuery AJAX Post

I'm posting from a form to a URL like so:
$.post('?class=articles&method=submit', $(this).serialize(), function(msg)
{
alert(msg);
$(msg.html).hide().insertBefore('#addCommentContainer').slideDown();
$('#body').val('');
},'json');
And in the 'submit' method the last line is:
print json_encode( array('html'=>$content) );
Yet I'm not even getting to the alert portion in the jQuery.
I have a feeling it is because the 'submit' method is in a class file that is part of a template system (similar to phpBB). I know that creating a seperate .php file for submitting would work, but was curious if there was any other way.
Looks like you don't even have a specific url:
$.post('?class=articles&method=submit', $(this).serialize(), function(msg)
Should be I think
$.post('thePlaceIsubmitTo.php?class=articles&method=submit', $(this).serialize(), function(msg)
I believe that the serialize data will be appended to the url with and &, Be sure that this refers to the form tag
try using the $.ajax method, instead of the shorthand. I believe the problem is that you're using the POST shortcut method, while specifying GET variables appended to the URL.
Let me know if this helps, if not, We'll be able to help you :-)
I'm on vacation, on a netbook, so I can't exactly write a whole new method at the moment.

Categories