returning data from a remote php script - php

I am using php/ajax to submit a form without page refresh. Here are my files-
coupon.js
jQuery(document).ready(function(){
jQuery(".appnitro").submit( function(e) {
$.ajax({
url : "sms.php",
type : "post",
dataType: "json",
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
//return false or
e.preventDefault();
});
});
sms.php
<?php
//process form
$res = "Message successfully delivered";
$arr = array( 'mess' => $res );
echo json_encode( $arr );//end sms processing
unset ($_POST);
?>
and here is code for my html page -
<form id="smsform" class="appnitro" action="sms.php" method="post">
...
</form>
<div id="mess" style="background:green;"></div>
Now instead of submitting form through ajax without page refreshing what is happening is that page gets redirected to
baseurl/sms.php and the only thing visible on page is
{"mess":"Message successfully delivered"}
My guess is that php script is not returning back successfully to the jquery and hence the echo in last part of sms.php is getting displayed. How should i make the php script return successfully?
ANY IDEAS HOW TO DEBUG THIS.I HAVE TRIED USING return false at the end of coupon.js but no results.
When i click on submit firebug gives following results -
POST http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php
404 Not Found 1.29s `jquery.min.js (line 130)`
Response
Firebug needs to POST to the server to get this information for url:
http://174.132.194.155/~kunal17/devbuzzr/wp-content/themes/street/sms.php
This second POST can interfere with some sites. If you want to send the POST again, open a new tab in Firefox, use URL 'about:config', set boolean value 'extensions.firebug.allowDoublePost' to true
This value is reset every time you restart Firefox This problem will disappear when https://bugzilla.mozilla.org/show_bug.cgi?id=430155 is shipped

#Fanis It's irrelevant whether he uses '$' or 'jQuery', they are synonyms.
#Ayush
As Fanis says, you should try Firebug if you don't use it already.
I've checked the example at my server, works OK, and I don't know
what's the problem at Your side.
You can use onsubmit="return false" to disable form submission:
<form id="..." class="..." ... onsubmit="return false">
Also check if javascript is enabled, for example do "alert('something')"
at $(document).ready
Edit:
// instead of
url: "sms.php"
// try
url: "/~kunal17/devbuzzr/wp-content/themes/street/sms.php"
// although I don't really know if it will help

If you're being redirected to sms.php instead of doing an ajax call, it probably means that there's something wrong with your jQuery code, probably the event binding itself.
I'm not sure without testing it, but shouldn't that code be:
$(document).ready(function(){
$(".appnitro").submit( function(e) {
$.ajax({
...
?
Check the javascript console, either in Firefox/Firebug or Chrome-IE/Developer Tools. Does it show any errors in those lines?

Fanis and Michal Kluczka are probably right about the issue with event binding , I tried your code myself as well, and it works for me.
Put an alert('X') as the first statements in your jQuery(document).ready() and jQuery(".appnitro").submit() functions and see if both are displayed (first one upon document load, second one upon form submission).
One more thing: I suggest you include a
header('Content-Type: application/json');
into your sms.php file before printing your JSON data to protect against cross-site-scripting (XSS) attacks. See also Don’t serve JSON as text/html for details.

Related

Php form in html document avoiding redirecting to the top when submitting form

I included a php form into my html code and changed it from index.html to index.php. The contact form is working well and sending everything. After submitting the user gets the message "Thank you. The message has been sent.". However, when the page is refreshed it jumps up to the header and the user has to scroll down again to see the message.
I know why this happens. A couple of days ago I had included this code:
$(document).ready(function(){
$(this).scrollTop(0);
});
I did so because when somebody visited my website he was directed to the contact form first and the page did not load at the header first. However, now, when somebody is submitting a message the page scrolls again to the top. Do you know any way to avoid this? It would be nice if the user would see the header first when visiting the website but should be redirected to the form section when submitting a message.
Thank you for your help.
Use a cookie:
https://www.w3schools.com/js/js_cookies.asp
$(document).ready(function(){
if(!getCookie(cname)){
$(this).scrollTop(0);
}
});
$( "#formID" ).submit(function( event ) {
setCookie(cname, cvalue, exdays)
});
Essentially you have two possible states. The first possible state is when you want to scroll to the top, the other is when you do not want to scroll to the top. Let's assume that you know what the condition is to be tested. In that case your code would look like:
<?php
if ($condition) {
?>
//your scrolling JS code
<?php
}
?>
Now, how could we determine $condition? an idea is to store some value in the $_SESSION of the user, which will be a logical value which will determine whether we need to scroll or not. You should check whether the value exists in $_SESSION and if not, default it to true or false (depending on your actual need).
When using jQuery, return false is doing 3 separate things when you call it:
event.preventDefault();
event.stopPropagation();
Stops callback execution and returns immediately when called.
See jQuery Events: Stop (Mis)Using Return False for more information and examples.
Ref
Wrap that particular JS code block with a PHP if condition that checks whether the form has not been submitted. E.g.
<?php if (!$formSubmitted) { ?>
[JS code here]
<?php } ?>
Try this
$('form').submit(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
url: "your_page.php",
data: $('form').serialize(),
success: function(response) { /*what to do on response*/ },
});
});
Here i prevent default submit with reloading and send ajax post

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.

Form auto submit ajax not working

I'm passing some variable from one file to another php file that contains a form via jQuery ajax. On The form page where data is being passed to have the following code in it, The values are getting passed in properly and and fields are getting populated with the correct entries, i'm able to very this with firebug response, but page is not automatically submitting. Is their anything i should be looking for that is preventing form from auto submitting. If i access the form page directly, i can see auto submit works.
<?php
$title = $_POST['title'];
$wrapper = $_POST['wrapper'];?>
<form action="test.php" method="post" id="publish">
<input type="text" value="<?php echo $title ?>" name="title">
<textarea name="wrapper"><?php echo $wrapper?></textarea>
<input type="submit" value="Submit">
</form>
<script>
window.onload = function(){
document.getElementById('publish').submit();
}
</script>
ajax code that is sending the values looks like this
$.ajax({
type: "POST",
url: "process.php",
data: {
title: 'test',
wrapper: 'testing123'
},
success: function(msg){
alert( "Data Saved: " + msg );
}
});
Spot the difference:
getElementById('publishForm')
id="publish"
From what I see the auto submit is linked to the 'publishForm'
However, your form Id is "publish"
This is probably the cause of the code not working.
Perhaps you should show us the caller code instead of the handler code. Most likely what you're dealing with is the JS not being run during the AJAX call - the PHP page processing is server side.
You could look into sending the form using PHP Curl instead of JS? That would probably address the issue where it works loaded directly, but fails when called from another page.
As far as I understood, that HTML is being loaded through AJAX, right? If so, then window.onload will not be fired since the page was already loaded (AJAX doesn't count). Just do this:
<script type="text/javascript">
document.getElementById('publish').submit();
</script>
EDIT
To break this down:
Your code on SourcePage.php(I made up this name for reference) is posting data to process.php via an AJAX request
process.php then injects "title" & "wrapper" into the html markup and returns html with some javascript to SourcePage.php
You're then expecting that displaying the resulting string (msg) of the returned html on SourcePage.php will get the javascript in that string to execute.
To get this working, you'll need to do a few things.
Parse out the incoming javascript from the html.
Inject the incoming parsed HTML into SourcePage.php's markup.
Pass the parsed out JavaScript into JavaScript's eval function.
Doing this should bring the page from the process.php and successfully execute the JavaScript code on SourcePage.php.
If you were expecting that the JavaScript would run on the server, then I'm afraid you're mistaken as the server(php runtime) will not execute the JavaScript on the server. Perhaps a redirect on the server will accomplish your goal (whatever that may be).
Original
Try this out: http://jsfiddle.net/NiceGuy4263/eJLMS/

Return results from a MySQL database using jQuery/AJAX and insert into a DIV

I am working on a project for reserving classrooms. One way of reserving a room is to select a room, see if the things it has (# of seats, # of computers, etc.) is ample for whatever the person needs it for, and then make a reservation.
I have a page that displays all of the available rooms as links in an HTML table, created dynamically in PHP/MySQL. My goal is when a user clicks on a room name, the AJAX request executes a query and returns the necessary data, and then displays it in a DIV on that same page.
Right now, I'm calling an external PHP file that gets the ID of the room that's clicked and executes the query. I'm still very much a novice at jQuery, and I'm pretty sure the problem is in my jQuery script:
<script type="text/javascript">
$(document).ready(function()
{
$('table.roomNums td a.rm-details').click(function()
{
var id = $(this).attr('id');
$.ajax(
{
type: 'POST',
url: 'roomInfo.php',
data: {
roomID: id
},
dataType: 'json',
cache: false,
success: function(result)
{
$('#room-details').empty();
$('#room-details').append("<ul>\n\t<li>Seats: " + result.numOfSeats + "</li>\n</ul>");
}
});
});
});
</script>
As of now, when I click on one of the room number links, nothing happens. I'm assuming that my problem resides in this script, but I'm not sure where or what. I've been reading into the ajax function in jQuery and I'm pretty sure I understand what's going on, but I'm having no luck at the moment.
You want to troubleshoot the following four things:
The HTTP Request Does the browser even issue an ajax request? If so, does it contain the form parameter you are trying to make it contain?
The HTTP Response Does your php script return the data you are expecting in JSON format so JQuery can automatically parse it for you? Copy and paste the response from the server into a test javascript file and see if it compiles as a valid JSON object in a javascript debugger.
AJAX success function Does your javascript error out? Can you step through each line of execution in a javascript debugger like firebug?
Click Event Handler Does your click handler properly return false so the page does not reload? Does your click event handler function fire at all upon click?
Somewhere in the above four things lies your issue. It looks to me like you just need to return false in your click handler so the page does not reload.

jQuery .post gets null data

This is my first post here, so I hope I'm doing it appropriately.
I have several jQuery $.post calls that work just fine. They send data to a PHP script that modifies a database and returns some data. No problem.
But this one doesn't work. The returned data is just NULL.
$.post("act_addTaskLog.php",
{description: $("#logFormDescription").val(), complete: $("#logFormComplete").is(':checked'), taskId: $("#logFormTaskId").val(), user: <?php echo $_SESSION['user']; ?>},
function(data) {
alert("data: " + data);
}
);
I've tried everything I can think of, to no avail. I've even tried just one line in my PHP script:
die("true");
Firebug shows that the script is being executed, but it's not completing. The alert message displays just with the label "data:" in it, no actual data.
Thanks in advance for your help!
I feel like an idiot now. The problem was outside the code I posted here.
The $.post call is being made as the button action on a Dialog. I added a keydown listener for the Dialog (in the "open" method), so it would submit when Enter is pressed.
For some reason, pressing Enter reloaded the entire page. So I added this line to my keydown listener code:
window.stop();
That line was causing my problems with the callback data. Removing it fixed this issue. My actual $.post code was just fine.

Categories