Test this

Jquery ajax call from javascript to PHP

There seems to be a problem with the code I have for calling php from javascript with jquery ajax. The ajax call seems to be successful but I don’t get the correct information returned from the php function. In the php function I create a SQL query. I send back the query as a reponse to debug it before performing a delete query. Here is the HTML for the div to show the query.

Here is the jquery ajax call. There are two variables being sent to the PHP function: nodeid for node to be delete, and option delete for the function.

function deleteitem() < //get selected node var selectnod = getCookie('pnodid'); //define php info and make ajax call $.ajax(< url: "uptree.php", type: "POST", data: < node: selectnod, option: "delete" >, cache: false, success: function (response) < $('#thenode').html(response); >>); > 
 $dbco = mysql_connect('localhost', 'root', 'mmowebdb'); if (!$dbco) < die('Could not connect: ' . mysql_error()); >mysql_select_db("pagelinks", $dbco); $sql = "DELETE FROM dtree_table WHERE nid='$node'"; return $sql; > ?> 

Should be straightforward but this ajax call returns an empty string and causes the div in the HTML to disappear. This is the first time I use ajax in an actual project. The problem must be easy to find for someone who knows what ajax really does. Can you tell the problems?

Читайте также:  Проверка нажатия клавиш python keyboard

i just wonder why you have to get the selected node via a cookie. are you sure the cookie is written when you send your ajax request? (if you need to have that cookie, why you dont read it out via php?)

4 Answers 4

I found the answer! Thanks to all of you who had suggestions about the SQL call. But here is the actual answer to my question.

There are four steps in making an ajax Javascript to PHP call. The first two steps happen in the Javascript. The other two steps happen in the PHP.

Step 1. In Javascript decide what variables are needed in the PHP function, retrieve them.

Step 2. Make the ajax call to the PHP function. jquery has a convenient way of passing values to PHP. You have a an array of name-value pairs like this in the data item for the ajax call.

Step 3. Have your PHP function ready in a PHP file. Write the function like this.

function updatetree($node, $option)  

Step 4. Echo a call to the php function within that PHP file.

With these four steps you should have a succesful call to PHP and be able to return information to javascript from the PHP function.

Here is the javascript function.

function deleteitem() < //Get selected node to send to PHP function var selectnod = getCookie('pnodid'); //Define php info, specify name of PHP file NOT PHP function //Note that by loading the PHP file you will probably execute any code in that file //that does not require a function call //Send PHP variables in the data item, and make ajax call //On success perform any action that you want, such as load a div here called thenode $.ajax(< url: "uptree.php", type: "POST", data: < node: selectnod, option: "delete" >, cache: false, success: function (response) < $('#thenode').html(response); >>); > 

Here is the PHP file uptree.PHP. It has a function defined, called updatetree. It also has an echo statement to call that function. This just seems to be the way to cause the function to run. Ajax itself doesn't call the function.

 $dbco = mysql_connect('localhost', 'root', 'mmowebdb'); if (!$dbco) < die('Could not connect: ' . mysql_error()); >mysql_select_db("pagelinks", $dbco); $sql = ''; switch($option) < case 'delete': $sql = "DELETE FROM dtree_table WHERE nid='$node'"; break; case 'add': list($pagename, $address) = explode(",", $page); $pagename = trim($pagename); $address = trim($address); $sql = "INSERT INTO dtree_table (nid, pid, name, url) values (NULL, ".$node.", '".$pagename."', '".$address."')"; break; case 'update': break; >if (!empty($sql)) return $sql; > //echo statement to run function, variables sent by ajax are retrieved with $_REQUEST //they could have also been retrieved with $_GET or $_POST echo updatetree(trim($_REQUEST['node']),trim($_REQUEST['option']),trim($_REQUEST['page'])); ?> 

So to recap. Javascript gets variables, makes ajax call to PHP file. Ajax loads PHP file which contains echo statement that causes PHP function to run. That PHP function is defined in that same file. The function return statement sends information back to javascript through ajax. Javascript does something with that information, e.g. load it into a div on the HTML page.

Источник

Примеры отправки 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'," и всё сразу заработало после этого. А я ведь ни один день ломал голову из-за этой ошибки!

Источник

How to ajax POST to php

I can't seem to figure out how to use ajax to post. I made a silly form to try it out and even after having cut it all the way down to just two values, still can't get anything to work. My html is this:

   Test this< /title> 
