ajax does not response - php

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.

Related

Execute php using jquery post

I've tried to go to php file using jquery.
Here is my code.
This is index.php
$.post('test.php',data,function(json){},'json');
This is test.php
//set session variable from passed data
$_SESSION['data1'] = $_POST['data1'];
<script>
window.open('test1.php','_blank');
</script>
This is test1.php
echo $_SESSION['data1'];
But this code is not working.
I want to pass data from index.php to test1.php.
How can I do this? I don't want to use GET method because of too long url.
Anyhelp would be appreciate.
I am not quite clear from you explanation right now. But I am here trying to resolve you problem as you can use the jquery post method as follows :
$.post('test1.php',{param1:value1,param2=value2,...},function(data){
//Here you can take action as per data return from the page or can add simple action like redirecting or other
});
Here is a simple example of register :
$.post('', $("#register_form").serialize(), function(data) {
if (data === '1') {
bootbox.alert("You have registered successfully.", function() {
document.location.href = base_url + '';
});
} else if (data === '0') {
bootbox.alert("Error submitting records");
} else {
bootbox.alert(data);
}
$("#user_register_button").button("reset");
});
Try this:
$.ajax({
url: 'test.php',
type: 'POST',
data: {
myData : 'somevalue'
},
success: function(response){ // response from test.php
// do your stuff here
}
});
test.php
$myData = $_REQUEST['myData'];
// do your stuff here
I like use jQuery post a url like this.
$('form').on('submit', function(e) {
e.preventDefault();
var $this = $(this);
$.ajax({
url: $this.attr('action'),
method: $this.attr('method'),
data: $this.serializeArray(),
success: function(response) {
console.log(response);
}
})
});
I you a beginner, you can reference this project
php-and-jQuery-messageBoard

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

Passing a Javascript Array through JQuery AJAX to PHP

$('#button').live('click', function () {
values_array = [];
$('.field').each(function () {
values_array.push = $(this).val();
});
$.ajax({
url: 'page.php',
data: {
array_a: values_array
},
type: 'POST',
success: function (data) {
$('#div').html(data);
}
});
});
//page.php
echo $_POST['array_a'] . "<br/>"; //The line break echos, but nothing else
A.) Do I need to iterate through each class with $.each in order to create a proper array, and
B.) Why doesn't php echo it?
Change:
values_array.push = $(this).val();
to:
values_array.push($(this).val());
That should do the trick :)
.push is a method which you have used like a property try instead
values_array = [];
$('.field').each(function() {
values_array.push($(this).val());
});
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push

Execute php script with JS [duplicate]

Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request

Jquery Ajax Data Post Problem in 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
};

Categories