简体   繁体   中英

Ajax not working with javascript. What am I supposed to do?

This is my code where I call the Request for Ajax, than a simple input button which on onClick event send some data to a function called setValue();

This is the code (JS):
//request for ajax XML

<script type='text/javascript'>
function callAjax(){
var XMLObj = false;

if(window.XMLHttpRequest)
    XMLObj = new XMLHttpRequest();
else if(window.ActiveXObject)
    XMLObj = new ActiveXObject('Microsoft.XMLHTTP');

if(!XMLObj)
    return false;

return XMLObj;

}

//var for ajaxobject handle;

var objAjax = callAjax();

function setValue(value, id, num, item){
if(objAjax){
   if(objAjax.readyState == 4 || objAjax.readyState == 0){
       objAjax.open('POST', 'addview.php', true);
       objAjax.send('value=' + val + '&id='+id+'&num='+num+'&item='+item);
   }
}
}

//input for sending value to function setValue();

<input type='button' onClick='setValue(1, 2, 3, 4)' />

//and this is where I handle the sent data via php

<?php
if(!$_POST['value'] || !$_POST['id'] || !$_POST['num'] || !$_POST['item'])
    exit();

include('config.php');

$value = mysql_real_escape_string($_POST['value']);
$id = mysql_real_escape_string($_POST['id']);
$num = mysql_real_escape_string($_POST['num']);
$item = mysql_real_escape_string($_POST['item']);

mysql_query("UPDATE `window` SET window_val = window_val + ".$value." WHERE window_id = '".$id."' AND window_num = '".$num."' AND window_item = '".$item."' ") or die(mysql_error() );
mysql_close($con);
?>

The php script is working, I tried it with sending data manually ($_GET['']) and it's working. Also I checked the URL with alert('value='+value+'&id='+id...) and all variables are Ok, but the database won't be queried.

If you see, I don't add any function for response, reply from the server. I just only want to send those data and query the data base.

Thank you !

You may be missing

objAjax.setRequestHeader("Content-type","application/x-www-form-urlencoded");

Consider improving your function names: callAjax doesn't call Ajax, it returns a reference to the XHR object. Call it getXhr or something more like what it's actually doing.

If you're ok with jQuery, just call

function setValue(value, id, num, item){
    $.post('addview.php', 'value=' + val + '&id='+id+'&num='+num+'&item='+item);
    // or the cleaner version
    $.post('addview.php', {value: val, id: id, num: num, item:item});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM