Make Directory

Php send a get request jquery

Solution 1: Try this — and let me know EDIT MY WORKING CODE — Solution 2: As swapnesh implies, you’re missing that expects an object as the second parameter: Then in PHP you retrieve it with this: Solution 3: In http requests both post and get,the values are sent as a Name/value pair. Every parameters shall be inputed in the either in string form(like the one above) or object form( ).

Send/receive data via jQuery to/from PHP

I am using this code to make the user input a name to create a folder. I have modified the code to try and send the form data via jQuery and receive the success/failure message from PHP through jQuery.

However, when I enter the name of the folder, nothing happens. No folder is created nor any error displayed. Firebug does not show any error either.

This is the code I have till now:

   

$success":""); ?> ' . $error . '':''); ?>


"; >else < $error = "Unable to create dir ."; > >else < $error = "Directory already exists."; > >else < // Invalid data, htmlenttie them incase < >were used. $dirName = htmlentities($dirName); $error = "You have invalid values in ."; > > ?>

There are at least two seperate problems with your code:

Читайте также:  What is integer range in java

In the php-file, you check if $_POST[‘btn_album’] is set. This field is not sent as it is not part of your ajax-request (You’re only sending «create_album» : $(«#create_album»).val() ). So the code that creates the folder is never executed.

Another problem is the part

in your response-message. This code is evaluated when the page loads, not during your ajax-request, so the php-variables $success and $error will always be undefined. You have to return those response-messages as response to the actual request and then use javascript to display them.

The ajax request has a bad habit of failing silently. You should use jQuery post and take advantage of .success(), .complete(), and .error() functions to track your code. Also use the console.log() to check if the parameters are sent corectly. I’ll try out the code myself to see the problem.

Due to the nature of the $.ajax request, $_POST[‘btn_album’] is not sent. So your php file gets here

also you need to echo $error to get a response.

Javascript — jQuery/PHP mail send the easy way?, Sounds like it works. Its doing ajax which doesn’t redirect but submits on request. So its as if you never leave the page but yet the mail is send if your sendmail.php is correct. basically what you want to do is attach the callback information to the jQuery(«.email-us».html(); i am going to update my answer …

Send values to $_GET using jQuery

I’m using a PHP script that is waiting for two values through $_GET.

I’m trying to pass those 2 values using jQuery and that’s where I’m not too good at.

Can somebody point me in the right direction ? Thanks !

(actual code copied from the comments)

function xrate(id,rating)< var oDate = new Date(); $.ajaxSetup(< cache: false >); $.ajaxSetup(< scriptCharset: "utf-8" , contentType: "application/x-www-form-urlencoded; charset=UTF-8" >); $.ajax(< url: 'ajax_xrate.php?timestamp='+oDate.getMilliseconds(), dataType: 'html', data: , cache: false, type: "GET", success : function(dataReturn) < alert(dataReturn); >>); > 
function xrate(id,rating)< $.ajax(< url: "ajax_xrate.php", data: < id: id, rate:rating >, type: "GET", success: function() < alert('Bravo!'); >>); > 
function xrate(id,rating)< $.get("ajax_xrate.php", < 'id': id, 'rate': rating >, function() < alert('Bravo!') >); > 
jquery.ajax work like this jQuery.ajax(< url:'you_ur', type:'GET' or 'POST', data:, // name value pair of props waiting on server //etc etc here >); 

You don’t need set parameters like type = ‘get’ because they are already default. Every parameters shall be inputed in the data: either in string form(like the one above) or object form( ). Async is also true on default in case you didn’t know

Http — How to send a GET request from PHP?, On the other hand, using the REST API of servers is very popular in PHP. You can suppose all URLs are parts of a REST API and use many well-designed PHP packages. Actually, REST API is a way to use services from a site. So, there are many PHP packages developed to simplify REST API call. For …

Send dynamically created input values to PHP using get request

i have a form. i’m allowing the user to add extra inputs by pressing a button:

$('#add_multi_item').click(function()< $('').attr().appendTo('#multi_responses'); next_add_id++; >); 

and my form is being submitted like this:

$("#add_form").bind('submit', function(event)< event.preventDefault(); $.get('file.php', , function(data) < $('#added').show().html(data); $('#added').hide(7000); $('#question_input').val(''); loadList(); >); >); 

how do i add those dynamically created input values into the get request? i guess some people use name arrays for post, but can i do something similar? also i think i will have to escape() all the inputs before sending them to prevent errors when adding to the database.

one option i was thinking was to send a single value, a delimited string created using something like:

$("#multi_responses input").each(string+=escape($(this).val())+"delimiter"); 

but i don’t know if that’s the best way. and if i do that, what is a typical delimiter to use?

That’s right, you just have to give those inputs a name attribute, like:

$('').attr().appendTo('#multi_responses'); 

Sending and receiving AJAX requests with jQuery and PHP, $.get will strip out

Send a post oneway with jquery.post

I have a variable we will call test_string which I am assigning the string «hello» too.

And I want it to post to a php page just oneway I have tried:

$.post('php_page.php', test_string); 
$new_var = $_POST['test_string']; echo $new_var; 

And get no result. What am I missing in the $.post()?

EDIT MY WORKING CODE

test.php           

As swapnesh implies, you’re missing that $.post expects an object as the second parameter:

Then in PHP you retrieve it with this:

In http requests both post and get,the values are sent as a Name/value pair. In your code you are missing two things. the first thing is you are trying to send just the data without assiging it in to a Name/vale pair. And the second thing is you have not writtien the function to catch the server response.

$.post('php_page.php', test_string: "hello", function(response) < alert(response); >); 

JQuery $.ajax(),$.post() sending GET as Request Method, Try adding the type also. function postAjax (URL,jsonData) < $.post (URL,jsonData, type:'POST', function (data) < response = data; alert ("In success"); console.log (data); >, «jsonp»); return response; > B/w the jsonp datatype might be the reason here. Check this answer. This is a case of cross-domain json object …

Источник

Примеры отправки AJAX JQuery

AJAX позволяет отправить и получить данные без перезагрузки страницы. Например, делать проверку форм, подгружать контент и т.д. А функции JQuery значительно упрощают работу.

Полное описание функции AJAX на jquery.com.

GET запрос

Запрос идет на index.php с параметром « text » и значением « Текст » через метод GET.
По сути это то же самое что перейти в браузере по адресу – http://site.com/index.php?text=Текст

В результате запроса index.php вернет строку «Данные приняты – Текст», которая будет выведена в сообщении alert.

$.ajax(< url: '/index.php', /* Куда пойдет запрос */ method: 'get', /* Метод передачи (post или get) */ dataType: 'html', /* Тип данных в ответе (xml, json, script, html). */ data: , /* Параметры передаваемые в запросе. */ success: function(data) < /* функция которая будет выполнена после успешного запроса. */ alert(data); /* В переменной data содержится ответ от index.php. */ >>);

Код можно сократить используя функцию $.get

$.get('/index.php', , function(data)< alert(data); >);

Код файла index.php

echo 'Данные приняты - ' . $_GET['text'];

GET запросы могут кэшироваться браузером или сервером, чтобы этого избежать нужно добавить в функцию параметр – cache: false .

POST запросы

$.ajax(< url: '/index.php', method: 'post', dataType: 'html', data: , success: function(data) < alert(data); >>);

Или сокращенная версия – функция $.post

$.post('/index.php', , function(data)< alert(data); >);

Код файла index.php

echo 'Данные приняты - ' . $_POST['text'];

POST запросы ни когда не кэшироваться.

Отправка формы через AJAX

При отправке формы применяется функция serialize() , подробнее на jquery.com.

Она обходит форму и собирает названия и заполненные пользователем значения полей и возвращает в виде массива – .

  • Кнопки формы по которым был клик игнорируются, в результате функции их не будет.
  • serialize можно применить только к тегу form и полям формы, т.е. $(‘div.form_container’).serialize(); – вернет пустой результат.

Пример отправки и обработки формы:

Код файла handler.php

if (empty($_POST['login'])) < echo 'Укажите логин'; >elseif (empty($_POST['password'])) < echo 'Укажите пароль'; >else

Работа с JSON

Идеальный вариант когда нужно работать с массивами данных.

Короткая версия

$.getJSON('/json.php', function(data) < alert(data.text); alert(data.error); >);

$.getJSON передает запрос только через GET.

Код файла json.php

header('Content-Type: application/json'); $result = array( 'text' => 'Текст', 'error' => 'Ошибка' ); echo json_encode($result);

Возможные проблемы

При работе с JSON может всплыть одна ошибка – после запроса сервер отдал результат, все хорошо, но метод success не срабатывает. Причина кроется в серверной части (PHP) т.к. перед данными могут появится управляющие символы, например:

Управляющие символы в ответе JSON

Из-за них ответ считается не валидным и считается как ошибочный запрос. В таких случаях помогает очистка буфера вывода ob_end_clean (если он используется на сайте).

. // Очистка буфера ob_end_clean(); header('Content-Type: application/json'); echo json_encode($result, JSON_UNESCAPED_UNICODE); exit();

Выполнение JS загруженного через AJAX

В JQuery реализована функция подгруздки кода JS через AJAX, после успешного запроса он будет сразу выполнен.

Или

Дождаться выполнения AJAX запроса

По умолчанию в JQuery AJAX запросы выполняются асинхронно. Т.е. запрос не задерживает выполнение программы пока ждет результатов, а работает параллельно. Простой пример:

var text = ''; $.ajax( < url: '/index.php', method: 'get', dataType: 'html', success: function(data)< text = data; >>); alert(text); /* Переменная будет пустая. */

Переменная text будет пустая, а не как ожидается текст который вернул index.php Чтобы включить синхронный режим нужно добавить параметр async: false .
Соответственно синхронный запрос будет вешать прогрузку страницы если код выполняется в страницы.

var text = ''; $.ajax( < url: '/index.php', method: 'get', dataType: 'html', async: false, success: function(data)< text = data; >>); alert(text); /* В переменной будет результат из index.php. */

Отправка HTTP заголовков

$.ajax(< url: '/index.php', method: 'get', dataType: 'html', headers: , success: function(data) < console.dir(data); >>);

В PHP они будут доступны в массиве $_SERVER , ключ массива переводится в верхний регистр с приставкой HTTP_ , например:

Обработка ошибок

Через параметр error задается callback-функция, которая будет вызвана в случаи если запрашиваемый ресурс отдал 404, 500 или другой код.

$.ajax(< url: '/index.php', method: 'get', dataType: 'json', success: function(data)< console.dir(data); >, error: function (jqXHR, exception) < if (jqXHR.status === 0) < alert('Not connect. Verify Network.'); >else if (jqXHR.status == 404) < alert('Requested page not found (404).'); >else if (jqXHR.status == 500) < alert('Internal Server Error (500).'); >else if (exception === 'parsererror') < alert('Requested JSON parse failed.'); >else if (exception === 'timeout') < alert('Time out error.'); >else if (exception === 'abort') < alert('Ajax request aborted.'); >else < alert('Uncaught Error. ' + jqXHR.responseText); >> >);

Комментарии 4

В примере Отправка формы через AJAX страница перезагружается. Видимо нужно добавить return false после $.ajax(<>);

$("#form").on("submit", function() $.ajax( url: '/handler.php', 
method: 'post',
dataType: 'html',
data: $(this).serialize(),
success: function(data) $('#message').html(data);
>
>);
return false;
>);
$("#form").on("submit", function(e). 
e.preventDefault();
>)

У меня вообще не работали POST запросы, особенно для меня, для начинающего было очень сложно, работали только GET, очень долго голову ломал почему так происходит. Нашёл пример на другом сайте, который работал долго сравнивал и думал почему так. Здесь пример не работает, а на другом сайте рабочий пример оказался.
Так вот:
$.ajax( url: ‘/index.php’,
method: ‘post’,
dataType: ‘html’,
data: ,
success: function(data) alert(data);
>
>);
Оказывается чтобы у меня заработали именно POST запросы надо было поменять строчку:
«method: ‘post’,» на:
«type: ‘post’,» и всё сразу заработало после этого. А я ведь ни один день ломал голову из-за этой ошибки!

Источник

jQuery Ajax GET and POST Requests

In this tutorial you will learn how to send and receive data from a web server through Ajax via HTTP GET or POST methods using jQuery.

jQuery $.get() and $.post() Methods

The jQuery’s $.get() and $.post() methods provide simple tools to send and retrieve data asynchronously from a web server. Both the methods are pretty much identical, apart from one major difference — the $.get() makes Ajax requests using the HTTP GET method, whereas the $.post() makes Ajax requests using the HTTP POST method.

The basic syntax of these methods can be given with:

The parameters in the above syntax have the following meaning:

  • The required URL parameter specifies the URL to which the request is sent.
  • The optional data parameter specifies a set of query string (i.e. key/value pairs) that is sent to the web server along with the request.
  • The optional success parameter is basically a callback function that is executed if the request succeeds. It is typically used to retrieve the returned data.

Note: The HTTP GET and POST methods are used to send request from a browser to a server. The main difference between these methods is the way in which the data is passed to the server. Check out the tutorial on GET and POST methods for the detailed explanation and comparison between these two methods.

Performing GET Request with AJAX using jQuery

The following example uses the jQuery $.get() method to make an Ajax request to the «date-time.php» file using HTTP GET method. It simply retrieves the date and time returned from the server and displays it in the browser without refreshing the page.

Example

         

Content of the result DIV box will be replaced by the server date and time

Here’s our «date-time.php» file that simply output the current date and time of the server.

Источник

Оцените статью