Jquery Ajax Data Post Problem in PHP - php

I am using jquery's AJAX in my project. Today, I used it somewhere else with all same themethods but it doesn't work.
Is there something wrong with my script?
HTML:
<a class='btn edit_receipe_btn' id='myreceipe-52'>Edit</a>
JQuery:
(Click function works. When I put alert(instance) after var instance line, it works)
$(document).ready(function(){
$('.edit_receipe_btn').click(function(){
var instance = $(this).attr('id');
var dataString = 'process=userReceipeEdit&instance='+instance;
$.ajax({
type: 'POST',
url: 'ajax/ajaxs.php',
data: dataString,
cache: false,
success: function(msg) {
alert(msg);
}
});
});
});
PHP:
$prcs = $_POST['process'];
if($prcs=='userReceipeEdit'){
$instance = $_POST['instance'];
return $instance;
}
It appears the problem is in the PHP. What am I doing wrong?

Is that the entire PHP page? if so, you should echo instead of return

As Jasper De Bruijn notified me, the problem was in my php script. I should use echo instead of return:
Wrong usage:
$prcs = $_POST['process'];
if($prcs=='userReceipeEdit'){
$instance = $_POST['instance'];
return $instance;
}
Correct usage:
$prcs = $_POST['process'];
if($prcs=='userReceipeEdit'){
$instance = $_POST['instance'];
echo $instance;
}

Two things, output the error and check to make sure instance is not undefined.
Output the error like this:
$('.edit_receipe_btn').click(function(){
var instance = $(this).attr('id');
var dataString = 'process=userReceipeEdit&instance='+instance;
$.ajax({
type: 'POST',
url: 'ajax/ajaxs.php',
data: dataString,
cache: false,
success: function(msg) {
alert(msg);
},
error: function(response, status, error)
{
alert(response.responseText);
alert(status);
alert(error);
}
});
});

I think you have formed this POST like a get, not sure why. Try doing this in JS:
var dataString =
{
"process" : "userReceipeEdit",
"instance" : instance
};

Related

Using Jquery AJAX to POST variable in PHP

I believe I have the right syntax but am missing something important. Been searching on here for a while but can't figure out why the POST variable is not being detected. Basically my .ajax is firing because my test statement has been changing due to the value but some reason can't receive variable via $_POST (i.e. my echo in php echo that it is not firing) Also the native file and php that I am sending it to are the same file blankFormTemplate.php but don't think that should be an issue.
$(document).ready(function()
{
var $selectedContexts = [];
$('.allContextField').change(function(){
//alert($(this).val());
hideField = $(this).val();
$('#'+hideField).remove();
$.ajax
({
type: "POST",
url: "blankFormTemplate.php",
data: addedContext=hideField,
cache: false,
success: function(addedContext)
{
$('#test').html($('#test').html()+hideField);
}
});
});
});
in my PHP blankFormTemplate.php:
<?php
if(isset($_POST['addedContext']))
{
echo 'hello';
}
else
{
echo 'why';
}
?>
Any help would be greatly appreciated.
Thanks,
Your javascript
$(document).ready(function()
{
$('.allContextField').change(function(){
hideField = $(this).val();
$('#'+hideField).remove();
});
if (hideField.trim()) {
$.ajax
({
type: "POST",
url: "blankFormTemplate.php",
data: (addedContext:hideField},
cache: false,
success: function(msg)
{
$('#test').html(msg);
}
});
}
});
Your PHP
<?php
if(isset($_POST['addedContext']))
{
echo 'hello';
}
else
{
echo 'why';
}
?>

ajax does not response