First Name:
Last Name:
function postStuff() < // Create our XMLHttpRequest object var hr = new XMLHttpRequest(); // Create some variables we need to send to our PHP file var url = "processForm.php"; var fn = document.getElementById("fname").value; var ln = document.getElementById("lname").value; var vars = "firstname="+fn+"&lastname="+ln; hr.open("POST", url, true); hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // Access the onreadystatechange event for the XMLHttpRequest object hr.onreadystatechange = function() < if(hr.readyState == 4 && hr.status == 200) < var return_data = hr.responseText; document.getElementById("status").innerHTML = return_data; >> // Send the data to PHP now. and wait for response to update the status div hr.send(vars); // Actually execute the request document.getElementById("status").innerHTML = "processing. "; > 

I can't find anything wrong in firebug or in chrome's toolsy thingies.. Can anybody who me what I'm doing wrong?

You send "application/x-www-form-urlencoded" as content-type but you're not encoding your values. There are ways how this can be automated but if you just pass your HTTP payload string to .send() you need to URL encode your values.

6 Answers 6

The whole problem is caused by the fact that you are both submitting the form and performing an AJAX call! status is for sure updated, but in the same moment the page is refreshed (notice that the -values disappear)

Simply avoid the form submit by altering the markup,

and your code works. Or dont use a form at all. It is to no use when you are AJAXing anyway.

update

I reproduced the whole scenario before answering :

     
First Name:
Last Name:

What if I'm going to be validating the form using a different function before actually submitting it to php? would I need to to basically just include this function within it if the form passes validation?

Perform the validation as the first thing in postStuff , or call your validation routine from there. If it not validates, abort. That is just one solution.

Or make a function submit() , which first calls validate() , and if that successes then calls postStuff() .

Well, I appreciate everybody's response so far. I'm very grateful. But, despite having tried everybody's suggestions short of using jquery (nothing against it, I just want to be really proficient with javascript before I start using libraries). I've still not gotten the status div to show the variables as I've specified in the code. Now, it sends the variables to the url.

And I like you are not falling in the jQuery-trap. Using jQuery myself, but that is really not the answer to your question.

 
First Name:
Last Name:

The page refreshes from the form submit as far as I can see. You don't need to use a form if you're using ajax.

Also read: Why is using onClick() in HTML a bad practice? since you're enclosing the post in a function anyway.

EDIT: I just noticed your title and head tags are broken in the source you've put up.

Not exactly. It is not "interrupts the ajax request", submit is just the last in the chain of execution. Both are executed very well. You can see that by yourself by reproducing the setup and insert console.log's / alerts.

I think David got the answer before me 🙂 Glad to see it worked out for you! As David mentioned, good to see you learning JS properly before jumping onto jQuery.

Here's how I do it:

Then you can call this function that will call (in my case) queryDB.php script.

function queryDB(db,query,doAfter)< $.ajax(< type: 'POST', data: < host: "localhost", port: "5432", db: db, usr: "guest", pass: "guest", statemnt: query >, url: 'scripts/php/queryDB.php', dataType: 'json', async: false, success: function(result)< // call the function that handles the response/results doAfterQuery_maps(result,doAfter); >, error: function() < window.alert("Wrong query 'queryDB.php': " + query); >>); >; 

Send post to test.php in the same hierarchy and accept the result in html variable

$.ajax( < type: "POST", url: "test.php", data: , success: function(html) < alert(html); >>); 

In PHP of the recipient, specify it as follows

Perhaps it's best for you to use a library like jquery and then you can do something like : $('form').submit(function()<$.post('detinatnion', $('form').serialize());>); but to answer your question since you have a reason for using pure js then:

function postStuff() < var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"] //activeX versions to check for in IE if (window.ActiveXObject)< //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken) for (var i=0; icatch(e) < //suppress error >> > else if (window.XMLHttpRequest) // if Mozilla, Safari etc mypostrequest = new XMLHttpRequest(); else return false; mypostrequest.onreadystatechange=function() < if (mypostrequest.readyState==4)< if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1)< document.getElementById("result").innerHTML=mypostrequest.responseText; >else < alert("An error has occured making the request"); >> > var fname=encodeURIComponent(document.getElementById("fname").value); var lname=encodeURIComponent(document.getElementById("lname").value); var parameters="fname="+fname+"&lname="+lname; mypostrequest.open("POST", "destination.php", true); mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); mypostrequest.send(parameters); 

Again my recommendation to you is to learn js with a library like jquery, because by the time you learn how to do these stuff, these libraries, hardware and everything will be so fast that javascript code like this will become useless for practical every day use.

Источник

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