I try to take a response but I could not. I can't describe it why it does not work or what it is wrong.
var virmanYap = function(){
$("#loading").show();
$("#tblVirman").hide();
alert('Virman');
var data = $("#virman_filtre").serialize();
$.post("php/virman_yap.php", data).success(function(r){
alert(r);
});
}
my php code:
foreach ($_POST['virman'] as $evrakNo => $detay) {
print_r($_detay);
}
echo "asd";
Try $.ajax instead of $.post:
var virmanYap = function () {
$("#loading").show();
$("#tblVirman").hide();
alert('Virman');
var data = $("#virman_filtre").serialize();
$.ajax({
url: 'php/virman_yap.php',
type: 'POST',
data: data,
success: function (r) {
alert(r);
}
});
}
Check $.post documentation here: https://api.jquery.com/jQuery.post/
As you can see, success callback is one of the parameters, you don't need to chain it.
$.post("php/virman_yap.php", data, function(r){
alert(r);
});
Do something like this. Just remove the chained success function and you should be good.

Why is this returning me 'undefined' [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 10 years ago.
Trying to run a script, (test.al();) and inside test.al, its called getcrypt.php();, the php script is on a webserver, and it is working. Currently, these are my scripts
JS
var getcrypt = {
php: function () {
$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
return v;
}
});
}
}
var test = {
al: function () {
a = getcrypt.php();
alert(a);
}
}
PHP
<?php
$id = $_POST['id'];
if ('getit' == $id){
$value = 'VALUE';
echo $value;
}else{
echo 0;
}
?>
In this way, it will show an alert with 'unidefined', and if i add a alert(v); right before return v, it will show me 'VALUE', but not able to use it outside the variable...
var getcrypt = {
php: function () {
$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
alert(v);
return v;
}
});
}
}
This will give me an alert with the correct value (AFTER THE 'undefined')
This is because of the asynchronous call you're making. The return is only for the success function and not for the php function.
To get the value out you would need to write:
var value;
var getcrypt = {
php: function (callback) {
$.ajax({
url: "",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
alert(v);
callback(v);
}
});
}
}
getcrypt.php(function(v) {
alert(v);
// This happens later than the below
value = v;
});
// The below will still not work since execution has already passed this place
// alert will still return undefined
alert(value);
The problem is jQuery ajax works with callbacks and does not work with return value's so you need to add an callback to your getcrypt function so say
var getcrypt = {
php: function (callback) {
$.ajax({
url: "server.com/return.php",
type: "POST",
async: true,
data: "id=getit",
success: function (msg) {
var v = msg.match(/^.*$/m)[0];
callback(v);
}
});
}
}
so now if you call
getcrypt.php(function(returnVar){
alert(returnVar)
});
you will get an alert with VALUE
$.ajax returns immidiately (well, almost :)) upon calling, before the response is received. You should rewrite your code to accomodate to this fact, something like this;
var getcrypt = {
php: function(){
$.ajax({
//..other params ..//
success: function(msg){
var v = msg.match(/^.*$/m)[0];
alertResponse(v);
}
});
},
alertResponse: function(processedResponse) {
alert(v);
}
}
var test = {
al: function(){
getcrypt.php();
}
}
If you need your response in test object, you move alertResponse to that object and call it from success method. I think this tutorial might be useful for you to learn javascript event-driven programming model.
$.ajax calls are async. So what you get is the return value of $.ajax (when the request is sent, before a response is received). It is only when the browser receives a response to the ajax call that the success callback is run, as a seerate process from the $.ajax call. In other words the return value of $.ajax will always be null. I'm not sure it's possible to do anythging with the return value of the success callback, you need to put your logic (or a call to another function with the logic) in the success callback itself, in the same way you did with the alert in your final example

can't get AJAX get call to work even so the code seems correct

Ok fixed jQuery code with help of others on stack overflow
$(document).ready(function() {
$(".note").live('click',function() {
$("#note_utm_con").show();
$("#note_utm_nt").html("<img src='http://www.ajaxload.info/images/exemples/4.gif' />");
$.ajax({
type: "GET",
url: "view.php",
data: "ajax=1&nid=' + parent.attr('id').replace('record-','')",
success: function(html){
$("#note_utm").html(html);
$("#note_utm_nt").html("");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#note_utm_nt").html("<img src='http://www.ajaxload.info/images/exemples/4.gif' /> Error...");
}
});
});
});
The PHP code for view.php
include 'object/db.class.php';
if($_GET['ajax'] == '1') {
#make a call to my sql to fetch some sort of ID
$nid = $_GET['nid'];
$q = mysql_query("SELECT * FROM `notice` WHERE nid = '".$nid."'");
$a = mysql_fetch_array($q);
$nid = stripslashes($a['nid']);
$note = stripslashes($a['note']);
$type = stripslashes($a['type']);
$private = stripslashes($a['private']);
$date = stripslashes($a['date']);
$author = stripslashes($a['author']);
$note_viewer .= <<<NOTE_VIEWER
<h2>By: $author</h2> - <h2>$date</h2>
<br/>
<p>$note</p>
<p>Request: $private</p>
NOTE_VIEWER;
echo $note_viewer;
}
The AJAX seems to be working now as it gives me Error...
concerning the docu of jQuery, you attach an event with the live() method. In your code, you define the click-method of node twice, I think: once with the live-attaching-stuff and once with note.click(). So it is not clear what to do when clicking or better when node is clicked, the click-event is defined :-) You define two different actions when note is clicked... try this one:
$(document).ready(function() {
$(".note").live('click',function() {
$("#note_utm_con").show();
$("#note_utm_nt").html("<img src='http://www.ajaxload.info/images/exemples/4.gif' />");
$.ajax({
type: "GET",
url: "view.php",
data: "ajax=1&nid=' + parent.attr('id').replace('record-',''),
success: function(html){
$("#note_utm").html(html);
$("#note_utm_nt").html("");
}
});
});
});
So what exactly is it doing? and What element is not visible? Your AJAX call isnt even using the response. If I understand your logic correctly, it should be...
$.ajax({
type: "GET",
url: "view.php",
data: "ajax=1&nid=' + parent.attr('id').replace('record-',''),
success: function(html){
$("#note_utm").html(html);
$("#note_utm_nt").html(html);
}
});
the "html" variable in the success function is the response from the php script.

Rebind dymanically created forms after jQuery ajax response

I'm kinda new to jQuery but understand it for the most part. My problem is that when my ajax call which refreshes the entire div is done, all my dynamically created forms don't work. If you try and submit them, the event doens't work properly and just tries to do a normal form submit. I have all the other items such as links bound using the .live() which seem to work great. Just the form dies.
How do I rebind the dynamically created forms after the ajax call? They all have id of formname_id. I tried to use bind but it doesn't work as below. Any help is appreciated.
Here is the code
jQuery(document).ready(function(){
jQuery("form[id^='commentform_']").each(function(){
var id = parseInt(this.id.replace("commentform_", ""));
jQuery(this).bind('submit', function(e) {
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: "action="+ action +"& act_id="+ act_id,
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
return false;
});
});
});
Try doing something like this:
jQuery("form[id^='commentform_']").live('submit',function(){
var id = parseInt(this.id.replace("commentform_", ""));
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: {"action": action, "act_id": act_id},
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
return false;
});
No need to loop over the forms to bind to them. If you can use delegate instead of live do so.
Why don't you over-ride the normal form submit:
function addNewitem() {
$('#new_item_form').submit(function() {
$.get("includes/ItemEdit.php", {
newItem: true
},
function(msg) {
isNewItem = true;
$("#new_item").hide();
$('#item_list').hide();
$("#item_edit").html( msg );
$("#item_edit").show();
editActiveEvent();
});
return false;
});
}
Don't forget to return false. or do a .preventDefault
I have gotten this to work adding the event in the function call and using event.preventDefault(); BUT of course only in FF. Doesn't work in IE7..
jQuery("form[id^='commentform_']").live('submit',function(event){
var id = parseInt(this.id.replace("commentform_", ""));
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: {"action": action, "act_id": act_id},
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
event.preventDefault();});
But IE7 still tries to sumbit the action. arrgggh.. Anything I'm doing wrong??

Categories